aframe-master.js 2.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972
  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 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})({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 TWEEN = TWEEN || (function () {
  12. var _tweens = [];
  13. return {
  14. getAll: function () {
  15. return _tweens;
  16. },
  17. removeAll: function () {
  18. _tweens = [];
  19. },
  20. add: function (tween) {
  21. _tweens.push(tween);
  22. },
  23. remove: function (tween) {
  24. var i = _tweens.indexOf(tween);
  25. if (i !== -1) {
  26. _tweens.splice(i, 1);
  27. }
  28. },
  29. update: function (time, preserve) {
  30. if (_tweens.length === 0) {
  31. return false;
  32. }
  33. var i = 0;
  34. time = time !== undefined ? time : TWEEN.now();
  35. while (i < _tweens.length) {
  36. if (_tweens[i].update(time) || preserve) {
  37. i++;
  38. } else {
  39. _tweens.splice(i, 1);
  40. }
  41. }
  42. return true;
  43. }
  44. };
  45. })();
  46. // Include a performance.now polyfill.
  47. // In node.js, use process.hrtime.
  48. if (typeof (window) === 'undefined' && typeof (process) !== 'undefined') {
  49. TWEEN.now = function () {
  50. var time = process.hrtime();
  51. // Convert [seconds, nanoseconds] to milliseconds.
  52. return time[0] * 1000 + time[1] / 1000000;
  53. };
  54. }
  55. // In a browser, use window.performance.now if it is available.
  56. else if (typeof (window) !== 'undefined' &&
  57. window.performance !== undefined &&
  58. window.performance.now !== undefined) {
  59. // This must be bound, because directly assigning this function
  60. // leads to an invocation exception in Chrome.
  61. TWEEN.now = window.performance.now.bind(window.performance);
  62. }
  63. // Use Date.now if it is available.
  64. else if (Date.now !== undefined) {
  65. TWEEN.now = Date.now;
  66. }
  67. // Otherwise, use 'new Date().getTime()'.
  68. else {
  69. TWEEN.now = function () {
  70. return new Date().getTime();
  71. };
  72. }
  73. TWEEN.Tween = function (object) {
  74. var _object = object;
  75. var _valuesStart = {};
  76. var _valuesEnd = {};
  77. var _valuesStartRepeat = {};
  78. var _duration = 1000;
  79. var _repeat = 0;
  80. var _repeatDelayTime;
  81. var _yoyo = false;
  82. var _isPlaying = false;
  83. var _reversed = false;
  84. var _delayTime = 0;
  85. var _startTime = null;
  86. var _easingFunction = TWEEN.Easing.Linear.None;
  87. var _interpolationFunction = TWEEN.Interpolation.Linear;
  88. var _chainedTweens = [];
  89. var _onStartCallback = null;
  90. var _onStartCallbackFired = false;
  91. var _onUpdateCallback = null;
  92. var _onCompleteCallback = null;
  93. var _onStopCallback = null;
  94. this.to = function (properties, duration) {
  95. _valuesEnd = properties;
  96. if (duration !== undefined) {
  97. _duration = duration;
  98. }
  99. return this;
  100. };
  101. this.start = function (time) {
  102. TWEEN.add(this);
  103. _isPlaying = true;
  104. _onStartCallbackFired = false;
  105. _startTime = time !== undefined ? time : TWEEN.now();
  106. _startTime += _delayTime;
  107. for (var property in _valuesEnd) {
  108. // Check if an Array was provided as property value
  109. if (_valuesEnd[property] instanceof Array) {
  110. if (_valuesEnd[property].length === 0) {
  111. continue;
  112. }
  113. // Create a local copy of the Array with the start value at the front
  114. _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]);
  115. }
  116. // If `to()` specifies a property that doesn't exist in the source object,
  117. // we should not set that property in the object
  118. if (_object[property] === undefined) {
  119. continue;
  120. }
  121. // Save the starting value.
  122. _valuesStart[property] = _object[property];
  123. if ((_valuesStart[property] instanceof Array) === false) {
  124. _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings
  125. }
  126. _valuesStartRepeat[property] = _valuesStart[property] || 0;
  127. }
  128. return this;
  129. };
  130. this.stop = function () {
  131. if (!_isPlaying) {
  132. return this;
  133. }
  134. TWEEN.remove(this);
  135. _isPlaying = false;
  136. if (_onStopCallback !== null) {
  137. _onStopCallback.call(_object, _object);
  138. }
  139. this.stopChainedTweens();
  140. return this;
  141. };
  142. this.end = function () {
  143. this.update(_startTime + _duration);
  144. return this;
  145. };
  146. this.stopChainedTweens = function () {
  147. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  148. _chainedTweens[i].stop();
  149. }
  150. };
  151. this.delay = function (amount) {
  152. _delayTime = amount;
  153. return this;
  154. };
  155. this.repeat = function (times) {
  156. _repeat = times;
  157. return this;
  158. };
  159. this.repeatDelay = function (amount) {
  160. _repeatDelayTime = amount;
  161. return this;
  162. };
  163. this.yoyo = function (yoyo) {
  164. _yoyo = yoyo;
  165. return this;
  166. };
  167. this.easing = function (easing) {
  168. _easingFunction = easing;
  169. return this;
  170. };
  171. this.interpolation = function (interpolation) {
  172. _interpolationFunction = interpolation;
  173. return this;
  174. };
  175. this.chain = function () {
  176. _chainedTweens = arguments;
  177. return this;
  178. };
  179. this.onStart = function (callback) {
  180. _onStartCallback = callback;
  181. return this;
  182. };
  183. this.onUpdate = function (callback) {
  184. _onUpdateCallback = callback;
  185. return this;
  186. };
  187. this.onComplete = function (callback) {
  188. _onCompleteCallback = callback;
  189. return this;
  190. };
  191. this.onStop = function (callback) {
  192. _onStopCallback = callback;
  193. return this;
  194. };
  195. this.update = function (time) {
  196. var property;
  197. var elapsed;
  198. var value;
  199. if (time < _startTime) {
  200. return true;
  201. }
  202. if (_onStartCallbackFired === false) {
  203. if (_onStartCallback !== null) {
  204. _onStartCallback.call(_object, _object);
  205. }
  206. _onStartCallbackFired = true;
  207. }
  208. elapsed = (time - _startTime) / _duration;
  209. elapsed = elapsed > 1 ? 1 : elapsed;
  210. value = _easingFunction(elapsed);
  211. for (property in _valuesEnd) {
  212. // Don't update properties that do not exist in the source object
  213. if (_valuesStart[property] === undefined) {
  214. continue;
  215. }
  216. var start = _valuesStart[property] || 0;
  217. var end = _valuesEnd[property];
  218. if (end instanceof Array) {
  219. _object[property] = _interpolationFunction(end, value);
  220. } else {
  221. // Parses relative end values with start as base (e.g.: +10, -3)
  222. if (typeof (end) === 'string') {
  223. if (end.charAt(0) === '+' || end.charAt(0) === '-') {
  224. end = start + parseFloat(end);
  225. } else {
  226. end = parseFloat(end);
  227. }
  228. }
  229. // Protect against non numeric properties.
  230. if (typeof (end) === 'number') {
  231. _object[property] = start + (end - start) * value;
  232. }
  233. }
  234. }
  235. if (_onUpdateCallback !== null) {
  236. _onUpdateCallback.call(_object, value);
  237. }
  238. if (elapsed === 1) {
  239. if (_repeat > 0) {
  240. if (isFinite(_repeat)) {
  241. _repeat--;
  242. }
  243. // Reassign starting values, restart by making startTime = now
  244. for (property in _valuesStartRepeat) {
  245. if (typeof (_valuesEnd[property]) === 'string') {
  246. _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property]);
  247. }
  248. if (_yoyo) {
  249. var tmp = _valuesStartRepeat[property];
  250. _valuesStartRepeat[property] = _valuesEnd[property];
  251. _valuesEnd[property] = tmp;
  252. }
  253. _valuesStart[property] = _valuesStartRepeat[property];
  254. }
  255. if (_yoyo) {
  256. _reversed = !_reversed;
  257. }
  258. if (_repeatDelayTime !== undefined) {
  259. _startTime = time + _repeatDelayTime;
  260. } else {
  261. _startTime = time + _delayTime;
  262. }
  263. return true;
  264. } else {
  265. if (_onCompleteCallback !== null) {
  266. _onCompleteCallback.call(_object, _object);
  267. }
  268. for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) {
  269. // Make the chained tweens start exactly at the time they should,
  270. // even if the `update()` method was called way past the duration of the tween
  271. _chainedTweens[i].start(_startTime + _duration);
  272. }
  273. return false;
  274. }
  275. }
  276. return true;
  277. };
  278. };
  279. TWEEN.Easing = {
  280. Linear: {
  281. None: function (k) {
  282. return k;
  283. }
  284. },
  285. Quadratic: {
  286. In: function (k) {
  287. return k * k;
  288. },
  289. Out: function (k) {
  290. return k * (2 - k);
  291. },
  292. InOut: function (k) {
  293. if ((k *= 2) < 1) {
  294. return 0.5 * k * k;
  295. }
  296. return - 0.5 * (--k * (k - 2) - 1);
  297. }
  298. },
  299. Cubic: {
  300. In: function (k) {
  301. return k * k * k;
  302. },
  303. Out: function (k) {
  304. return --k * k * k + 1;
  305. },
  306. InOut: function (k) {
  307. if ((k *= 2) < 1) {
  308. return 0.5 * k * k * k;
  309. }
  310. return 0.5 * ((k -= 2) * k * k + 2);
  311. }
  312. },
  313. Quartic: {
  314. In: function (k) {
  315. return k * k * k * k;
  316. },
  317. Out: function (k) {
  318. return 1 - (--k * k * k * k);
  319. },
  320. InOut: function (k) {
  321. if ((k *= 2) < 1) {
  322. return 0.5 * k * k * k * k;
  323. }
  324. return - 0.5 * ((k -= 2) * k * k * k - 2);
  325. }
  326. },
  327. Quintic: {
  328. In: function (k) {
  329. return k * k * k * k * k;
  330. },
  331. Out: function (k) {
  332. return --k * k * k * k * k + 1;
  333. },
  334. InOut: function (k) {
  335. if ((k *= 2) < 1) {
  336. return 0.5 * k * k * k * k * k;
  337. }
  338. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  339. }
  340. },
  341. Sinusoidal: {
  342. In: function (k) {
  343. return 1 - Math.cos(k * Math.PI / 2);
  344. },
  345. Out: function (k) {
  346. return Math.sin(k * Math.PI / 2);
  347. },
  348. InOut: function (k) {
  349. return 0.5 * (1 - Math.cos(Math.PI * k));
  350. }
  351. },
  352. Exponential: {
  353. In: function (k) {
  354. return k === 0 ? 0 : Math.pow(1024, k - 1);
  355. },
  356. Out: function (k) {
  357. return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k);
  358. },
  359. InOut: function (k) {
  360. if (k === 0) {
  361. return 0;
  362. }
  363. if (k === 1) {
  364. return 1;
  365. }
  366. if ((k *= 2) < 1) {
  367. return 0.5 * Math.pow(1024, k - 1);
  368. }
  369. return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2);
  370. }
  371. },
  372. Circular: {
  373. In: function (k) {
  374. return 1 - Math.sqrt(1 - k * k);
  375. },
  376. Out: function (k) {
  377. return Math.sqrt(1 - (--k * k));
  378. },
  379. InOut: function (k) {
  380. if ((k *= 2) < 1) {
  381. return - 0.5 * (Math.sqrt(1 - k * k) - 1);
  382. }
  383. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  384. }
  385. },
  386. Elastic: {
  387. In: function (k) {
  388. if (k === 0) {
  389. return 0;
  390. }
  391. if (k === 1) {
  392. return 1;
  393. }
  394. return -Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  395. },
  396. Out: function (k) {
  397. if (k === 0) {
  398. return 0;
  399. }
  400. if (k === 1) {
  401. return 1;
  402. }
  403. return Math.pow(2, -10 * k) * Math.sin((k - 0.1) * 5 * Math.PI) + 1;
  404. },
  405. InOut: function (k) {
  406. if (k === 0) {
  407. return 0;
  408. }
  409. if (k === 1) {
  410. return 1;
  411. }
  412. k *= 2;
  413. if (k < 1) {
  414. return -0.5 * Math.pow(2, 10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI);
  415. }
  416. return 0.5 * Math.pow(2, -10 * (k - 1)) * Math.sin((k - 1.1) * 5 * Math.PI) + 1;
  417. }
  418. },
  419. Back: {
  420. In: function (k) {
  421. var s = 1.70158;
  422. return k * k * ((s + 1) * k - s);
  423. },
  424. Out: function (k) {
  425. var s = 1.70158;
  426. return --k * k * ((s + 1) * k + s) + 1;
  427. },
  428. InOut: function (k) {
  429. var s = 1.70158 * 1.525;
  430. if ((k *= 2) < 1) {
  431. return 0.5 * (k * k * ((s + 1) * k - s));
  432. }
  433. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  434. }
  435. },
  436. Bounce: {
  437. In: function (k) {
  438. return 1 - TWEEN.Easing.Bounce.Out(1 - k);
  439. },
  440. Out: function (k) {
  441. if (k < (1 / 2.75)) {
  442. return 7.5625 * k * k;
  443. } else if (k < (2 / 2.75)) {
  444. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  445. } else if (k < (2.5 / 2.75)) {
  446. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  447. } else {
  448. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  449. }
  450. },
  451. InOut: function (k) {
  452. if (k < 0.5) {
  453. return TWEEN.Easing.Bounce.In(k * 2) * 0.5;
  454. }
  455. return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5;
  456. }
  457. }
  458. };
  459. TWEEN.Interpolation = {
  460. Linear: function (v, k) {
  461. var m = v.length - 1;
  462. var f = m * k;
  463. var i = Math.floor(f);
  464. var fn = TWEEN.Interpolation.Utils.Linear;
  465. if (k < 0) {
  466. return fn(v[0], v[1], f);
  467. }
  468. if (k > 1) {
  469. return fn(v[m], v[m - 1], m - f);
  470. }
  471. return fn(v[i], v[i + 1 > m ? m : i + 1], f - i);
  472. },
  473. Bezier: function (v, k) {
  474. var b = 0;
  475. var n = v.length - 1;
  476. var pw = Math.pow;
  477. var bn = TWEEN.Interpolation.Utils.Bernstein;
  478. for (var i = 0; i <= n; i++) {
  479. b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i);
  480. }
  481. return b;
  482. },
  483. CatmullRom: function (v, k) {
  484. var m = v.length - 1;
  485. var f = m * k;
  486. var i = Math.floor(f);
  487. var fn = TWEEN.Interpolation.Utils.CatmullRom;
  488. if (v[0] === v[m]) {
  489. if (k < 0) {
  490. i = Math.floor(f = m * (1 + k));
  491. }
  492. return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  493. } else {
  494. if (k < 0) {
  495. return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]);
  496. }
  497. if (k > 1) {
  498. return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  499. }
  500. 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);
  501. }
  502. },
  503. Utils: {
  504. Linear: function (p0, p1, t) {
  505. return (p1 - p0) * t + p0;
  506. },
  507. Bernstein: function (n, i) {
  508. var fc = TWEEN.Interpolation.Utils.Factorial;
  509. return fc(n) / fc(i) / fc(n - i);
  510. },
  511. Factorial: (function () {
  512. var a = [1];
  513. return function (n) {
  514. var s = 1;
  515. if (a[n]) {
  516. return a[n];
  517. }
  518. for (var i = n; i > 1; i--) {
  519. s *= i;
  520. }
  521. a[n] = s;
  522. return s;
  523. };
  524. })(),
  525. CatmullRom: function (p0, p1, p2, p3, t) {
  526. var v0 = (p2 - p0) * 0.5;
  527. var v1 = (p3 - p1) * 0.5;
  528. var t2 = t * t;
  529. var t3 = t * t2;
  530. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  531. }
  532. }
  533. };
  534. // UMD (Universal Module Definition)
  535. (function (root) {
  536. if (typeof define === 'function' && define.amd) {
  537. // AMD
  538. define([], function () {
  539. return TWEEN;
  540. });
  541. } else if (typeof module !== 'undefined' && typeof exports === 'object') {
  542. // Node.js
  543. module.exports = TWEEN;
  544. } else if (root !== undefined) {
  545. // Global variable
  546. root.TWEEN = TWEEN;
  547. }
  548. })(this);
  549. }).call(this,_dereq_('_process'))
  550. },{"_process":33}],2:[function(_dereq_,module,exports){
  551. var str = Object.prototype.toString
  552. module.exports = anArray
  553. function anArray(arr) {
  554. return (
  555. arr.BYTES_PER_ELEMENT
  556. && str.call(arr.buffer) === '[object ArrayBuffer]'
  557. || Array.isArray(arr)
  558. )
  559. }
  560. },{}],3:[function(_dereq_,module,exports){
  561. module.exports = function numtype(num, def) {
  562. return typeof num === 'number'
  563. ? num
  564. : (typeof def === 'number' ? def : 0)
  565. }
  566. },{}],4:[function(_dereq_,module,exports){
  567. 'use strict'
  568. exports.byteLength = byteLength
  569. exports.toByteArray = toByteArray
  570. exports.fromByteArray = fromByteArray
  571. var lookup = []
  572. var revLookup = []
  573. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  574. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  575. for (var i = 0, len = code.length; i < len; ++i) {
  576. lookup[i] = code[i]
  577. revLookup[code.charCodeAt(i)] = i
  578. }
  579. revLookup['-'.charCodeAt(0)] = 62
  580. revLookup['_'.charCodeAt(0)] = 63
  581. function placeHoldersCount (b64) {
  582. var len = b64.length
  583. if (len % 4 > 0) {
  584. throw new Error('Invalid string. Length must be a multiple of 4')
  585. }
  586. // the number of equal signs (place holders)
  587. // if there are two placeholders, than the two characters before it
  588. // represent one byte
  589. // if there is only one, then the three characters before it represent 2 bytes
  590. // this is just a cheap hack to not do indexOf twice
  591. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  592. }
  593. function byteLength (b64) {
  594. // base64 is 4/3 + up to two characters of the original data
  595. return b64.length * 3 / 4 - placeHoldersCount(b64)
  596. }
  597. function toByteArray (b64) {
  598. var i, j, l, tmp, placeHolders, arr
  599. var len = b64.length
  600. placeHolders = placeHoldersCount(b64)
  601. arr = new Arr(len * 3 / 4 - placeHolders)
  602. // if there are placeholders, only get up to the last complete 4 chars
  603. l = placeHolders > 0 ? len - 4 : len
  604. var L = 0
  605. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  606. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  607. arr[L++] = (tmp >> 16) & 0xFF
  608. arr[L++] = (tmp >> 8) & 0xFF
  609. arr[L++] = tmp & 0xFF
  610. }
  611. if (placeHolders === 2) {
  612. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  613. arr[L++] = tmp & 0xFF
  614. } else if (placeHolders === 1) {
  615. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  616. arr[L++] = (tmp >> 8) & 0xFF
  617. arr[L++] = tmp & 0xFF
  618. }
  619. return arr
  620. }
  621. function tripletToBase64 (num) {
  622. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  623. }
  624. function encodeChunk (uint8, start, end) {
  625. var tmp
  626. var output = []
  627. for (var i = start; i < end; i += 3) {
  628. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  629. output.push(tripletToBase64(tmp))
  630. }
  631. return output.join('')
  632. }
  633. function fromByteArray (uint8) {
  634. var tmp
  635. var len = uint8.length
  636. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  637. var output = ''
  638. var parts = []
  639. var maxChunkLength = 16383 // must be multiple of 3
  640. // go through the array every three bytes, we'll deal with trailing stuff later
  641. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  642. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  643. }
  644. // pad the end with zeros, but make sure to not forget the extra bytes
  645. if (extraBytes === 1) {
  646. tmp = uint8[len - 1]
  647. output += lookup[tmp >> 2]
  648. output += lookup[(tmp << 4) & 0x3F]
  649. output += '=='
  650. } else if (extraBytes === 2) {
  651. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  652. output += lookup[tmp >> 10]
  653. output += lookup[(tmp >> 4) & 0x3F]
  654. output += lookup[(tmp << 2) & 0x3F]
  655. output += '='
  656. }
  657. parts.push(output)
  658. return parts.join('')
  659. }
  660. },{}],5:[function(_dereq_,module,exports){
  661. 'use strict';
  662. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  663. module.exports = {
  664. // Create a <link> tag with optional data attributes
  665. createLink: function(href, attributes) {
  666. var head = document.head || document.getElementsByTagName('head')[0];
  667. var link = document.createElement('link');
  668. link.href = href;
  669. link.rel = 'stylesheet';
  670. for (var key in attributes) {
  671. if ( ! attributes.hasOwnProperty(key)) {
  672. continue;
  673. }
  674. var value = attributes[key];
  675. link.setAttribute('data-' + key, value);
  676. }
  677. head.appendChild(link);
  678. },
  679. // Create a <style> tag with optional data attributes
  680. createStyle: function(cssText, attributes) {
  681. var head = document.head || document.getElementsByTagName('head')[0],
  682. style = document.createElement('style');
  683. style.type = 'text/css';
  684. for (var key in attributes) {
  685. if ( ! attributes.hasOwnProperty(key)) {
  686. continue;
  687. }
  688. var value = attributes[key];
  689. style.setAttribute('data-' + key, value);
  690. }
  691. if (style.sheet) { // for jsdom and IE9+
  692. style.innerHTML = cssText;
  693. style.sheet.cssText = cssText;
  694. head.appendChild(style);
  695. } else if (style.styleSheet) { // for IE8 and below
  696. head.appendChild(style);
  697. style.styleSheet.cssText = cssText;
  698. } else { // for Chrome, Firefox, and Safari
  699. style.appendChild(document.createTextNode(cssText));
  700. head.appendChild(style);
  701. }
  702. }
  703. };
  704. },{}],6:[function(_dereq_,module,exports){
  705. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  706. module.exports = function (a, b) {
  707. if (!Buffer.isBuffer(a)) return undefined;
  708. if (!Buffer.isBuffer(b)) return undefined;
  709. if (typeof a.equals === 'function') return a.equals(b);
  710. if (a.length !== b.length) return false;
  711. for (var i = 0; i < a.length; i++) {
  712. if (a[i] !== b[i]) return false;
  713. }
  714. return true;
  715. };
  716. },{"buffer":7}],7:[function(_dereq_,module,exports){
  717. (function (global){
  718. /*!
  719. * The buffer module from node.js, for the browser.
  720. *
  721. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  722. * @license MIT
  723. */
  724. /* eslint-disable no-proto */
  725. 'use strict'
  726. var base64 = _dereq_('base64-js')
  727. var ieee754 = _dereq_('ieee754')
  728. var isArray = _dereq_('isarray')
  729. exports.Buffer = Buffer
  730. exports.SlowBuffer = SlowBuffer
  731. exports.INSPECT_MAX_BYTES = 50
  732. /**
  733. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  734. * === true Use Uint8Array implementation (fastest)
  735. * === false Use Object implementation (most compatible, even IE6)
  736. *
  737. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  738. * Opera 11.6+, iOS 4.2+.
  739. *
  740. * Due to various browser bugs, sometimes the Object implementation will be used even
  741. * when the browser supports typed arrays.
  742. *
  743. * Note:
  744. *
  745. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  746. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  747. *
  748. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  749. *
  750. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  751. * incorrect length in some situations.
  752. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  753. * get the Object implementation, which is slower but behaves correctly.
  754. */
  755. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  756. ? global.TYPED_ARRAY_SUPPORT
  757. : typedArraySupport()
  758. /*
  759. * Export kMaxLength after typed array support is determined.
  760. */
  761. exports.kMaxLength = kMaxLength()
  762. function typedArraySupport () {
  763. try {
  764. var arr = new Uint8Array(1)
  765. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  766. return arr.foo() === 42 && // typed array instances can be augmented
  767. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  768. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  769. } catch (e) {
  770. return false
  771. }
  772. }
  773. function kMaxLength () {
  774. return Buffer.TYPED_ARRAY_SUPPORT
  775. ? 0x7fffffff
  776. : 0x3fffffff
  777. }
  778. function createBuffer (that, length) {
  779. if (kMaxLength() < length) {
  780. throw new RangeError('Invalid typed array length')
  781. }
  782. if (Buffer.TYPED_ARRAY_SUPPORT) {
  783. // Return an augmented `Uint8Array` instance, for best performance
  784. that = new Uint8Array(length)
  785. that.__proto__ = Buffer.prototype
  786. } else {
  787. // Fallback: Return an object instance of the Buffer class
  788. if (that === null) {
  789. that = new Buffer(length)
  790. }
  791. that.length = length
  792. }
  793. return that
  794. }
  795. /**
  796. * The Buffer constructor returns instances of `Uint8Array` that have their
  797. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  798. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  799. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  800. * returns a single octet.
  801. *
  802. * The `Uint8Array` prototype remains unmodified.
  803. */
  804. function Buffer (arg, encodingOrOffset, length) {
  805. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  806. return new Buffer(arg, encodingOrOffset, length)
  807. }
  808. // Common case.
  809. if (typeof arg === 'number') {
  810. if (typeof encodingOrOffset === 'string') {
  811. throw new Error(
  812. 'If encoding is specified then the first argument must be a string'
  813. )
  814. }
  815. return allocUnsafe(this, arg)
  816. }
  817. return from(this, arg, encodingOrOffset, length)
  818. }
  819. Buffer.poolSize = 8192 // not used by this implementation
  820. // TODO: Legacy, not needed anymore. Remove in next major version.
  821. Buffer._augment = function (arr) {
  822. arr.__proto__ = Buffer.prototype
  823. return arr
  824. }
  825. function from (that, value, encodingOrOffset, length) {
  826. if (typeof value === 'number') {
  827. throw new TypeError('"value" argument must not be a number')
  828. }
  829. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  830. return fromArrayBuffer(that, value, encodingOrOffset, length)
  831. }
  832. if (typeof value === 'string') {
  833. return fromString(that, value, encodingOrOffset)
  834. }
  835. return fromObject(that, value)
  836. }
  837. /**
  838. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  839. * if value is a number.
  840. * Buffer.from(str[, encoding])
  841. * Buffer.from(array)
  842. * Buffer.from(buffer)
  843. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  844. **/
  845. Buffer.from = function (value, encodingOrOffset, length) {
  846. return from(null, value, encodingOrOffset, length)
  847. }
  848. if (Buffer.TYPED_ARRAY_SUPPORT) {
  849. Buffer.prototype.__proto__ = Uint8Array.prototype
  850. Buffer.__proto__ = Uint8Array
  851. if (typeof Symbol !== 'undefined' && Symbol.species &&
  852. Buffer[Symbol.species] === Buffer) {
  853. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  854. Object.defineProperty(Buffer, Symbol.species, {
  855. value: null,
  856. configurable: true
  857. })
  858. }
  859. }
  860. function assertSize (size) {
  861. if (typeof size !== 'number') {
  862. throw new TypeError('"size" argument must be a number')
  863. } else if (size < 0) {
  864. throw new RangeError('"size" argument must not be negative')
  865. }
  866. }
  867. function alloc (that, size, fill, encoding) {
  868. assertSize(size)
  869. if (size <= 0) {
  870. return createBuffer(that, size)
  871. }
  872. if (fill !== undefined) {
  873. // Only pay attention to encoding if it's a string. This
  874. // prevents accidentally sending in a number that would
  875. // be interpretted as a start offset.
  876. return typeof encoding === 'string'
  877. ? createBuffer(that, size).fill(fill, encoding)
  878. : createBuffer(that, size).fill(fill)
  879. }
  880. return createBuffer(that, size)
  881. }
  882. /**
  883. * Creates a new filled Buffer instance.
  884. * alloc(size[, fill[, encoding]])
  885. **/
  886. Buffer.alloc = function (size, fill, encoding) {
  887. return alloc(null, size, fill, encoding)
  888. }
  889. function allocUnsafe (that, size) {
  890. assertSize(size)
  891. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  892. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  893. for (var i = 0; i < size; ++i) {
  894. that[i] = 0
  895. }
  896. }
  897. return that
  898. }
  899. /**
  900. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  901. * */
  902. Buffer.allocUnsafe = function (size) {
  903. return allocUnsafe(null, size)
  904. }
  905. /**
  906. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  907. */
  908. Buffer.allocUnsafeSlow = function (size) {
  909. return allocUnsafe(null, size)
  910. }
  911. function fromString (that, string, encoding) {
  912. if (typeof encoding !== 'string' || encoding === '') {
  913. encoding = 'utf8'
  914. }
  915. if (!Buffer.isEncoding(encoding)) {
  916. throw new TypeError('"encoding" must be a valid string encoding')
  917. }
  918. var length = byteLength(string, encoding) | 0
  919. that = createBuffer(that, length)
  920. var actual = that.write(string, encoding)
  921. if (actual !== length) {
  922. // Writing a hex string, for example, that contains invalid characters will
  923. // cause everything after the first invalid character to be ignored. (e.g.
  924. // 'abxxcd' will be treated as 'ab')
  925. that = that.slice(0, actual)
  926. }
  927. return that
  928. }
  929. function fromArrayLike (that, array) {
  930. var length = array.length < 0 ? 0 : checked(array.length) | 0
  931. that = createBuffer(that, length)
  932. for (var i = 0; i < length; i += 1) {
  933. that[i] = array[i] & 255
  934. }
  935. return that
  936. }
  937. function fromArrayBuffer (that, array, byteOffset, length) {
  938. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  939. if (byteOffset < 0 || array.byteLength < byteOffset) {
  940. throw new RangeError('\'offset\' is out of bounds')
  941. }
  942. if (array.byteLength < byteOffset + (length || 0)) {
  943. throw new RangeError('\'length\' is out of bounds')
  944. }
  945. if (byteOffset === undefined && length === undefined) {
  946. array = new Uint8Array(array)
  947. } else if (length === undefined) {
  948. array = new Uint8Array(array, byteOffset)
  949. } else {
  950. array = new Uint8Array(array, byteOffset, length)
  951. }
  952. if (Buffer.TYPED_ARRAY_SUPPORT) {
  953. // Return an augmented `Uint8Array` instance, for best performance
  954. that = array
  955. that.__proto__ = Buffer.prototype
  956. } else {
  957. // Fallback: Return an object instance of the Buffer class
  958. that = fromArrayLike(that, array)
  959. }
  960. return that
  961. }
  962. function fromObject (that, obj) {
  963. if (Buffer.isBuffer(obj)) {
  964. var len = checked(obj.length) | 0
  965. that = createBuffer(that, len)
  966. if (that.length === 0) {
  967. return that
  968. }
  969. obj.copy(that, 0, 0, len)
  970. return that
  971. }
  972. if (obj) {
  973. if ((typeof ArrayBuffer !== 'undefined' &&
  974. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  975. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  976. return createBuffer(that, 0)
  977. }
  978. return fromArrayLike(that, obj)
  979. }
  980. if (obj.type === 'Buffer' && isArray(obj.data)) {
  981. return fromArrayLike(that, obj.data)
  982. }
  983. }
  984. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  985. }
  986. function checked (length) {
  987. // Note: cannot use `length < kMaxLength()` here because that fails when
  988. // length is NaN (which is otherwise coerced to zero.)
  989. if (length >= kMaxLength()) {
  990. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  991. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  992. }
  993. return length | 0
  994. }
  995. function SlowBuffer (length) {
  996. if (+length != length) { // eslint-disable-line eqeqeq
  997. length = 0
  998. }
  999. return Buffer.alloc(+length)
  1000. }
  1001. Buffer.isBuffer = function isBuffer (b) {
  1002. return !!(b != null && b._isBuffer)
  1003. }
  1004. Buffer.compare = function compare (a, b) {
  1005. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  1006. throw new TypeError('Arguments must be Buffers')
  1007. }
  1008. if (a === b) return 0
  1009. var x = a.length
  1010. var y = b.length
  1011. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  1012. if (a[i] !== b[i]) {
  1013. x = a[i]
  1014. y = b[i]
  1015. break
  1016. }
  1017. }
  1018. if (x < y) return -1
  1019. if (y < x) return 1
  1020. return 0
  1021. }
  1022. Buffer.isEncoding = function isEncoding (encoding) {
  1023. switch (String(encoding).toLowerCase()) {
  1024. case 'hex':
  1025. case 'utf8':
  1026. case 'utf-8':
  1027. case 'ascii':
  1028. case 'latin1':
  1029. case 'binary':
  1030. case 'base64':
  1031. case 'ucs2':
  1032. case 'ucs-2':
  1033. case 'utf16le':
  1034. case 'utf-16le':
  1035. return true
  1036. default:
  1037. return false
  1038. }
  1039. }
  1040. Buffer.concat = function concat (list, length) {
  1041. if (!isArray(list)) {
  1042. throw new TypeError('"list" argument must be an Array of Buffers')
  1043. }
  1044. if (list.length === 0) {
  1045. return Buffer.alloc(0)
  1046. }
  1047. var i
  1048. if (length === undefined) {
  1049. length = 0
  1050. for (i = 0; i < list.length; ++i) {
  1051. length += list[i].length
  1052. }
  1053. }
  1054. var buffer = Buffer.allocUnsafe(length)
  1055. var pos = 0
  1056. for (i = 0; i < list.length; ++i) {
  1057. var buf = list[i]
  1058. if (!Buffer.isBuffer(buf)) {
  1059. throw new TypeError('"list" argument must be an Array of Buffers')
  1060. }
  1061. buf.copy(buffer, pos)
  1062. pos += buf.length
  1063. }
  1064. return buffer
  1065. }
  1066. function byteLength (string, encoding) {
  1067. if (Buffer.isBuffer(string)) {
  1068. return string.length
  1069. }
  1070. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  1071. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  1072. return string.byteLength
  1073. }
  1074. if (typeof string !== 'string') {
  1075. string = '' + string
  1076. }
  1077. var len = string.length
  1078. if (len === 0) return 0
  1079. // Use a for loop to avoid recursion
  1080. var loweredCase = false
  1081. for (;;) {
  1082. switch (encoding) {
  1083. case 'ascii':
  1084. case 'latin1':
  1085. case 'binary':
  1086. return len
  1087. case 'utf8':
  1088. case 'utf-8':
  1089. case undefined:
  1090. return utf8ToBytes(string).length
  1091. case 'ucs2':
  1092. case 'ucs-2':
  1093. case 'utf16le':
  1094. case 'utf-16le':
  1095. return len * 2
  1096. case 'hex':
  1097. return len >>> 1
  1098. case 'base64':
  1099. return base64ToBytes(string).length
  1100. default:
  1101. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  1102. encoding = ('' + encoding).toLowerCase()
  1103. loweredCase = true
  1104. }
  1105. }
  1106. }
  1107. Buffer.byteLength = byteLength
  1108. function slowToString (encoding, start, end) {
  1109. var loweredCase = false
  1110. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  1111. // property of a typed array.
  1112. // This behaves neither like String nor Uint8Array in that we set start/end
  1113. // to their upper/lower bounds if the value passed is out of range.
  1114. // undefined is handled specially as per ECMA-262 6th Edition,
  1115. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  1116. if (start === undefined || start < 0) {
  1117. start = 0
  1118. }
  1119. // Return early if start > this.length. Done here to prevent potential uint32
  1120. // coercion fail below.
  1121. if (start > this.length) {
  1122. return ''
  1123. }
  1124. if (end === undefined || end > this.length) {
  1125. end = this.length
  1126. }
  1127. if (end <= 0) {
  1128. return ''
  1129. }
  1130. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  1131. end >>>= 0
  1132. start >>>= 0
  1133. if (end <= start) {
  1134. return ''
  1135. }
  1136. if (!encoding) encoding = 'utf8'
  1137. while (true) {
  1138. switch (encoding) {
  1139. case 'hex':
  1140. return hexSlice(this, start, end)
  1141. case 'utf8':
  1142. case 'utf-8':
  1143. return utf8Slice(this, start, end)
  1144. case 'ascii':
  1145. return asciiSlice(this, start, end)
  1146. case 'latin1':
  1147. case 'binary':
  1148. return latin1Slice(this, start, end)
  1149. case 'base64':
  1150. return base64Slice(this, start, end)
  1151. case 'ucs2':
  1152. case 'ucs-2':
  1153. case 'utf16le':
  1154. case 'utf-16le':
  1155. return utf16leSlice(this, start, end)
  1156. default:
  1157. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1158. encoding = (encoding + '').toLowerCase()
  1159. loweredCase = true
  1160. }
  1161. }
  1162. }
  1163. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  1164. // Buffer instances.
  1165. Buffer.prototype._isBuffer = true
  1166. function swap (b, n, m) {
  1167. var i = b[n]
  1168. b[n] = b[m]
  1169. b[m] = i
  1170. }
  1171. Buffer.prototype.swap16 = function swap16 () {
  1172. var len = this.length
  1173. if (len % 2 !== 0) {
  1174. throw new RangeError('Buffer size must be a multiple of 16-bits')
  1175. }
  1176. for (var i = 0; i < len; i += 2) {
  1177. swap(this, i, i + 1)
  1178. }
  1179. return this
  1180. }
  1181. Buffer.prototype.swap32 = function swap32 () {
  1182. var len = this.length
  1183. if (len % 4 !== 0) {
  1184. throw new RangeError('Buffer size must be a multiple of 32-bits')
  1185. }
  1186. for (var i = 0; i < len; i += 4) {
  1187. swap(this, i, i + 3)
  1188. swap(this, i + 1, i + 2)
  1189. }
  1190. return this
  1191. }
  1192. Buffer.prototype.swap64 = function swap64 () {
  1193. var len = this.length
  1194. if (len % 8 !== 0) {
  1195. throw new RangeError('Buffer size must be a multiple of 64-bits')
  1196. }
  1197. for (var i = 0; i < len; i += 8) {
  1198. swap(this, i, i + 7)
  1199. swap(this, i + 1, i + 6)
  1200. swap(this, i + 2, i + 5)
  1201. swap(this, i + 3, i + 4)
  1202. }
  1203. return this
  1204. }
  1205. Buffer.prototype.toString = function toString () {
  1206. var length = this.length | 0
  1207. if (length === 0) return ''
  1208. if (arguments.length === 0) return utf8Slice(this, 0, length)
  1209. return slowToString.apply(this, arguments)
  1210. }
  1211. Buffer.prototype.equals = function equals (b) {
  1212. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  1213. if (this === b) return true
  1214. return Buffer.compare(this, b) === 0
  1215. }
  1216. Buffer.prototype.inspect = function inspect () {
  1217. var str = ''
  1218. var max = exports.INSPECT_MAX_BYTES
  1219. if (this.length > 0) {
  1220. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  1221. if (this.length > max) str += ' ... '
  1222. }
  1223. return '<Buffer ' + str + '>'
  1224. }
  1225. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  1226. if (!Buffer.isBuffer(target)) {
  1227. throw new TypeError('Argument must be a Buffer')
  1228. }
  1229. if (start === undefined) {
  1230. start = 0
  1231. }
  1232. if (end === undefined) {
  1233. end = target ? target.length : 0
  1234. }
  1235. if (thisStart === undefined) {
  1236. thisStart = 0
  1237. }
  1238. if (thisEnd === undefined) {
  1239. thisEnd = this.length
  1240. }
  1241. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  1242. throw new RangeError('out of range index')
  1243. }
  1244. if (thisStart >= thisEnd && start >= end) {
  1245. return 0
  1246. }
  1247. if (thisStart >= thisEnd) {
  1248. return -1
  1249. }
  1250. if (start >= end) {
  1251. return 1
  1252. }
  1253. start >>>= 0
  1254. end >>>= 0
  1255. thisStart >>>= 0
  1256. thisEnd >>>= 0
  1257. if (this === target) return 0
  1258. var x = thisEnd - thisStart
  1259. var y = end - start
  1260. var len = Math.min(x, y)
  1261. var thisCopy = this.slice(thisStart, thisEnd)
  1262. var targetCopy = target.slice(start, end)
  1263. for (var i = 0; i < len; ++i) {
  1264. if (thisCopy[i] !== targetCopy[i]) {
  1265. x = thisCopy[i]
  1266. y = targetCopy[i]
  1267. break
  1268. }
  1269. }
  1270. if (x < y) return -1
  1271. if (y < x) return 1
  1272. return 0
  1273. }
  1274. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  1275. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  1276. //
  1277. // Arguments:
  1278. // - buffer - a Buffer to search
  1279. // - val - a string, Buffer, or number
  1280. // - byteOffset - an index into `buffer`; will be clamped to an int32
  1281. // - encoding - an optional encoding, relevant is val is a string
  1282. // - dir - true for indexOf, false for lastIndexOf
  1283. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  1284. // Empty buffer means no match
  1285. if (buffer.length === 0) return -1
  1286. // Normalize byteOffset
  1287. if (typeof byteOffset === 'string') {
  1288. encoding = byteOffset
  1289. byteOffset = 0
  1290. } else if (byteOffset > 0x7fffffff) {
  1291. byteOffset = 0x7fffffff
  1292. } else if (byteOffset < -0x80000000) {
  1293. byteOffset = -0x80000000
  1294. }
  1295. byteOffset = +byteOffset // Coerce to Number.
  1296. if (isNaN(byteOffset)) {
  1297. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  1298. byteOffset = dir ? 0 : (buffer.length - 1)
  1299. }
  1300. // Normalize byteOffset: negative offsets start from the end of the buffer
  1301. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  1302. if (byteOffset >= buffer.length) {
  1303. if (dir) return -1
  1304. else byteOffset = buffer.length - 1
  1305. } else if (byteOffset < 0) {
  1306. if (dir) byteOffset = 0
  1307. else return -1
  1308. }
  1309. // Normalize val
  1310. if (typeof val === 'string') {
  1311. val = Buffer.from(val, encoding)
  1312. }
  1313. // Finally, search either indexOf (if dir is true) or lastIndexOf
  1314. if (Buffer.isBuffer(val)) {
  1315. // Special case: looking for empty string/buffer always fails
  1316. if (val.length === 0) {
  1317. return -1
  1318. }
  1319. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  1320. } else if (typeof val === 'number') {
  1321. val = val & 0xFF // Search for a byte value [0-255]
  1322. if (Buffer.TYPED_ARRAY_SUPPORT &&
  1323. typeof Uint8Array.prototype.indexOf === 'function') {
  1324. if (dir) {
  1325. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  1326. } else {
  1327. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  1328. }
  1329. }
  1330. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  1331. }
  1332. throw new TypeError('val must be string, number or Buffer')
  1333. }
  1334. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  1335. var indexSize = 1
  1336. var arrLength = arr.length
  1337. var valLength = val.length
  1338. if (encoding !== undefined) {
  1339. encoding = String(encoding).toLowerCase()
  1340. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  1341. encoding === 'utf16le' || encoding === 'utf-16le') {
  1342. if (arr.length < 2 || val.length < 2) {
  1343. return -1
  1344. }
  1345. indexSize = 2
  1346. arrLength /= 2
  1347. valLength /= 2
  1348. byteOffset /= 2
  1349. }
  1350. }
  1351. function read (buf, i) {
  1352. if (indexSize === 1) {
  1353. return buf[i]
  1354. } else {
  1355. return buf.readUInt16BE(i * indexSize)
  1356. }
  1357. }
  1358. var i
  1359. if (dir) {
  1360. var foundIndex = -1
  1361. for (i = byteOffset; i < arrLength; i++) {
  1362. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  1363. if (foundIndex === -1) foundIndex = i
  1364. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  1365. } else {
  1366. if (foundIndex !== -1) i -= i - foundIndex
  1367. foundIndex = -1
  1368. }
  1369. }
  1370. } else {
  1371. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  1372. for (i = byteOffset; i >= 0; i--) {
  1373. var found = true
  1374. for (var j = 0; j < valLength; j++) {
  1375. if (read(arr, i + j) !== read(val, j)) {
  1376. found = false
  1377. break
  1378. }
  1379. }
  1380. if (found) return i
  1381. }
  1382. }
  1383. return -1
  1384. }
  1385. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  1386. return this.indexOf(val, byteOffset, encoding) !== -1
  1387. }
  1388. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  1389. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  1390. }
  1391. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  1392. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  1393. }
  1394. function hexWrite (buf, string, offset, length) {
  1395. offset = Number(offset) || 0
  1396. var remaining = buf.length - offset
  1397. if (!length) {
  1398. length = remaining
  1399. } else {
  1400. length = Number(length)
  1401. if (length > remaining) {
  1402. length = remaining
  1403. }
  1404. }
  1405. // must be an even number of digits
  1406. var strLen = string.length
  1407. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  1408. if (length > strLen / 2) {
  1409. length = strLen / 2
  1410. }
  1411. for (var i = 0; i < length; ++i) {
  1412. var parsed = parseInt(string.substr(i * 2, 2), 16)
  1413. if (isNaN(parsed)) return i
  1414. buf[offset + i] = parsed
  1415. }
  1416. return i
  1417. }
  1418. function utf8Write (buf, string, offset, length) {
  1419. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  1420. }
  1421. function asciiWrite (buf, string, offset, length) {
  1422. return blitBuffer(asciiToBytes(string), buf, offset, length)
  1423. }
  1424. function latin1Write (buf, string, offset, length) {
  1425. return asciiWrite(buf, string, offset, length)
  1426. }
  1427. function base64Write (buf, string, offset, length) {
  1428. return blitBuffer(base64ToBytes(string), buf, offset, length)
  1429. }
  1430. function ucs2Write (buf, string, offset, length) {
  1431. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  1432. }
  1433. Buffer.prototype.write = function write (string, offset, length, encoding) {
  1434. // Buffer#write(string)
  1435. if (offset === undefined) {
  1436. encoding = 'utf8'
  1437. length = this.length
  1438. offset = 0
  1439. // Buffer#write(string, encoding)
  1440. } else if (length === undefined && typeof offset === 'string') {
  1441. encoding = offset
  1442. length = this.length
  1443. offset = 0
  1444. // Buffer#write(string, offset[, length][, encoding])
  1445. } else if (isFinite(offset)) {
  1446. offset = offset | 0
  1447. if (isFinite(length)) {
  1448. length = length | 0
  1449. if (encoding === undefined) encoding = 'utf8'
  1450. } else {
  1451. encoding = length
  1452. length = undefined
  1453. }
  1454. // legacy write(string, encoding, offset, length) - remove in v0.13
  1455. } else {
  1456. throw new Error(
  1457. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  1458. )
  1459. }
  1460. var remaining = this.length - offset
  1461. if (length === undefined || length > remaining) length = remaining
  1462. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  1463. throw new RangeError('Attempt to write outside buffer bounds')
  1464. }
  1465. if (!encoding) encoding = 'utf8'
  1466. var loweredCase = false
  1467. for (;;) {
  1468. switch (encoding) {
  1469. case 'hex':
  1470. return hexWrite(this, string, offset, length)
  1471. case 'utf8':
  1472. case 'utf-8':
  1473. return utf8Write(this, string, offset, length)
  1474. case 'ascii':
  1475. return asciiWrite(this, string, offset, length)
  1476. case 'latin1':
  1477. case 'binary':
  1478. return latin1Write(this, string, offset, length)
  1479. case 'base64':
  1480. // Warning: maxLength not taken into account in base64Write
  1481. return base64Write(this, string, offset, length)
  1482. case 'ucs2':
  1483. case 'ucs-2':
  1484. case 'utf16le':
  1485. case 'utf-16le':
  1486. return ucs2Write(this, string, offset, length)
  1487. default:
  1488. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  1489. encoding = ('' + encoding).toLowerCase()
  1490. loweredCase = true
  1491. }
  1492. }
  1493. }
  1494. Buffer.prototype.toJSON = function toJSON () {
  1495. return {
  1496. type: 'Buffer',
  1497. data: Array.prototype.slice.call(this._arr || this, 0)
  1498. }
  1499. }
  1500. function base64Slice (buf, start, end) {
  1501. if (start === 0 && end === buf.length) {
  1502. return base64.fromByteArray(buf)
  1503. } else {
  1504. return base64.fromByteArray(buf.slice(start, end))
  1505. }
  1506. }
  1507. function utf8Slice (buf, start, end) {
  1508. end = Math.min(buf.length, end)
  1509. var res = []
  1510. var i = start
  1511. while (i < end) {
  1512. var firstByte = buf[i]
  1513. var codePoint = null
  1514. var bytesPerSequence = (firstByte > 0xEF) ? 4
  1515. : (firstByte > 0xDF) ? 3
  1516. : (firstByte > 0xBF) ? 2
  1517. : 1
  1518. if (i + bytesPerSequence <= end) {
  1519. var secondByte, thirdByte, fourthByte, tempCodePoint
  1520. switch (bytesPerSequence) {
  1521. case 1:
  1522. if (firstByte < 0x80) {
  1523. codePoint = firstByte
  1524. }
  1525. break
  1526. case 2:
  1527. secondByte = buf[i + 1]
  1528. if ((secondByte & 0xC0) === 0x80) {
  1529. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  1530. if (tempCodePoint > 0x7F) {
  1531. codePoint = tempCodePoint
  1532. }
  1533. }
  1534. break
  1535. case 3:
  1536. secondByte = buf[i + 1]
  1537. thirdByte = buf[i + 2]
  1538. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  1539. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  1540. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  1541. codePoint = tempCodePoint
  1542. }
  1543. }
  1544. break
  1545. case 4:
  1546. secondByte = buf[i + 1]
  1547. thirdByte = buf[i + 2]
  1548. fourthByte = buf[i + 3]
  1549. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  1550. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  1551. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  1552. codePoint = tempCodePoint
  1553. }
  1554. }
  1555. }
  1556. }
  1557. if (codePoint === null) {
  1558. // we did not generate a valid codePoint so insert a
  1559. // replacement char (U+FFFD) and advance only 1 byte
  1560. codePoint = 0xFFFD
  1561. bytesPerSequence = 1
  1562. } else if (codePoint > 0xFFFF) {
  1563. // encode to utf16 (surrogate pair dance)
  1564. codePoint -= 0x10000
  1565. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  1566. codePoint = 0xDC00 | codePoint & 0x3FF
  1567. }
  1568. res.push(codePoint)
  1569. i += bytesPerSequence
  1570. }
  1571. return decodeCodePointsArray(res)
  1572. }
  1573. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  1574. // the lowest limit is Chrome, with 0x10000 args.
  1575. // We go 1 magnitude less, for safety
  1576. var MAX_ARGUMENTS_LENGTH = 0x1000
  1577. function decodeCodePointsArray (codePoints) {
  1578. var len = codePoints.length
  1579. if (len <= MAX_ARGUMENTS_LENGTH) {
  1580. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  1581. }
  1582. // Decode in chunks to avoid "call stack size exceeded".
  1583. var res = ''
  1584. var i = 0
  1585. while (i < len) {
  1586. res += String.fromCharCode.apply(
  1587. String,
  1588. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  1589. )
  1590. }
  1591. return res
  1592. }
  1593. function asciiSlice (buf, start, end) {
  1594. var ret = ''
  1595. end = Math.min(buf.length, end)
  1596. for (var i = start; i < end; ++i) {
  1597. ret += String.fromCharCode(buf[i] & 0x7F)
  1598. }
  1599. return ret
  1600. }
  1601. function latin1Slice (buf, start, end) {
  1602. var ret = ''
  1603. end = Math.min(buf.length, end)
  1604. for (var i = start; i < end; ++i) {
  1605. ret += String.fromCharCode(buf[i])
  1606. }
  1607. return ret
  1608. }
  1609. function hexSlice (buf, start, end) {
  1610. var len = buf.length
  1611. if (!start || start < 0) start = 0
  1612. if (!end || end < 0 || end > len) end = len
  1613. var out = ''
  1614. for (var i = start; i < end; ++i) {
  1615. out += toHex(buf[i])
  1616. }
  1617. return out
  1618. }
  1619. function utf16leSlice (buf, start, end) {
  1620. var bytes = buf.slice(start, end)
  1621. var res = ''
  1622. for (var i = 0; i < bytes.length; i += 2) {
  1623. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  1624. }
  1625. return res
  1626. }
  1627. Buffer.prototype.slice = function slice (start, end) {
  1628. var len = this.length
  1629. start = ~~start
  1630. end = end === undefined ? len : ~~end
  1631. if (start < 0) {
  1632. start += len
  1633. if (start < 0) start = 0
  1634. } else if (start > len) {
  1635. start = len
  1636. }
  1637. if (end < 0) {
  1638. end += len
  1639. if (end < 0) end = 0
  1640. } else if (end > len) {
  1641. end = len
  1642. }
  1643. if (end < start) end = start
  1644. var newBuf
  1645. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1646. newBuf = this.subarray(start, end)
  1647. newBuf.__proto__ = Buffer.prototype
  1648. } else {
  1649. var sliceLen = end - start
  1650. newBuf = new Buffer(sliceLen, undefined)
  1651. for (var i = 0; i < sliceLen; ++i) {
  1652. newBuf[i] = this[i + start]
  1653. }
  1654. }
  1655. return newBuf
  1656. }
  1657. /*
  1658. * Need to make sure that buffer isn't trying to write out of bounds.
  1659. */
  1660. function checkOffset (offset, ext, length) {
  1661. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1662. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1663. }
  1664. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1665. offset = offset | 0
  1666. byteLength = byteLength | 0
  1667. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1668. var val = this[offset]
  1669. var mul = 1
  1670. var i = 0
  1671. while (++i < byteLength && (mul *= 0x100)) {
  1672. val += this[offset + i] * mul
  1673. }
  1674. return val
  1675. }
  1676. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1677. offset = offset | 0
  1678. byteLength = byteLength | 0
  1679. if (!noAssert) {
  1680. checkOffset(offset, byteLength, this.length)
  1681. }
  1682. var val = this[offset + --byteLength]
  1683. var mul = 1
  1684. while (byteLength > 0 && (mul *= 0x100)) {
  1685. val += this[offset + --byteLength] * mul
  1686. }
  1687. return val
  1688. }
  1689. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1690. if (!noAssert) checkOffset(offset, 1, this.length)
  1691. return this[offset]
  1692. }
  1693. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1694. if (!noAssert) checkOffset(offset, 2, this.length)
  1695. return this[offset] | (this[offset + 1] << 8)
  1696. }
  1697. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1698. if (!noAssert) checkOffset(offset, 2, this.length)
  1699. return (this[offset] << 8) | this[offset + 1]
  1700. }
  1701. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1702. if (!noAssert) checkOffset(offset, 4, this.length)
  1703. return ((this[offset]) |
  1704. (this[offset + 1] << 8) |
  1705. (this[offset + 2] << 16)) +
  1706. (this[offset + 3] * 0x1000000)
  1707. }
  1708. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1709. if (!noAssert) checkOffset(offset, 4, this.length)
  1710. return (this[offset] * 0x1000000) +
  1711. ((this[offset + 1] << 16) |
  1712. (this[offset + 2] << 8) |
  1713. this[offset + 3])
  1714. }
  1715. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1716. offset = offset | 0
  1717. byteLength = byteLength | 0
  1718. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1719. var val = this[offset]
  1720. var mul = 1
  1721. var i = 0
  1722. while (++i < byteLength && (mul *= 0x100)) {
  1723. val += this[offset + i] * mul
  1724. }
  1725. mul *= 0x80
  1726. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1727. return val
  1728. }
  1729. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1730. offset = offset | 0
  1731. byteLength = byteLength | 0
  1732. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1733. var i = byteLength
  1734. var mul = 1
  1735. var val = this[offset + --i]
  1736. while (i > 0 && (mul *= 0x100)) {
  1737. val += this[offset + --i] * mul
  1738. }
  1739. mul *= 0x80
  1740. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1741. return val
  1742. }
  1743. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1744. if (!noAssert) checkOffset(offset, 1, this.length)
  1745. if (!(this[offset] & 0x80)) return (this[offset])
  1746. return ((0xff - this[offset] + 1) * -1)
  1747. }
  1748. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1749. if (!noAssert) checkOffset(offset, 2, this.length)
  1750. var val = this[offset] | (this[offset + 1] << 8)
  1751. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1752. }
  1753. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1754. if (!noAssert) checkOffset(offset, 2, this.length)
  1755. var val = this[offset + 1] | (this[offset] << 8)
  1756. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1757. }
  1758. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1759. if (!noAssert) checkOffset(offset, 4, this.length)
  1760. return (this[offset]) |
  1761. (this[offset + 1] << 8) |
  1762. (this[offset + 2] << 16) |
  1763. (this[offset + 3] << 24)
  1764. }
  1765. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1766. if (!noAssert) checkOffset(offset, 4, this.length)
  1767. return (this[offset] << 24) |
  1768. (this[offset + 1] << 16) |
  1769. (this[offset + 2] << 8) |
  1770. (this[offset + 3])
  1771. }
  1772. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1773. if (!noAssert) checkOffset(offset, 4, this.length)
  1774. return ieee754.read(this, offset, true, 23, 4)
  1775. }
  1776. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1777. if (!noAssert) checkOffset(offset, 4, this.length)
  1778. return ieee754.read(this, offset, false, 23, 4)
  1779. }
  1780. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1781. if (!noAssert) checkOffset(offset, 8, this.length)
  1782. return ieee754.read(this, offset, true, 52, 8)
  1783. }
  1784. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1785. if (!noAssert) checkOffset(offset, 8, this.length)
  1786. return ieee754.read(this, offset, false, 52, 8)
  1787. }
  1788. function checkInt (buf, value, offset, ext, max, min) {
  1789. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1790. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1791. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1792. }
  1793. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1794. value = +value
  1795. offset = offset | 0
  1796. byteLength = byteLength | 0
  1797. if (!noAssert) {
  1798. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1799. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1800. }
  1801. var mul = 1
  1802. var i = 0
  1803. this[offset] = value & 0xFF
  1804. while (++i < byteLength && (mul *= 0x100)) {
  1805. this[offset + i] = (value / mul) & 0xFF
  1806. }
  1807. return offset + byteLength
  1808. }
  1809. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1810. value = +value
  1811. offset = offset | 0
  1812. byteLength = byteLength | 0
  1813. if (!noAssert) {
  1814. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1815. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1816. }
  1817. var i = byteLength - 1
  1818. var mul = 1
  1819. this[offset + i] = value & 0xFF
  1820. while (--i >= 0 && (mul *= 0x100)) {
  1821. this[offset + i] = (value / mul) & 0xFF
  1822. }
  1823. return offset + byteLength
  1824. }
  1825. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1826. value = +value
  1827. offset = offset | 0
  1828. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1829. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1830. this[offset] = (value & 0xff)
  1831. return offset + 1
  1832. }
  1833. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1834. if (value < 0) value = 0xffff + value + 1
  1835. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1836. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1837. (littleEndian ? i : 1 - i) * 8
  1838. }
  1839. }
  1840. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1841. value = +value
  1842. offset = offset | 0
  1843. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1844. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1845. this[offset] = (value & 0xff)
  1846. this[offset + 1] = (value >>> 8)
  1847. } else {
  1848. objectWriteUInt16(this, value, offset, true)
  1849. }
  1850. return offset + 2
  1851. }
  1852. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1853. value = +value
  1854. offset = offset | 0
  1855. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1856. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1857. this[offset] = (value >>> 8)
  1858. this[offset + 1] = (value & 0xff)
  1859. } else {
  1860. objectWriteUInt16(this, value, offset, false)
  1861. }
  1862. return offset + 2
  1863. }
  1864. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1865. if (value < 0) value = 0xffffffff + value + 1
  1866. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1867. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1868. }
  1869. }
  1870. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1871. value = +value
  1872. offset = offset | 0
  1873. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1874. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1875. this[offset + 3] = (value >>> 24)
  1876. this[offset + 2] = (value >>> 16)
  1877. this[offset + 1] = (value >>> 8)
  1878. this[offset] = (value & 0xff)
  1879. } else {
  1880. objectWriteUInt32(this, value, offset, true)
  1881. }
  1882. return offset + 4
  1883. }
  1884. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1885. value = +value
  1886. offset = offset | 0
  1887. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1888. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1889. this[offset] = (value >>> 24)
  1890. this[offset + 1] = (value >>> 16)
  1891. this[offset + 2] = (value >>> 8)
  1892. this[offset + 3] = (value & 0xff)
  1893. } else {
  1894. objectWriteUInt32(this, value, offset, false)
  1895. }
  1896. return offset + 4
  1897. }
  1898. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1899. value = +value
  1900. offset = offset | 0
  1901. if (!noAssert) {
  1902. var limit = Math.pow(2, 8 * byteLength - 1)
  1903. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1904. }
  1905. var i = 0
  1906. var mul = 1
  1907. var sub = 0
  1908. this[offset] = value & 0xFF
  1909. while (++i < byteLength && (mul *= 0x100)) {
  1910. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1911. sub = 1
  1912. }
  1913. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1914. }
  1915. return offset + byteLength
  1916. }
  1917. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1918. value = +value
  1919. offset = offset | 0
  1920. if (!noAssert) {
  1921. var limit = Math.pow(2, 8 * byteLength - 1)
  1922. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1923. }
  1924. var i = byteLength - 1
  1925. var mul = 1
  1926. var sub = 0
  1927. this[offset + i] = value & 0xFF
  1928. while (--i >= 0 && (mul *= 0x100)) {
  1929. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1930. sub = 1
  1931. }
  1932. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1933. }
  1934. return offset + byteLength
  1935. }
  1936. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1937. value = +value
  1938. offset = offset | 0
  1939. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1940. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1941. if (value < 0) value = 0xff + value + 1
  1942. this[offset] = (value & 0xff)
  1943. return offset + 1
  1944. }
  1945. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1946. value = +value
  1947. offset = offset | 0
  1948. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1949. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1950. this[offset] = (value & 0xff)
  1951. this[offset + 1] = (value >>> 8)
  1952. } else {
  1953. objectWriteUInt16(this, value, offset, true)
  1954. }
  1955. return offset + 2
  1956. }
  1957. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1958. value = +value
  1959. offset = offset | 0
  1960. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1961. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1962. this[offset] = (value >>> 8)
  1963. this[offset + 1] = (value & 0xff)
  1964. } else {
  1965. objectWriteUInt16(this, value, offset, false)
  1966. }
  1967. return offset + 2
  1968. }
  1969. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1970. value = +value
  1971. offset = offset | 0
  1972. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1973. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1974. this[offset] = (value & 0xff)
  1975. this[offset + 1] = (value >>> 8)
  1976. this[offset + 2] = (value >>> 16)
  1977. this[offset + 3] = (value >>> 24)
  1978. } else {
  1979. objectWriteUInt32(this, value, offset, true)
  1980. }
  1981. return offset + 4
  1982. }
  1983. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1984. value = +value
  1985. offset = offset | 0
  1986. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1987. if (value < 0) value = 0xffffffff + value + 1
  1988. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1989. this[offset] = (value >>> 24)
  1990. this[offset + 1] = (value >>> 16)
  1991. this[offset + 2] = (value >>> 8)
  1992. this[offset + 3] = (value & 0xff)
  1993. } else {
  1994. objectWriteUInt32(this, value, offset, false)
  1995. }
  1996. return offset + 4
  1997. }
  1998. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1999. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2000. if (offset < 0) throw new RangeError('Index out of range')
  2001. }
  2002. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  2003. if (!noAssert) {
  2004. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  2005. }
  2006. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  2007. return offset + 4
  2008. }
  2009. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  2010. return writeFloat(this, value, offset, true, noAssert)
  2011. }
  2012. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  2013. return writeFloat(this, value, offset, false, noAssert)
  2014. }
  2015. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  2016. if (!noAssert) {
  2017. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  2018. }
  2019. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  2020. return offset + 8
  2021. }
  2022. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  2023. return writeDouble(this, value, offset, true, noAssert)
  2024. }
  2025. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  2026. return writeDouble(this, value, offset, false, noAssert)
  2027. }
  2028. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  2029. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  2030. if (!start) start = 0
  2031. if (!end && end !== 0) end = this.length
  2032. if (targetStart >= target.length) targetStart = target.length
  2033. if (!targetStart) targetStart = 0
  2034. if (end > 0 && end < start) end = start
  2035. // Copy 0 bytes; we're done
  2036. if (end === start) return 0
  2037. if (target.length === 0 || this.length === 0) return 0
  2038. // Fatal error conditions
  2039. if (targetStart < 0) {
  2040. throw new RangeError('targetStart out of bounds')
  2041. }
  2042. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  2043. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  2044. // Are we oob?
  2045. if (end > this.length) end = this.length
  2046. if (target.length - targetStart < end - start) {
  2047. end = target.length - targetStart + start
  2048. }
  2049. var len = end - start
  2050. var i
  2051. if (this === target && start < targetStart && targetStart < end) {
  2052. // descending copy from end
  2053. for (i = len - 1; i >= 0; --i) {
  2054. target[i + targetStart] = this[i + start]
  2055. }
  2056. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  2057. // ascending copy from start
  2058. for (i = 0; i < len; ++i) {
  2059. target[i + targetStart] = this[i + start]
  2060. }
  2061. } else {
  2062. Uint8Array.prototype.set.call(
  2063. target,
  2064. this.subarray(start, start + len),
  2065. targetStart
  2066. )
  2067. }
  2068. return len
  2069. }
  2070. // Usage:
  2071. // buffer.fill(number[, offset[, end]])
  2072. // buffer.fill(buffer[, offset[, end]])
  2073. // buffer.fill(string[, offset[, end]][, encoding])
  2074. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  2075. // Handle string cases:
  2076. if (typeof val === 'string') {
  2077. if (typeof start === 'string') {
  2078. encoding = start
  2079. start = 0
  2080. end = this.length
  2081. } else if (typeof end === 'string') {
  2082. encoding = end
  2083. end = this.length
  2084. }
  2085. if (val.length === 1) {
  2086. var code = val.charCodeAt(0)
  2087. if (code < 256) {
  2088. val = code
  2089. }
  2090. }
  2091. if (encoding !== undefined && typeof encoding !== 'string') {
  2092. throw new TypeError('encoding must be a string')
  2093. }
  2094. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  2095. throw new TypeError('Unknown encoding: ' + encoding)
  2096. }
  2097. } else if (typeof val === 'number') {
  2098. val = val & 255
  2099. }
  2100. // Invalid ranges are not set to a default, so can range check early.
  2101. if (start < 0 || this.length < start || this.length < end) {
  2102. throw new RangeError('Out of range index')
  2103. }
  2104. if (end <= start) {
  2105. return this
  2106. }
  2107. start = start >>> 0
  2108. end = end === undefined ? this.length : end >>> 0
  2109. if (!val) val = 0
  2110. var i
  2111. if (typeof val === 'number') {
  2112. for (i = start; i < end; ++i) {
  2113. this[i] = val
  2114. }
  2115. } else {
  2116. var bytes = Buffer.isBuffer(val)
  2117. ? val
  2118. : utf8ToBytes(new Buffer(val, encoding).toString())
  2119. var len = bytes.length
  2120. for (i = 0; i < end - start; ++i) {
  2121. this[i + start] = bytes[i % len]
  2122. }
  2123. }
  2124. return this
  2125. }
  2126. // HELPER FUNCTIONS
  2127. // ================
  2128. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  2129. function base64clean (str) {
  2130. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  2131. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  2132. // Node converts strings with length < 2 to ''
  2133. if (str.length < 2) return ''
  2134. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  2135. while (str.length % 4 !== 0) {
  2136. str = str + '='
  2137. }
  2138. return str
  2139. }
  2140. function stringtrim (str) {
  2141. if (str.trim) return str.trim()
  2142. return str.replace(/^\s+|\s+$/g, '')
  2143. }
  2144. function toHex (n) {
  2145. if (n < 16) return '0' + n.toString(16)
  2146. return n.toString(16)
  2147. }
  2148. function utf8ToBytes (string, units) {
  2149. units = units || Infinity
  2150. var codePoint
  2151. var length = string.length
  2152. var leadSurrogate = null
  2153. var bytes = []
  2154. for (var i = 0; i < length; ++i) {
  2155. codePoint = string.charCodeAt(i)
  2156. // is surrogate component
  2157. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  2158. // last char was a lead
  2159. if (!leadSurrogate) {
  2160. // no lead yet
  2161. if (codePoint > 0xDBFF) {
  2162. // unexpected trail
  2163. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2164. continue
  2165. } else if (i + 1 === length) {
  2166. // unpaired lead
  2167. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2168. continue
  2169. }
  2170. // valid lead
  2171. leadSurrogate = codePoint
  2172. continue
  2173. }
  2174. // 2 leads in a row
  2175. if (codePoint < 0xDC00) {
  2176. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2177. leadSurrogate = codePoint
  2178. continue
  2179. }
  2180. // valid surrogate pair
  2181. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  2182. } else if (leadSurrogate) {
  2183. // valid bmp char, but last char was a lead
  2184. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  2185. }
  2186. leadSurrogate = null
  2187. // encode utf8
  2188. if (codePoint < 0x80) {
  2189. if ((units -= 1) < 0) break
  2190. bytes.push(codePoint)
  2191. } else if (codePoint < 0x800) {
  2192. if ((units -= 2) < 0) break
  2193. bytes.push(
  2194. codePoint >> 0x6 | 0xC0,
  2195. codePoint & 0x3F | 0x80
  2196. )
  2197. } else if (codePoint < 0x10000) {
  2198. if ((units -= 3) < 0) break
  2199. bytes.push(
  2200. codePoint >> 0xC | 0xE0,
  2201. codePoint >> 0x6 & 0x3F | 0x80,
  2202. codePoint & 0x3F | 0x80
  2203. )
  2204. } else if (codePoint < 0x110000) {
  2205. if ((units -= 4) < 0) break
  2206. bytes.push(
  2207. codePoint >> 0x12 | 0xF0,
  2208. codePoint >> 0xC & 0x3F | 0x80,
  2209. codePoint >> 0x6 & 0x3F | 0x80,
  2210. codePoint & 0x3F | 0x80
  2211. )
  2212. } else {
  2213. throw new Error('Invalid code point')
  2214. }
  2215. }
  2216. return bytes
  2217. }
  2218. function asciiToBytes (str) {
  2219. var byteArray = []
  2220. for (var i = 0; i < str.length; ++i) {
  2221. // Node's code seems to be doing this and not & 0x7F..
  2222. byteArray.push(str.charCodeAt(i) & 0xFF)
  2223. }
  2224. return byteArray
  2225. }
  2226. function utf16leToBytes (str, units) {
  2227. var c, hi, lo
  2228. var byteArray = []
  2229. for (var i = 0; i < str.length; ++i) {
  2230. if ((units -= 2) < 0) break
  2231. c = str.charCodeAt(i)
  2232. hi = c >> 8
  2233. lo = c % 256
  2234. byteArray.push(lo)
  2235. byteArray.push(hi)
  2236. }
  2237. return byteArray
  2238. }
  2239. function base64ToBytes (str) {
  2240. return base64.toByteArray(base64clean(str))
  2241. }
  2242. function blitBuffer (src, dst, offset, length) {
  2243. for (var i = 0; i < length; ++i) {
  2244. if ((i + offset >= dst.length) || (i >= src.length)) break
  2245. dst[i + offset] = src[i]
  2246. }
  2247. return i
  2248. }
  2249. function isnan (val) {
  2250. return val !== val // eslint-disable-line no-self-compare
  2251. }
  2252. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2253. },{"base64-js":4,"ieee754":16,"isarray":22}],8:[function(_dereq_,module,exports){
  2254. /**
  2255. * This is the web browser implementation of `debug()`.
  2256. *
  2257. * Expose `debug()` as the module.
  2258. */
  2259. exports = module.exports = _dereq_('./debug');
  2260. exports.log = log;
  2261. exports.formatArgs = formatArgs;
  2262. exports.save = save;
  2263. exports.load = load;
  2264. exports.useColors = useColors;
  2265. exports.storage = 'undefined' != typeof chrome
  2266. && 'undefined' != typeof chrome.storage
  2267. ? chrome.storage.local
  2268. : localstorage();
  2269. /**
  2270. * Colors.
  2271. */
  2272. exports.colors = [
  2273. 'lightseagreen',
  2274. 'forestgreen',
  2275. 'goldenrod',
  2276. 'dodgerblue',
  2277. 'darkorchid',
  2278. 'crimson'
  2279. ];
  2280. /**
  2281. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2282. * and the Firebug extension (any Firefox version) are known
  2283. * to support "%c" CSS customizations.
  2284. *
  2285. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2286. */
  2287. function useColors() {
  2288. // is webkit? http://stackoverflow.com/a/16459606/376773
  2289. return ('WebkitAppearance' in document.documentElement.style) ||
  2290. // is firebug? http://stackoverflow.com/a/398120/376773
  2291. (window.console && (console.firebug || (console.exception && console.table))) ||
  2292. // is firefox >= v31?
  2293. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2294. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2295. }
  2296. /**
  2297. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2298. */
  2299. exports.formatters.j = function(v) {
  2300. return JSON.stringify(v);
  2301. };
  2302. /**
  2303. * Colorize log arguments if enabled.
  2304. *
  2305. * @api public
  2306. */
  2307. function formatArgs() {
  2308. var args = arguments;
  2309. var useColors = this.useColors;
  2310. args[0] = (useColors ? '%c' : '')
  2311. + this.namespace
  2312. + (useColors ? ' %c' : ' ')
  2313. + args[0]
  2314. + (useColors ? '%c ' : ' ');
  2315. if (!useColors) return args;
  2316. var c = 'color: ' + this.color;
  2317. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2318. // the final "%c" is somewhat tricky, because there could be other
  2319. // arguments passed either before or after the %c, so we need to
  2320. // figure out the correct index to insert the CSS into
  2321. var index = 0;
  2322. var lastC = 0;
  2323. args[0].replace(/%[a-z%]/g, function(match) {
  2324. if ('%%' === match) return;
  2325. index++;
  2326. if ('%c' === match) {
  2327. // we only are interested in the *last* %c
  2328. // (the user may have provided their own)
  2329. lastC = index;
  2330. }
  2331. });
  2332. args.splice(lastC, 0, c);
  2333. return args;
  2334. }
  2335. /**
  2336. * Invokes `console.log()` when available.
  2337. * No-op when `console.log` is not a "function".
  2338. *
  2339. * @api public
  2340. */
  2341. function log() {
  2342. // this hackery is required for IE8/9, where
  2343. // the `console.log` function doesn't have 'apply'
  2344. return 'object' === typeof console
  2345. && console.log
  2346. && Function.prototype.apply.call(console.log, console, arguments);
  2347. }
  2348. /**
  2349. * Save `namespaces`.
  2350. *
  2351. * @param {String} namespaces
  2352. * @api private
  2353. */
  2354. function save(namespaces) {
  2355. try {
  2356. if (null == namespaces) {
  2357. exports.storage.removeItem('debug');
  2358. } else {
  2359. exports.storage.debug = namespaces;
  2360. }
  2361. } catch(e) {}
  2362. }
  2363. /**
  2364. * Load `namespaces`.
  2365. *
  2366. * @return {String} returns the previously persisted debug modes
  2367. * @api private
  2368. */
  2369. function load() {
  2370. var r;
  2371. try {
  2372. r = exports.storage.debug;
  2373. } catch(e) {}
  2374. return r;
  2375. }
  2376. /**
  2377. * Enable namespaces listed in `localStorage.debug` initially.
  2378. */
  2379. exports.enable(load());
  2380. /**
  2381. * Localstorage attempts to return the localstorage.
  2382. *
  2383. * This is necessary because safari throws
  2384. * when a user disables cookies/localstorage
  2385. * and you attempt to access it.
  2386. *
  2387. * @return {LocalStorage}
  2388. * @api private
  2389. */
  2390. function localstorage(){
  2391. try {
  2392. return window.localStorage;
  2393. } catch (e) {}
  2394. }
  2395. },{"./debug":9}],9:[function(_dereq_,module,exports){
  2396. /**
  2397. * This is the common logic for both the Node.js and web browser
  2398. * implementations of `debug()`.
  2399. *
  2400. * Expose `debug()` as the module.
  2401. */
  2402. exports = module.exports = debug;
  2403. exports.coerce = coerce;
  2404. exports.disable = disable;
  2405. exports.enable = enable;
  2406. exports.enabled = enabled;
  2407. /**
  2408. * The currently active debug mode names, and names to skip.
  2409. */
  2410. exports.names = [];
  2411. exports.skips = [];
  2412. /**
  2413. * Map of special "%n" handling functions, for the debug "format" argument.
  2414. *
  2415. * Valid key names are a single, lowercased letter, i.e. "n".
  2416. */
  2417. exports.formatters = {};
  2418. /**
  2419. * Previously assigned color.
  2420. */
  2421. var prevColor = 0;
  2422. /**
  2423. * Select a color.
  2424. *
  2425. * @return {Number}
  2426. * @api private
  2427. */
  2428. function selectColor() {
  2429. return exports.colors[prevColor++ % exports.colors.length];
  2430. }
  2431. /**
  2432. * Create a debugger with the given `namespace`.
  2433. *
  2434. * @param {String} namespace
  2435. * @return {Function}
  2436. * @api public
  2437. */
  2438. function debug(namespace) {
  2439. // define the `disabled` version
  2440. function disabled() {
  2441. }
  2442. disabled.enabled = false;
  2443. // define the `enabled` version
  2444. function enabled() {
  2445. var self = enabled;
  2446. // add the `color` if not set
  2447. if (null == self.useColors) self.useColors = exports.useColors();
  2448. if (null == self.color && self.useColors) self.color = selectColor();
  2449. var args = Array.prototype.slice.call(arguments);
  2450. args[0] = exports.coerce(args[0]);
  2451. if ('string' !== typeof args[0]) {
  2452. // anything else let's inspect with %o
  2453. args = ['%o'].concat(args);
  2454. }
  2455. // apply any `formatters` transformations
  2456. var index = 0;
  2457. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2458. // if we encounter an escaped % then don't increase the array index
  2459. if (match === '%%') return match;
  2460. index++;
  2461. var formatter = exports.formatters[format];
  2462. if ('function' === typeof formatter) {
  2463. var val = args[index];
  2464. match = formatter.call(self, val);
  2465. // now we need to remove `args[index]` since it's inlined in the `format`
  2466. args.splice(index, 1);
  2467. index--;
  2468. }
  2469. return match;
  2470. });
  2471. if ('function' === typeof exports.formatArgs) {
  2472. args = exports.formatArgs.apply(self, args);
  2473. }
  2474. var logFn = enabled.log || exports.log || console.log.bind(console);
  2475. logFn.apply(self, args);
  2476. }
  2477. enabled.enabled = true;
  2478. var fn = exports.enabled(namespace) ? enabled : disabled;
  2479. fn.namespace = namespace;
  2480. return fn;
  2481. }
  2482. /**
  2483. * Enables a debug mode by namespaces. This can include modes
  2484. * separated by a colon and wildcards.
  2485. *
  2486. * @param {String} namespaces
  2487. * @api public
  2488. */
  2489. function enable(namespaces) {
  2490. exports.save(namespaces);
  2491. var split = (namespaces || '').split(/[\s,]+/);
  2492. var len = split.length;
  2493. for (var i = 0; i < len; i++) {
  2494. if (!split[i]) continue; // ignore empty strings
  2495. namespaces = split[i].replace(/\*/g, '.*?');
  2496. if (namespaces[0] === '-') {
  2497. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2498. } else {
  2499. exports.names.push(new RegExp('^' + namespaces + '$'));
  2500. }
  2501. }
  2502. }
  2503. /**
  2504. * Disable debug output.
  2505. *
  2506. * @api public
  2507. */
  2508. function disable() {
  2509. exports.enable('');
  2510. }
  2511. /**
  2512. * Returns true if the given mode name is enabled, false otherwise.
  2513. *
  2514. * @param {String} name
  2515. * @return {Boolean}
  2516. * @api public
  2517. */
  2518. function enabled(name) {
  2519. var i, len;
  2520. for (i = 0, len = exports.skips.length; i < len; i++) {
  2521. if (exports.skips[i].test(name)) {
  2522. return false;
  2523. }
  2524. }
  2525. for (i = 0, len = exports.names.length; i < len; i++) {
  2526. if (exports.names[i].test(name)) {
  2527. return true;
  2528. }
  2529. }
  2530. return false;
  2531. }
  2532. /**
  2533. * Coerce `val`.
  2534. *
  2535. * @param {Mixed} val
  2536. * @return {Mixed}
  2537. * @api private
  2538. */
  2539. function coerce(val) {
  2540. if (val instanceof Error) return val.stack || val.message;
  2541. return val;
  2542. }
  2543. },{}],10:[function(_dereq_,module,exports){
  2544. 'use strict';
  2545. var isObj = _dereq_('is-obj');
  2546. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2547. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2548. function toObject(val) {
  2549. if (val === null || val === undefined) {
  2550. throw new TypeError('Sources cannot be null or undefined');
  2551. }
  2552. return Object(val);
  2553. }
  2554. function assignKey(to, from, key) {
  2555. var val = from[key];
  2556. if (val === undefined || val === null) {
  2557. return;
  2558. }
  2559. if (hasOwnProperty.call(to, key)) {
  2560. if (to[key] === undefined || to[key] === null) {
  2561. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2562. }
  2563. }
  2564. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2565. to[key] = val;
  2566. } else {
  2567. to[key] = assign(Object(to[key]), from[key]);
  2568. }
  2569. }
  2570. function assign(to, from) {
  2571. if (to === from) {
  2572. return to;
  2573. }
  2574. from = Object(from);
  2575. for (var key in from) {
  2576. if (hasOwnProperty.call(from, key)) {
  2577. assignKey(to, from, key);
  2578. }
  2579. }
  2580. if (Object.getOwnPropertySymbols) {
  2581. var symbols = Object.getOwnPropertySymbols(from);
  2582. for (var i = 0; i < symbols.length; i++) {
  2583. if (propIsEnumerable.call(from, symbols[i])) {
  2584. assignKey(to, from, symbols[i]);
  2585. }
  2586. }
  2587. }
  2588. return to;
  2589. }
  2590. module.exports = function deepAssign(target) {
  2591. target = toObject(target);
  2592. for (var s = 1; s < arguments.length; s++) {
  2593. assign(target, arguments[s]);
  2594. }
  2595. return target;
  2596. };
  2597. },{"is-obj":21}],11:[function(_dereq_,module,exports){
  2598. /*! (C) WebReflection Mit Style License */
  2599. (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");
  2600. },{}],12:[function(_dereq_,module,exports){
  2601. module.exports = function(dtype) {
  2602. switch (dtype) {
  2603. case 'int8':
  2604. return Int8Array
  2605. case 'int16':
  2606. return Int16Array
  2607. case 'int32':
  2608. return Int32Array
  2609. case 'uint8':
  2610. return Uint8Array
  2611. case 'uint16':
  2612. return Uint16Array
  2613. case 'uint32':
  2614. return Uint32Array
  2615. case 'float32':
  2616. return Float32Array
  2617. case 'float64':
  2618. return Float64Array
  2619. case 'array':
  2620. return Array
  2621. case 'uint8_clamped':
  2622. return Uint8ClampedArray
  2623. }
  2624. }
  2625. },{}],13:[function(_dereq_,module,exports){
  2626. /*eslint new-cap:0*/
  2627. var dtype = _dereq_('dtype')
  2628. module.exports = flattenVertexData
  2629. function flattenVertexData (data, output, offset) {
  2630. if (!data) throw new TypeError('must specify data as first parameter')
  2631. offset = +(offset || 0) | 0
  2632. if (Array.isArray(data) && Array.isArray(data[0])) {
  2633. var dim = data[0].length
  2634. var length = data.length * dim
  2635. // no output specified, create a new typed array
  2636. if (!output || typeof output === 'string') {
  2637. output = new (dtype(output || 'float32'))(length + offset)
  2638. }
  2639. var dstLength = output.length - offset
  2640. if (length !== dstLength) {
  2641. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2642. ' does not match destination length ' + dstLength)
  2643. }
  2644. for (var i = 0, k = offset; i < data.length; i++) {
  2645. for (var j = 0; j < dim; j++) {
  2646. output[k++] = data[i][j]
  2647. }
  2648. }
  2649. } else {
  2650. if (!output || typeof output === 'string') {
  2651. // no output, create a new one
  2652. var Ctor = dtype(output || 'float32')
  2653. if (offset === 0) {
  2654. output = new Ctor(data)
  2655. } else {
  2656. output = new Ctor(data.length + offset)
  2657. output.set(data, offset)
  2658. }
  2659. } else {
  2660. // store output in existing array
  2661. output.set(data, offset)
  2662. }
  2663. }
  2664. return output
  2665. }
  2666. },{"dtype":12}],14:[function(_dereq_,module,exports){
  2667. var isFunction = _dereq_('is-function')
  2668. module.exports = forEach
  2669. var toString = Object.prototype.toString
  2670. var hasOwnProperty = Object.prototype.hasOwnProperty
  2671. function forEach(list, iterator, context) {
  2672. if (!isFunction(iterator)) {
  2673. throw new TypeError('iterator must be a function')
  2674. }
  2675. if (arguments.length < 3) {
  2676. context = this
  2677. }
  2678. if (toString.call(list) === '[object Array]')
  2679. forEachArray(list, iterator, context)
  2680. else if (typeof list === 'string')
  2681. forEachString(list, iterator, context)
  2682. else
  2683. forEachObject(list, iterator, context)
  2684. }
  2685. function forEachArray(array, iterator, context) {
  2686. for (var i = 0, len = array.length; i < len; i++) {
  2687. if (hasOwnProperty.call(array, i)) {
  2688. iterator.call(context, array[i], i, array)
  2689. }
  2690. }
  2691. }
  2692. function forEachString(string, iterator, context) {
  2693. for (var i = 0, len = string.length; i < len; i++) {
  2694. // no such thing as a sparse string.
  2695. iterator.call(context, string.charAt(i), i, string)
  2696. }
  2697. }
  2698. function forEachObject(object, iterator, context) {
  2699. for (var k in object) {
  2700. if (hasOwnProperty.call(object, k)) {
  2701. iterator.call(context, object[k], k, object)
  2702. }
  2703. }
  2704. }
  2705. },{"is-function":20}],15:[function(_dereq_,module,exports){
  2706. (function (global){
  2707. if (typeof window !== "undefined") {
  2708. module.exports = window;
  2709. } else if (typeof global !== "undefined") {
  2710. module.exports = global;
  2711. } else if (typeof self !== "undefined"){
  2712. module.exports = self;
  2713. } else {
  2714. module.exports = {};
  2715. }
  2716. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2717. },{}],16:[function(_dereq_,module,exports){
  2718. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  2719. var e, m
  2720. var eLen = nBytes * 8 - mLen - 1
  2721. var eMax = (1 << eLen) - 1
  2722. var eBias = eMax >> 1
  2723. var nBits = -7
  2724. var i = isLE ? (nBytes - 1) : 0
  2725. var d = isLE ? -1 : 1
  2726. var s = buffer[offset + i]
  2727. i += d
  2728. e = s & ((1 << (-nBits)) - 1)
  2729. s >>= (-nBits)
  2730. nBits += eLen
  2731. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2732. m = e & ((1 << (-nBits)) - 1)
  2733. e >>= (-nBits)
  2734. nBits += mLen
  2735. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  2736. if (e === 0) {
  2737. e = 1 - eBias
  2738. } else if (e === eMax) {
  2739. return m ? NaN : ((s ? -1 : 1) * Infinity)
  2740. } else {
  2741. m = m + Math.pow(2, mLen)
  2742. e = e - eBias
  2743. }
  2744. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  2745. }
  2746. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  2747. var e, m, c
  2748. var eLen = nBytes * 8 - mLen - 1
  2749. var eMax = (1 << eLen) - 1
  2750. var eBias = eMax >> 1
  2751. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  2752. var i = isLE ? 0 : (nBytes - 1)
  2753. var d = isLE ? 1 : -1
  2754. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  2755. value = Math.abs(value)
  2756. if (isNaN(value) || value === Infinity) {
  2757. m = isNaN(value) ? 1 : 0
  2758. e = eMax
  2759. } else {
  2760. e = Math.floor(Math.log(value) / Math.LN2)
  2761. if (value * (c = Math.pow(2, -e)) < 1) {
  2762. e--
  2763. c *= 2
  2764. }
  2765. if (e + eBias >= 1) {
  2766. value += rt / c
  2767. } else {
  2768. value += rt * Math.pow(2, 1 - eBias)
  2769. }
  2770. if (value * c >= 2) {
  2771. e++
  2772. c /= 2
  2773. }
  2774. if (e + eBias >= eMax) {
  2775. m = 0
  2776. e = eMax
  2777. } else if (e + eBias >= 1) {
  2778. m = (value * c - 1) * Math.pow(2, mLen)
  2779. e = e + eBias
  2780. } else {
  2781. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  2782. e = 0
  2783. }
  2784. }
  2785. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  2786. e = (e << mLen) | m
  2787. eLen += mLen
  2788. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  2789. buffer[offset + i - d] |= s * 128
  2790. }
  2791. },{}],17:[function(_dereq_,module,exports){
  2792. module.exports = function compile(property) {
  2793. if (!property || typeof property !== 'string')
  2794. throw new Error('must specify property for indexof search')
  2795. return new Function('array', 'value', 'start', [
  2796. 'start = start || 0',
  2797. 'for (var i=start; i<array.length; i++)',
  2798. ' if (array[i]["' + property +'"] === value)',
  2799. ' return i',
  2800. 'return -1'
  2801. ].join('\n'))
  2802. }
  2803. },{}],18:[function(_dereq_,module,exports){
  2804. if (typeof Object.create === 'function') {
  2805. // implementation from standard node.js 'util' module
  2806. module.exports = function inherits(ctor, superCtor) {
  2807. ctor.super_ = superCtor
  2808. ctor.prototype = Object.create(superCtor.prototype, {
  2809. constructor: {
  2810. value: ctor,
  2811. enumerable: false,
  2812. writable: true,
  2813. configurable: true
  2814. }
  2815. });
  2816. };
  2817. } else {
  2818. // old school shim for old browsers
  2819. module.exports = function inherits(ctor, superCtor) {
  2820. ctor.super_ = superCtor
  2821. var TempCtor = function () {}
  2822. TempCtor.prototype = superCtor.prototype
  2823. ctor.prototype = new TempCtor()
  2824. ctor.prototype.constructor = ctor
  2825. }
  2826. }
  2827. },{}],19:[function(_dereq_,module,exports){
  2828. /*!
  2829. * Determine if an object is a Buffer
  2830. *
  2831. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2832. * @license MIT
  2833. */
  2834. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2835. // Object.prototype.constructor. Remove this eventually
  2836. module.exports = function (obj) {
  2837. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2838. }
  2839. function isBuffer (obj) {
  2840. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2841. }
  2842. // For Node v0.10 support. Remove this eventually.
  2843. function isSlowBuffer (obj) {
  2844. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2845. }
  2846. },{}],20:[function(_dereq_,module,exports){
  2847. module.exports = isFunction
  2848. var toString = Object.prototype.toString
  2849. function isFunction (fn) {
  2850. var string = toString.call(fn)
  2851. return string === '[object Function]' ||
  2852. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2853. (typeof window !== 'undefined' &&
  2854. // IE8 and below
  2855. (fn === window.setTimeout ||
  2856. fn === window.alert ||
  2857. fn === window.confirm ||
  2858. fn === window.prompt))
  2859. };
  2860. },{}],21:[function(_dereq_,module,exports){
  2861. 'use strict';
  2862. module.exports = function (x) {
  2863. var type = typeof x;
  2864. return x !== null && (type === 'object' || type === 'function');
  2865. };
  2866. },{}],22:[function(_dereq_,module,exports){
  2867. var toString = {}.toString;
  2868. module.exports = Array.isArray || function (arr) {
  2869. return toString.call(arr) == '[object Array]';
  2870. };
  2871. },{}],23:[function(_dereq_,module,exports){
  2872. var wordWrap = _dereq_('word-wrapper')
  2873. var xtend = _dereq_('xtend')
  2874. var findChar = _dereq_('indexof-property')('id')
  2875. var number = _dereq_('as-number')
  2876. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2877. var M_WIDTHS = ['m', 'w']
  2878. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2879. var TAB_ID = '\t'.charCodeAt(0)
  2880. var SPACE_ID = ' '.charCodeAt(0)
  2881. var ALIGN_LEFT = 0,
  2882. ALIGN_CENTER = 1,
  2883. ALIGN_RIGHT = 2
  2884. module.exports = function createLayout(opt) {
  2885. return new TextLayout(opt)
  2886. }
  2887. function TextLayout(opt) {
  2888. this.glyphs = []
  2889. this._measure = this.computeMetrics.bind(this)
  2890. this.update(opt)
  2891. }
  2892. TextLayout.prototype.update = function(opt) {
  2893. opt = xtend({
  2894. measure: this._measure
  2895. }, opt)
  2896. this._opt = opt
  2897. this._opt.tabSize = number(this._opt.tabSize, 4)
  2898. if (!opt.font)
  2899. throw new Error('must provide a valid bitmap font')
  2900. var glyphs = this.glyphs
  2901. var text = opt.text||''
  2902. var font = opt.font
  2903. this._setupSpaceGlyphs(font)
  2904. var lines = wordWrap.lines(text, opt)
  2905. var minWidth = opt.width || 0
  2906. //clear glyphs
  2907. glyphs.length = 0
  2908. //get max line width
  2909. var maxLineWidth = lines.reduce(function(prev, line) {
  2910. return Math.max(prev, line.width, minWidth)
  2911. }, 0)
  2912. //the pen position
  2913. var x = 0
  2914. var y = 0
  2915. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2916. var baseline = font.common.base
  2917. var descender = lineHeight-baseline
  2918. var letterSpacing = opt.letterSpacing || 0
  2919. var height = lineHeight * lines.length - descender
  2920. var align = getAlignType(this._opt.align)
  2921. //draw text along baseline
  2922. y -= height
  2923. //the metrics for this text layout
  2924. this._width = maxLineWidth
  2925. this._height = height
  2926. this._descender = lineHeight - baseline
  2927. this._baseline = baseline
  2928. this._xHeight = getXHeight(font)
  2929. this._capHeight = getCapHeight(font)
  2930. this._lineHeight = lineHeight
  2931. this._ascender = lineHeight - descender - this._xHeight
  2932. //layout each glyph
  2933. var self = this
  2934. lines.forEach(function(line, lineIndex) {
  2935. var start = line.start
  2936. var end = line.end
  2937. var lineWidth = line.width
  2938. var lastGlyph
  2939. //for each glyph in that line...
  2940. for (var i=start; i<end; i++) {
  2941. var id = text.charCodeAt(i)
  2942. var glyph = self.getGlyph(font, id)
  2943. if (glyph) {
  2944. if (lastGlyph)
  2945. x += getKerning(font, lastGlyph.id, glyph.id)
  2946. var tx = x
  2947. if (align === ALIGN_CENTER)
  2948. tx += (maxLineWidth-lineWidth)/2
  2949. else if (align === ALIGN_RIGHT)
  2950. tx += (maxLineWidth-lineWidth)
  2951. glyphs.push({
  2952. position: [tx, y],
  2953. data: glyph,
  2954. index: i,
  2955. line: lineIndex
  2956. })
  2957. //move pen forward
  2958. x += glyph.xadvance + letterSpacing
  2959. lastGlyph = glyph
  2960. }
  2961. }
  2962. //next line down
  2963. y += lineHeight
  2964. x = 0
  2965. })
  2966. this._linesTotal = lines.length;
  2967. }
  2968. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2969. //These are fallbacks, when the font doesn't include
  2970. //' ' or '\t' glyphs
  2971. this._fallbackSpaceGlyph = null
  2972. this._fallbackTabGlyph = null
  2973. if (!font.chars || font.chars.length === 0)
  2974. return
  2975. //try to get space glyph
  2976. //then fall back to the 'm' or 'w' glyphs
  2977. //then fall back to the first glyph available
  2978. var space = getGlyphById(font, SPACE_ID)
  2979. || getMGlyph(font)
  2980. || font.chars[0]
  2981. //and create a fallback for tab
  2982. var tabWidth = this._opt.tabSize * space.xadvance
  2983. this._fallbackSpaceGlyph = space
  2984. this._fallbackTabGlyph = xtend(space, {
  2985. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2986. xoffset: 0, yoffset: 0, width: 0, height: 0
  2987. })
  2988. }
  2989. TextLayout.prototype.getGlyph = function(font, id) {
  2990. var glyph = getGlyphById(font, id)
  2991. if (glyph)
  2992. return glyph
  2993. else if (id === TAB_ID)
  2994. return this._fallbackTabGlyph
  2995. else if (id === SPACE_ID)
  2996. return this._fallbackSpaceGlyph
  2997. return null
  2998. }
  2999. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  3000. var letterSpacing = this._opt.letterSpacing || 0
  3001. var font = this._opt.font
  3002. var curPen = 0
  3003. var curWidth = 0
  3004. var count = 0
  3005. var glyph
  3006. var lastGlyph
  3007. if (!font.chars || font.chars.length === 0) {
  3008. return {
  3009. start: start,
  3010. end: start,
  3011. width: 0
  3012. }
  3013. }
  3014. end = Math.min(text.length, end)
  3015. for (var i=start; i < end; i++) {
  3016. var id = text.charCodeAt(i)
  3017. var glyph = this.getGlyph(font, id)
  3018. if (glyph) {
  3019. //move pen forward
  3020. var xoff = glyph.xoffset
  3021. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  3022. curPen += kern
  3023. var nextPen = curPen + glyph.xadvance + letterSpacing
  3024. var nextWidth = curPen + glyph.width
  3025. //we've hit our limit; we can't move onto the next glyph
  3026. if (nextWidth >= width || nextPen >= width)
  3027. break
  3028. //otherwise continue along our line
  3029. curPen = nextPen
  3030. curWidth = nextWidth
  3031. lastGlyph = glyph
  3032. }
  3033. count++
  3034. }
  3035. //make sure rightmost edge lines up with rendered glyphs
  3036. if (lastGlyph)
  3037. curWidth += lastGlyph.xoffset
  3038. return {
  3039. start: start,
  3040. end: start + count,
  3041. width: curWidth
  3042. }
  3043. }
  3044. //getters for the private vars
  3045. ;['width', 'height',
  3046. 'descender', 'ascender',
  3047. 'xHeight', 'baseline',
  3048. 'capHeight',
  3049. 'lineHeight' ].forEach(addGetter)
  3050. function addGetter(name) {
  3051. Object.defineProperty(TextLayout.prototype, name, {
  3052. get: wrapper(name),
  3053. configurable: true
  3054. })
  3055. }
  3056. //create lookups for private vars
  3057. function wrapper(name) {
  3058. return (new Function([
  3059. 'return function '+name+'() {',
  3060. ' return this._'+name,
  3061. '}'
  3062. ].join('\n')))()
  3063. }
  3064. function getGlyphById(font, id) {
  3065. if (!font.chars || font.chars.length === 0)
  3066. return null
  3067. var glyphIdx = findChar(font.chars, id)
  3068. if (glyphIdx >= 0)
  3069. return font.chars[glyphIdx]
  3070. return null
  3071. }
  3072. function getXHeight(font) {
  3073. for (var i=0; i<X_HEIGHTS.length; i++) {
  3074. var id = X_HEIGHTS[i].charCodeAt(0)
  3075. var idx = findChar(font.chars, id)
  3076. if (idx >= 0)
  3077. return font.chars[idx].height
  3078. }
  3079. return 0
  3080. }
  3081. function getMGlyph(font) {
  3082. for (var i=0; i<M_WIDTHS.length; i++) {
  3083. var id = M_WIDTHS[i].charCodeAt(0)
  3084. var idx = findChar(font.chars, id)
  3085. if (idx >= 0)
  3086. return font.chars[idx]
  3087. }
  3088. return 0
  3089. }
  3090. function getCapHeight(font) {
  3091. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3092. var id = CAP_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 getKerning(font, left, right) {
  3100. if (!font.kernings || font.kernings.length === 0)
  3101. return 0
  3102. var table = font.kernings
  3103. for (var i=0; i<table.length; i++) {
  3104. var kern = table[i]
  3105. if (kern.first === left && kern.second === right)
  3106. return kern.amount
  3107. }
  3108. return 0
  3109. }
  3110. function getAlignType(align) {
  3111. if (align === 'center')
  3112. return ALIGN_CENTER
  3113. else if (align === 'right')
  3114. return ALIGN_RIGHT
  3115. return ALIGN_LEFT
  3116. }
  3117. },{"as-number":3,"indexof-property":17,"word-wrapper":72,"xtend":75}],24:[function(_dereq_,module,exports){
  3118. (function (Buffer){
  3119. var xhr = _dereq_('xhr')
  3120. var noop = function(){}
  3121. var parseASCII = _dereq_('parse-bmfont-ascii')
  3122. var parseXML = _dereq_('parse-bmfont-xml')
  3123. var readBinary = _dereq_('parse-bmfont-binary')
  3124. var isBinaryFormat = _dereq_('./lib/is-binary')
  3125. var xtend = _dereq_('xtend')
  3126. var xml2 = (function hasXML2() {
  3127. return window.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3128. })()
  3129. module.exports = function(opt, cb) {
  3130. cb = typeof cb === 'function' ? cb : noop
  3131. if (typeof opt === 'string')
  3132. opt = { uri: opt }
  3133. else if (!opt)
  3134. opt = {}
  3135. var expectBinary = opt.binary
  3136. if (expectBinary)
  3137. opt = getBinaryOpts(opt)
  3138. xhr(opt, function(err, res, body) {
  3139. if (err)
  3140. return cb(err)
  3141. if (!/^2/.test(res.statusCode))
  3142. return cb(new Error('http status code: '+res.statusCode))
  3143. if (!body)
  3144. return cb(new Error('no body result'))
  3145. var binary = false
  3146. //if the response type is an array buffer,
  3147. //we need to convert it into a regular Buffer object
  3148. if (isArrayBuffer(body)) {
  3149. var array = new Uint8Array(body)
  3150. body = new Buffer(array, 'binary')
  3151. }
  3152. //now check the string/Buffer response
  3153. //and see if it has a binary BMF header
  3154. if (isBinaryFormat(body)) {
  3155. binary = true
  3156. //if we have a string, turn it into a Buffer
  3157. if (typeof body === 'string')
  3158. body = new Buffer(body, 'binary')
  3159. }
  3160. //we are not parsing a binary format, just ASCII/XML/etc
  3161. if (!binary) {
  3162. //might still be a buffer if responseType is 'arraybuffer'
  3163. if (Buffer.isBuffer(body))
  3164. body = body.toString(opt.encoding)
  3165. body = body.trim()
  3166. }
  3167. var result
  3168. try {
  3169. var type = res.headers['content-type']
  3170. if (binary)
  3171. result = readBinary(body)
  3172. else if (/json/.test(type) || body.charAt(0) === '{')
  3173. result = JSON.parse(body)
  3174. else if (/xml/.test(type) || body.charAt(0) === '<')
  3175. result = parseXML(body)
  3176. else
  3177. result = parseASCII(body)
  3178. } catch (e) {
  3179. cb(new Error('error parsing font '+e.message))
  3180. cb = noop
  3181. }
  3182. cb(null, result)
  3183. })
  3184. }
  3185. function isArrayBuffer(arr) {
  3186. var str = Object.prototype.toString
  3187. return str.call(arr) === '[object ArrayBuffer]'
  3188. }
  3189. function getBinaryOpts(opt) {
  3190. //IE10+ and other modern browsers support array buffers
  3191. if (xml2)
  3192. return xtend(opt, { responseType: 'arraybuffer' })
  3193. if (typeof window.XMLHttpRequest === 'undefined')
  3194. throw new Error('your browser does not support XHR loading')
  3195. //IE9 and XML1 browsers could still use an override
  3196. var req = new window.XMLHttpRequest()
  3197. req.overrideMimeType('text/plain; charset=x-user-defined')
  3198. return xtend({
  3199. xhr: req
  3200. }, opt)
  3201. }
  3202. }).call(this,_dereq_("buffer").Buffer)
  3203. },{"./lib/is-binary":25,"buffer":7,"parse-bmfont-ascii":27,"parse-bmfont-binary":28,"parse-bmfont-xml":29,"xhr":73,"xtend":75}],25:[function(_dereq_,module,exports){
  3204. (function (Buffer){
  3205. var equal = _dereq_('buffer-equal')
  3206. var HEADER = new Buffer([66, 77, 70, 3])
  3207. module.exports = function(buf) {
  3208. if (typeof buf === 'string')
  3209. return buf.substring(0, 3) === 'BMF'
  3210. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3211. }
  3212. }).call(this,_dereq_("buffer").Buffer)
  3213. },{"buffer":7,"buffer-equal":6}],26:[function(_dereq_,module,exports){
  3214. 'use strict';
  3215. /* eslint-disable no-unused-vars */
  3216. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3217. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3218. function toObject(val) {
  3219. if (val === null || val === undefined) {
  3220. throw new TypeError('Object.assign cannot be called with null or undefined');
  3221. }
  3222. return Object(val);
  3223. }
  3224. function shouldUseNative() {
  3225. try {
  3226. if (!Object.assign) {
  3227. return false;
  3228. }
  3229. // Detect buggy property enumeration order in older V8 versions.
  3230. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3231. var test1 = new String('abc'); // eslint-disable-line
  3232. test1[5] = 'de';
  3233. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3234. return false;
  3235. }
  3236. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3237. var test2 = {};
  3238. for (var i = 0; i < 10; i++) {
  3239. test2['_' + String.fromCharCode(i)] = i;
  3240. }
  3241. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3242. return test2[n];
  3243. });
  3244. if (order2.join('') !== '0123456789') {
  3245. return false;
  3246. }
  3247. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3248. var test3 = {};
  3249. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3250. test3[letter] = letter;
  3251. });
  3252. if (Object.keys(Object.assign({}, test3)).join('') !==
  3253. 'abcdefghijklmnopqrst') {
  3254. return false;
  3255. }
  3256. return true;
  3257. } catch (e) {
  3258. // We don't expect any of the above to throw, but better to be safe.
  3259. return false;
  3260. }
  3261. }
  3262. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3263. var from;
  3264. var to = toObject(target);
  3265. var symbols;
  3266. for (var s = 1; s < arguments.length; s++) {
  3267. from = Object(arguments[s]);
  3268. for (var key in from) {
  3269. if (hasOwnProperty.call(from, key)) {
  3270. to[key] = from[key];
  3271. }
  3272. }
  3273. if (Object.getOwnPropertySymbols) {
  3274. symbols = Object.getOwnPropertySymbols(from);
  3275. for (var i = 0; i < symbols.length; i++) {
  3276. if (propIsEnumerable.call(from, symbols[i])) {
  3277. to[symbols[i]] = from[symbols[i]];
  3278. }
  3279. }
  3280. }
  3281. }
  3282. return to;
  3283. };
  3284. },{}],27:[function(_dereq_,module,exports){
  3285. module.exports = function parseBMFontAscii(data) {
  3286. if (!data)
  3287. throw new Error('no data provided')
  3288. data = data.toString().trim()
  3289. var output = {
  3290. pages: [],
  3291. chars: [],
  3292. kernings: []
  3293. }
  3294. var lines = data.split(/\r\n?|\n/g)
  3295. if (lines.length === 0)
  3296. throw new Error('no data in BMFont file')
  3297. for (var i = 0; i < lines.length; i++) {
  3298. var lineData = splitLine(lines[i], i)
  3299. if (!lineData) //skip empty lines
  3300. continue
  3301. if (lineData.key === 'page') {
  3302. if (typeof lineData.data.id !== 'number')
  3303. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3304. if (typeof lineData.data.file !== 'string')
  3305. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3306. output.pages[lineData.data.id] = lineData.data.file
  3307. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3308. //... do nothing for these two ...
  3309. } else if (lineData.key === 'char') {
  3310. output.chars.push(lineData.data)
  3311. } else if (lineData.key === 'kerning') {
  3312. output.kernings.push(lineData.data)
  3313. } else {
  3314. output[lineData.key] = lineData.data
  3315. }
  3316. }
  3317. return output
  3318. }
  3319. function splitLine(line, idx) {
  3320. line = line.replace(/\t+/g, ' ').trim()
  3321. if (!line)
  3322. return null
  3323. var space = line.indexOf(' ')
  3324. if (space === -1)
  3325. throw new Error("no named row at line " + idx)
  3326. var key = line.substring(0, space)
  3327. line = line.substring(space + 1)
  3328. //clear "letter" field as it is non-standard and
  3329. //requires additional complexity to parse " / = symbols
  3330. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3331. line = line.split("=")
  3332. line = line.map(function(str) {
  3333. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3334. })
  3335. var data = []
  3336. for (var i = 0; i < line.length; i++) {
  3337. var dt = line[i]
  3338. if (i === 0) {
  3339. data.push({
  3340. key: dt[0],
  3341. data: ""
  3342. })
  3343. } else if (i === line.length - 1) {
  3344. data[data.length - 1].data = parseData(dt[0])
  3345. } else {
  3346. data[data.length - 1].data = parseData(dt[0])
  3347. data.push({
  3348. key: dt[1],
  3349. data: ""
  3350. })
  3351. }
  3352. }
  3353. var out = {
  3354. key: key,
  3355. data: {}
  3356. }
  3357. data.forEach(function(v) {
  3358. out.data[v.key] = v.data;
  3359. })
  3360. return out
  3361. }
  3362. function parseData(data) {
  3363. if (!data || data.length === 0)
  3364. return ""
  3365. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3366. return data.substring(1, data.length - 1)
  3367. if (data.indexOf(',') !== -1)
  3368. return parseIntList(data)
  3369. return parseInt(data, 10)
  3370. }
  3371. function parseIntList(data) {
  3372. return data.split(',').map(function(val) {
  3373. return parseInt(val, 10)
  3374. })
  3375. }
  3376. },{}],28:[function(_dereq_,module,exports){
  3377. var HEADER = [66, 77, 70]
  3378. module.exports = function readBMFontBinary(buf) {
  3379. if (buf.length < 6)
  3380. throw new Error('invalid buffer length for BMFont')
  3381. var header = HEADER.every(function(byte, i) {
  3382. return buf.readUInt8(i) === byte
  3383. })
  3384. if (!header)
  3385. throw new Error('BMFont missing BMF byte header')
  3386. var i = 3
  3387. var vers = buf.readUInt8(i++)
  3388. if (vers > 3)
  3389. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3390. var target = { kernings: [], chars: [] }
  3391. for (var b=0; b<5; b++)
  3392. i += readBlock(target, buf, i)
  3393. return target
  3394. }
  3395. function readBlock(target, buf, i) {
  3396. if (i > buf.length-1)
  3397. return 0
  3398. var blockID = buf.readUInt8(i++)
  3399. var blockSize = buf.readInt32LE(i)
  3400. i += 4
  3401. switch(blockID) {
  3402. case 1:
  3403. target.info = readInfo(buf, i)
  3404. break
  3405. case 2:
  3406. target.common = readCommon(buf, i)
  3407. break
  3408. case 3:
  3409. target.pages = readPages(buf, i, blockSize)
  3410. break
  3411. case 4:
  3412. target.chars = readChars(buf, i, blockSize)
  3413. break
  3414. case 5:
  3415. target.kernings = readKernings(buf, i, blockSize)
  3416. break
  3417. }
  3418. return 5 + blockSize
  3419. }
  3420. function readInfo(buf, i) {
  3421. var info = {}
  3422. info.size = buf.readInt16LE(i)
  3423. var bitField = buf.readUInt8(i+2)
  3424. info.smooth = (bitField >> 7) & 1
  3425. info.unicode = (bitField >> 6) & 1
  3426. info.italic = (bitField >> 5) & 1
  3427. info.bold = (bitField >> 4) & 1
  3428. //fixedHeight is only mentioned in binary spec
  3429. if ((bitField >> 3) & 1)
  3430. info.fixedHeight = 1
  3431. info.charset = buf.readUInt8(i+3) || ''
  3432. info.stretchH = buf.readUInt16LE(i+4)
  3433. info.aa = buf.readUInt8(i+6)
  3434. info.padding = [
  3435. buf.readInt8(i+7),
  3436. buf.readInt8(i+8),
  3437. buf.readInt8(i+9),
  3438. buf.readInt8(i+10)
  3439. ]
  3440. info.spacing = [
  3441. buf.readInt8(i+11),
  3442. buf.readInt8(i+12)
  3443. ]
  3444. info.outline = buf.readUInt8(i+13)
  3445. info.face = readStringNT(buf, i+14)
  3446. return info
  3447. }
  3448. function readCommon(buf, i) {
  3449. var common = {}
  3450. common.lineHeight = buf.readUInt16LE(i)
  3451. common.base = buf.readUInt16LE(i+2)
  3452. common.scaleW = buf.readUInt16LE(i+4)
  3453. common.scaleH = buf.readUInt16LE(i+6)
  3454. common.pages = buf.readUInt16LE(i+8)
  3455. var bitField = buf.readUInt8(i+10)
  3456. common.packed = 0
  3457. common.alphaChnl = buf.readUInt8(i+11)
  3458. common.redChnl = buf.readUInt8(i+12)
  3459. common.greenChnl = buf.readUInt8(i+13)
  3460. common.blueChnl = buf.readUInt8(i+14)
  3461. return common
  3462. }
  3463. function readPages(buf, i, size) {
  3464. var pages = []
  3465. var text = readNameNT(buf, i)
  3466. var len = text.length+1
  3467. var count = size / len
  3468. for (var c=0; c<count; c++) {
  3469. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3470. i += len
  3471. }
  3472. return pages
  3473. }
  3474. function readChars(buf, i, blockSize) {
  3475. var chars = []
  3476. var count = blockSize / 20
  3477. for (var c=0; c<count; c++) {
  3478. var char = {}
  3479. var off = c*20
  3480. char.id = buf.readUInt32LE(i + 0 + off)
  3481. char.x = buf.readUInt16LE(i + 4 + off)
  3482. char.y = buf.readUInt16LE(i + 6 + off)
  3483. char.width = buf.readUInt16LE(i + 8 + off)
  3484. char.height = buf.readUInt16LE(i + 10 + off)
  3485. char.xoffset = buf.readInt16LE(i + 12 + off)
  3486. char.yoffset = buf.readInt16LE(i + 14 + off)
  3487. char.xadvance = buf.readInt16LE(i + 16 + off)
  3488. char.page = buf.readUInt8(i + 18 + off)
  3489. char.chnl = buf.readUInt8(i + 19 + off)
  3490. chars[c] = char
  3491. }
  3492. return chars
  3493. }
  3494. function readKernings(buf, i, blockSize) {
  3495. var kernings = []
  3496. var count = blockSize / 10
  3497. for (var c=0; c<count; c++) {
  3498. var kern = {}
  3499. var off = c*10
  3500. kern.first = buf.readUInt32LE(i + 0 + off)
  3501. kern.second = buf.readUInt32LE(i + 4 + off)
  3502. kern.amount = buf.readInt16LE(i + 8 + off)
  3503. kernings[c] = kern
  3504. }
  3505. return kernings
  3506. }
  3507. function readNameNT(buf, offset) {
  3508. var pos=offset
  3509. for (; pos<buf.length; pos++) {
  3510. if (buf[pos] === 0x00)
  3511. break
  3512. }
  3513. return buf.slice(offset, pos)
  3514. }
  3515. function readStringNT(buf, offset) {
  3516. return readNameNT(buf, offset).toString('utf8')
  3517. }
  3518. },{}],29:[function(_dereq_,module,exports){
  3519. var parseAttributes = _dereq_('./parse-attribs')
  3520. var parseFromString = _dereq_('xml-parse-from-string')
  3521. //In some cases element.attribute.nodeName can return
  3522. //all lowercase values.. so we need to map them to the correct
  3523. //case
  3524. var NAME_MAP = {
  3525. scaleh: 'scaleH',
  3526. scalew: 'scaleW',
  3527. stretchh: 'stretchH',
  3528. lineheight: 'lineHeight',
  3529. alphachnl: 'alphaChnl',
  3530. redchnl: 'redChnl',
  3531. greenchnl: 'greenChnl',
  3532. bluechnl: 'blueChnl'
  3533. }
  3534. module.exports = function parse(data) {
  3535. data = data.toString()
  3536. var xmlRoot = parseFromString(data)
  3537. var output = {
  3538. pages: [],
  3539. chars: [],
  3540. kernings: []
  3541. }
  3542. //get config settings
  3543. ;['info', 'common'].forEach(function(key) {
  3544. var element = xmlRoot.getElementsByTagName(key)[0]
  3545. if (element)
  3546. output[key] = parseAttributes(getAttribs(element))
  3547. })
  3548. //get page info
  3549. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3550. if (!pageRoot)
  3551. throw new Error('malformed file -- no <pages> element')
  3552. var pages = pageRoot.getElementsByTagName('page')
  3553. for (var i=0; i<pages.length; i++) {
  3554. var p = pages[i]
  3555. var id = parseInt(p.getAttribute('id'), 10)
  3556. var file = p.getAttribute('file')
  3557. if (isNaN(id))
  3558. throw new Error('malformed file -- page "id" attribute is NaN')
  3559. if (!file)
  3560. throw new Error('malformed file -- needs page "file" attribute')
  3561. output.pages[parseInt(id, 10)] = file
  3562. }
  3563. //get kernings / chars
  3564. ;['chars', 'kernings'].forEach(function(key) {
  3565. var element = xmlRoot.getElementsByTagName(key)[0]
  3566. if (!element)
  3567. return
  3568. var childTag = key.substring(0, key.length-1)
  3569. var children = element.getElementsByTagName(childTag)
  3570. for (var i=0; i<children.length; i++) {
  3571. var child = children[i]
  3572. output[key].push(parseAttributes(getAttribs(child)))
  3573. }
  3574. })
  3575. return output
  3576. }
  3577. function getAttribs(element) {
  3578. var attribs = getAttribList(element)
  3579. return attribs.reduce(function(dict, attrib) {
  3580. var key = mapName(attrib.nodeName)
  3581. dict[key] = attrib.nodeValue
  3582. return dict
  3583. }, {})
  3584. }
  3585. function getAttribList(element) {
  3586. //IE8+ and modern browsers
  3587. var attribs = []
  3588. for (var i=0; i<element.attributes.length; i++)
  3589. attribs.push(element.attributes[i])
  3590. return attribs
  3591. }
  3592. function mapName(nodeName) {
  3593. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3594. }
  3595. },{"./parse-attribs":30,"xml-parse-from-string":74}],30:[function(_dereq_,module,exports){
  3596. //Some versions of GlyphDesigner have a typo
  3597. //that causes some bugs with parsing.
  3598. //Need to confirm with recent version of the software
  3599. //to see whether this is still an issue or not.
  3600. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3601. module.exports = function parseAttributes(obj) {
  3602. if (GLYPH_DESIGNER_ERROR in obj) {
  3603. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3604. delete obj[GLYPH_DESIGNER_ERROR]
  3605. }
  3606. for (var k in obj) {
  3607. if (k === 'face' || k === 'charset')
  3608. continue
  3609. else if (k === 'padding' || k === 'spacing')
  3610. obj[k] = parseIntList(obj[k])
  3611. else
  3612. obj[k] = parseInt(obj[k], 10)
  3613. }
  3614. return obj
  3615. }
  3616. function parseIntList(data) {
  3617. return data.split(',').map(function(val) {
  3618. return parseInt(val, 10)
  3619. })
  3620. }
  3621. },{}],31:[function(_dereq_,module,exports){
  3622. var trim = _dereq_('trim')
  3623. , forEach = _dereq_('for-each')
  3624. , isArray = function(arg) {
  3625. return Object.prototype.toString.call(arg) === '[object Array]';
  3626. }
  3627. module.exports = function (headers) {
  3628. if (!headers)
  3629. return {}
  3630. var result = {}
  3631. forEach(
  3632. trim(headers).split('\n')
  3633. , function (row) {
  3634. var index = row.indexOf(':')
  3635. , key = trim(row.slice(0, index)).toLowerCase()
  3636. , value = trim(row.slice(index + 1))
  3637. if (typeof(result[key]) === 'undefined') {
  3638. result[key] = value
  3639. } else if (isArray(result[key])) {
  3640. result[key].push(value)
  3641. } else {
  3642. result[key] = [ result[key], value ]
  3643. }
  3644. }
  3645. )
  3646. return result
  3647. }
  3648. },{"for-each":14,"trim":46}],32:[function(_dereq_,module,exports){
  3649. (function (global){
  3650. var performance = global.performance || {};
  3651. var present = (function () {
  3652. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3653. while (names.length) {
  3654. var name = names.shift();
  3655. if (name in performance) {
  3656. return performance[name].bind(performance);
  3657. }
  3658. }
  3659. var dateNow = Date.now || function () { return new Date().getTime(); };
  3660. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3661. return function () {
  3662. return dateNow() - navigationStart;
  3663. };
  3664. }());
  3665. present.performanceNow = performance.now;
  3666. present.noConflict = function () {
  3667. performance.now = present.performanceNow;
  3668. };
  3669. present.conflict = function () {
  3670. performance.now = present;
  3671. };
  3672. present.conflict();
  3673. module.exports = present;
  3674. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3675. },{}],33:[function(_dereq_,module,exports){
  3676. // shim for using process in browser
  3677. var process = module.exports = {};
  3678. // cached from whatever global is present so that test runners that stub it
  3679. // don't break things. But we need to wrap it in a try catch in case it is
  3680. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3681. // function because try/catches deoptimize in certain engines.
  3682. var cachedSetTimeout;
  3683. var cachedClearTimeout;
  3684. function defaultSetTimout() {
  3685. throw new Error('setTimeout has not been defined');
  3686. }
  3687. function defaultClearTimeout () {
  3688. throw new Error('clearTimeout has not been defined');
  3689. }
  3690. (function () {
  3691. try {
  3692. if (typeof setTimeout === 'function') {
  3693. cachedSetTimeout = setTimeout;
  3694. } else {
  3695. cachedSetTimeout = defaultSetTimout;
  3696. }
  3697. } catch (e) {
  3698. cachedSetTimeout = defaultSetTimout;
  3699. }
  3700. try {
  3701. if (typeof clearTimeout === 'function') {
  3702. cachedClearTimeout = clearTimeout;
  3703. } else {
  3704. cachedClearTimeout = defaultClearTimeout;
  3705. }
  3706. } catch (e) {
  3707. cachedClearTimeout = defaultClearTimeout;
  3708. }
  3709. } ())
  3710. function runTimeout(fun) {
  3711. if (cachedSetTimeout === setTimeout) {
  3712. //normal enviroments in sane situations
  3713. return setTimeout(fun, 0);
  3714. }
  3715. // if setTimeout wasn't available but was latter defined
  3716. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  3717. cachedSetTimeout = setTimeout;
  3718. return setTimeout(fun, 0);
  3719. }
  3720. try {
  3721. // when when somebody has screwed with setTimeout but no I.E. maddness
  3722. return cachedSetTimeout(fun, 0);
  3723. } catch(e){
  3724. try {
  3725. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3726. return cachedSetTimeout.call(null, fun, 0);
  3727. } catch(e){
  3728. // 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
  3729. return cachedSetTimeout.call(this, fun, 0);
  3730. }
  3731. }
  3732. }
  3733. function runClearTimeout(marker) {
  3734. if (cachedClearTimeout === clearTimeout) {
  3735. //normal enviroments in sane situations
  3736. return clearTimeout(marker);
  3737. }
  3738. // if clearTimeout wasn't available but was latter defined
  3739. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  3740. cachedClearTimeout = clearTimeout;
  3741. return clearTimeout(marker);
  3742. }
  3743. try {
  3744. // when when somebody has screwed with setTimeout but no I.E. maddness
  3745. return cachedClearTimeout(marker);
  3746. } catch (e){
  3747. try {
  3748. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  3749. return cachedClearTimeout.call(null, marker);
  3750. } catch (e){
  3751. // 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.
  3752. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  3753. return cachedClearTimeout.call(this, marker);
  3754. }
  3755. }
  3756. }
  3757. var queue = [];
  3758. var draining = false;
  3759. var currentQueue;
  3760. var queueIndex = -1;
  3761. function cleanUpNextTick() {
  3762. if (!draining || !currentQueue) {
  3763. return;
  3764. }
  3765. draining = false;
  3766. if (currentQueue.length) {
  3767. queue = currentQueue.concat(queue);
  3768. } else {
  3769. queueIndex = -1;
  3770. }
  3771. if (queue.length) {
  3772. drainQueue();
  3773. }
  3774. }
  3775. function drainQueue() {
  3776. if (draining) {
  3777. return;
  3778. }
  3779. var timeout = runTimeout(cleanUpNextTick);
  3780. draining = true;
  3781. var len = queue.length;
  3782. while(len) {
  3783. currentQueue = queue;
  3784. queue = [];
  3785. while (++queueIndex < len) {
  3786. if (currentQueue) {
  3787. currentQueue[queueIndex].run();
  3788. }
  3789. }
  3790. queueIndex = -1;
  3791. len = queue.length;
  3792. }
  3793. currentQueue = null;
  3794. draining = false;
  3795. runClearTimeout(timeout);
  3796. }
  3797. process.nextTick = function (fun) {
  3798. var args = new Array(arguments.length - 1);
  3799. if (arguments.length > 1) {
  3800. for (var i = 1; i < arguments.length; i++) {
  3801. args[i - 1] = arguments[i];
  3802. }
  3803. }
  3804. queue.push(new Item(fun, args));
  3805. if (queue.length === 1 && !draining) {
  3806. runTimeout(drainQueue);
  3807. }
  3808. };
  3809. // v8 likes predictible objects
  3810. function Item(fun, array) {
  3811. this.fun = fun;
  3812. this.array = array;
  3813. }
  3814. Item.prototype.run = function () {
  3815. this.fun.apply(null, this.array);
  3816. };
  3817. process.title = 'browser';
  3818. process.browser = true;
  3819. process.env = {};
  3820. process.argv = [];
  3821. process.version = ''; // empty string to avoid regexp issues
  3822. process.versions = {};
  3823. function noop() {}
  3824. process.on = noop;
  3825. process.addListener = noop;
  3826. process.once = noop;
  3827. process.off = noop;
  3828. process.removeListener = noop;
  3829. process.removeAllListeners = noop;
  3830. process.emit = noop;
  3831. process.binding = function (name) {
  3832. throw new Error('process.binding is not supported');
  3833. };
  3834. process.cwd = function () { return '/' };
  3835. process.chdir = function (dir) {
  3836. throw new Error('process.chdir is not supported');
  3837. };
  3838. process.umask = function() { return 0; };
  3839. },{}],34:[function(_dereq_,module,exports){
  3840. (function(root) {
  3841. // Store setTimeout reference so promise-polyfill will be unaffected by
  3842. // other code modifying setTimeout (like sinon.useFakeTimers())
  3843. var setTimeoutFunc = setTimeout;
  3844. // Use polyfill for setImmediate for performance gains
  3845. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3846. function(fn) { setTimeoutFunc(fn, 1); };
  3847. // Polyfill for Function.prototype.bind
  3848. function bind(fn, thisArg) {
  3849. return function() {
  3850. fn.apply(thisArg, arguments);
  3851. }
  3852. }
  3853. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3854. function Promise(fn) {
  3855. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3856. if (typeof fn !== 'function') throw new TypeError('not a function');
  3857. this._state = null;
  3858. this._value = null;
  3859. this._deferreds = []
  3860. doResolve(fn, bind(resolve, this), bind(reject, this))
  3861. }
  3862. function handle(deferred) {
  3863. var me = this;
  3864. if (this._state === null) {
  3865. this._deferreds.push(deferred);
  3866. return
  3867. }
  3868. asap(function() {
  3869. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3870. if (cb === null) {
  3871. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3872. return;
  3873. }
  3874. var ret;
  3875. try {
  3876. ret = cb(me._value);
  3877. }
  3878. catch (e) {
  3879. deferred.reject(e);
  3880. return;
  3881. }
  3882. deferred.resolve(ret);
  3883. })
  3884. }
  3885. function resolve(newValue) {
  3886. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3887. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3888. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3889. var then = newValue.then;
  3890. if (typeof then === 'function') {
  3891. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3892. return;
  3893. }
  3894. }
  3895. this._state = true;
  3896. this._value = newValue;
  3897. finale.call(this);
  3898. } catch (e) { reject.call(this, e); }
  3899. }
  3900. function reject(newValue) {
  3901. this._state = false;
  3902. this._value = newValue;
  3903. finale.call(this);
  3904. }
  3905. function finale() {
  3906. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3907. handle.call(this, this._deferreds[i]);
  3908. }
  3909. this._deferreds = null;
  3910. }
  3911. function Handler(onFulfilled, onRejected, resolve, reject){
  3912. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3913. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3914. this.resolve = resolve;
  3915. this.reject = reject;
  3916. }
  3917. /**
  3918. * Take a potentially misbehaving resolver function and make sure
  3919. * onFulfilled and onRejected are only called once.
  3920. *
  3921. * Makes no guarantees about asynchrony.
  3922. */
  3923. function doResolve(fn, onFulfilled, onRejected) {
  3924. var done = false;
  3925. try {
  3926. fn(function (value) {
  3927. if (done) return;
  3928. done = true;
  3929. onFulfilled(value);
  3930. }, function (reason) {
  3931. if (done) return;
  3932. done = true;
  3933. onRejected(reason);
  3934. })
  3935. } catch (ex) {
  3936. if (done) return;
  3937. done = true;
  3938. onRejected(ex);
  3939. }
  3940. }
  3941. Promise.prototype['catch'] = function (onRejected) {
  3942. return this.then(null, onRejected);
  3943. };
  3944. Promise.prototype.then = function(onFulfilled, onRejected) {
  3945. var me = this;
  3946. return new Promise(function(resolve, reject) {
  3947. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3948. })
  3949. };
  3950. Promise.all = function () {
  3951. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3952. return new Promise(function (resolve, reject) {
  3953. if (args.length === 0) return resolve([]);
  3954. var remaining = args.length;
  3955. function res(i, val) {
  3956. try {
  3957. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3958. var then = val.then;
  3959. if (typeof then === 'function') {
  3960. then.call(val, function (val) { res(i, val) }, reject);
  3961. return;
  3962. }
  3963. }
  3964. args[i] = val;
  3965. if (--remaining === 0) {
  3966. resolve(args);
  3967. }
  3968. } catch (ex) {
  3969. reject(ex);
  3970. }
  3971. }
  3972. for (var i = 0; i < args.length; i++) {
  3973. res(i, args[i]);
  3974. }
  3975. });
  3976. };
  3977. Promise.resolve = function (value) {
  3978. if (value && typeof value === 'object' && value.constructor === Promise) {
  3979. return value;
  3980. }
  3981. return new Promise(function (resolve) {
  3982. resolve(value);
  3983. });
  3984. };
  3985. Promise.reject = function (value) {
  3986. return new Promise(function (resolve, reject) {
  3987. reject(value);
  3988. });
  3989. };
  3990. Promise.race = function (values) {
  3991. return new Promise(function (resolve, reject) {
  3992. for(var i = 0, len = values.length; i < len; i++) {
  3993. values[i].then(resolve, reject);
  3994. }
  3995. });
  3996. };
  3997. /**
  3998. * Set the immediate function to execute callbacks
  3999. * @param fn {function} Function to execute
  4000. * @private
  4001. */
  4002. Promise._setImmediateFn = function _setImmediateFn(fn) {
  4003. asap = fn;
  4004. };
  4005. if (typeof module !== 'undefined' && module.exports) {
  4006. module.exports = Promise;
  4007. } else if (!root.Promise) {
  4008. root.Promise = Promise;
  4009. }
  4010. })(this);
  4011. },{}],35:[function(_dereq_,module,exports){
  4012. var dtype = _dereq_('dtype')
  4013. var anArray = _dereq_('an-array')
  4014. var isBuffer = _dereq_('is-buffer')
  4015. var CW = [0, 2, 3]
  4016. var CCW = [2, 1, 3]
  4017. module.exports = function createQuadElements(array, opt) {
  4018. //if user didn't specify an output array
  4019. if (!array || !(anArray(array) || isBuffer(array))) {
  4020. opt = array || {}
  4021. array = null
  4022. }
  4023. if (typeof opt === 'number') //backwards-compatible
  4024. opt = { count: opt }
  4025. else
  4026. opt = opt || {}
  4027. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  4028. var count = typeof opt.count === 'number' ? opt.count : 1
  4029. var start = (opt.start || 0)
  4030. var dir = opt.clockwise !== false ? CW : CCW,
  4031. a = dir[0],
  4032. b = dir[1],
  4033. c = dir[2]
  4034. var numIndices = count * 6
  4035. var indices = array || new (dtype(type))(numIndices)
  4036. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  4037. var x = i + start
  4038. indices[x + 0] = j + 0
  4039. indices[x + 1] = j + 1
  4040. indices[x + 2] = j + 2
  4041. indices[x + 3] = j + a
  4042. indices[x + 4] = j + b
  4043. indices[x + 5] = j + c
  4044. }
  4045. return indices
  4046. }
  4047. },{"an-array":2,"dtype":12,"is-buffer":19}],36:[function(_dereq_,module,exports){
  4048. /*:: type Attr = { [key: string]: string } */
  4049. /*
  4050. style-attr
  4051. ====
  4052. Very simple parsing and stringifying of style attributes.
  4053. `parse`
  4054. ----
  4055. Convert a style attribute string to an object.
  4056. */
  4057. /*:: declare function parse (raw: string): Attr */
  4058. function parse(raw) {
  4059. var trim = function (s) {
  4060. return s.trim();
  4061. };
  4062. var obj = {};
  4063. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  4064. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  4065. var pos = item.indexOf(':');
  4066. var key = item.substr(0, pos).trim();
  4067. var val = item.substr(pos + 1).trim();
  4068. obj[key] = val;
  4069. });
  4070. return obj;
  4071. }
  4072. /*
  4073. `getKeyValueChunks`
  4074. ----
  4075. Split a string into chunks matching `<key>: <value>`
  4076. */
  4077. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  4078. function getKeyValueChunks(raw) {
  4079. var chunks = [];
  4080. var offset = 0;
  4081. var sep = ';';
  4082. var hasUnclosedUrl = /url\([^\)]+$/;
  4083. var chunk = '';
  4084. var nextSplit;
  4085. while (offset < raw.length) {
  4086. nextSplit = raw.indexOf(sep, offset);
  4087. if (nextSplit === -1) {
  4088. nextSplit = raw.length;
  4089. }
  4090. chunk += raw.substring(offset, nextSplit);
  4091. // data URIs can contain semicolons, so make sure we get the whole thing
  4092. if (hasUnclosedUrl.test(chunk)) {
  4093. chunk += ';';
  4094. offset = nextSplit + 1;
  4095. continue;
  4096. }
  4097. chunks.push(chunk);
  4098. chunk = '';
  4099. offset = nextSplit + 1;
  4100. }
  4101. return chunks;
  4102. }
  4103. /*
  4104. `stringify`
  4105. ----
  4106. Convert an object into an attribute string
  4107. */
  4108. /*:: declare function stringify (obj: Attr): string */
  4109. function stringify(obj) {
  4110. return Object.keys(obj).map(function (key) {
  4111. return key + ':' + obj[key];
  4112. }).join(';');
  4113. }
  4114. /*
  4115. `normalize`
  4116. ----
  4117. Normalize an attribute string (eg. collapse duplicates)
  4118. */
  4119. /*:: declare function normalize (str: string): string */
  4120. function normalize(str) {
  4121. return stringify(parse(str));
  4122. }
  4123. module.exports.parse = parse;
  4124. module.exports.stringify = stringify;
  4125. module.exports.normalize = normalize;
  4126. },{}],37:[function(_dereq_,module,exports){
  4127. var createLayout = _dereq_('layout-bmfont-text')
  4128. var inherits = _dereq_('inherits')
  4129. var createIndices = _dereq_('quad-indices')
  4130. var buffer = _dereq_('three-buffer-vertex-data')
  4131. var assign = _dereq_('object-assign')
  4132. var vertices = _dereq_('./lib/vertices')
  4133. var utils = _dereq_('./lib/utils')
  4134. var Base = THREE.BufferGeometry
  4135. module.exports = function createTextGeometry (opt) {
  4136. return new TextGeometry(opt)
  4137. }
  4138. function TextGeometry (opt) {
  4139. Base.call(this)
  4140. if (typeof opt === 'string') {
  4141. opt = { text: opt }
  4142. }
  4143. // use these as default values for any subsequent
  4144. // calls to update()
  4145. this._opt = assign({}, opt)
  4146. // also do an initial setup...
  4147. if (opt) this.update(opt)
  4148. }
  4149. inherits(TextGeometry, Base)
  4150. TextGeometry.prototype.update = function (opt) {
  4151. if (typeof opt === 'string') {
  4152. opt = { text: opt }
  4153. }
  4154. // use constructor defaults
  4155. opt = assign({}, this._opt, opt)
  4156. if (!opt.font) {
  4157. throw new TypeError('must specify a { font } in options')
  4158. }
  4159. this.layout = createLayout(opt)
  4160. // get vec2 texcoords
  4161. var flipY = opt.flipY !== false
  4162. // the desired BMFont data
  4163. var font = opt.font
  4164. // determine texture size from font file
  4165. var texWidth = font.common.scaleW
  4166. var texHeight = font.common.scaleH
  4167. // get visible glyphs
  4168. var glyphs = this.layout.glyphs.filter(function (glyph) {
  4169. var bitmap = glyph.data
  4170. return bitmap.width * bitmap.height > 0
  4171. })
  4172. // provide visible glyphs for convenience
  4173. this.visibleGlyphs = glyphs
  4174. // get common vertex data
  4175. var positions = vertices.positions(glyphs)
  4176. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  4177. var indices = createIndices({
  4178. clockwise: true,
  4179. type: 'uint16',
  4180. count: glyphs.length
  4181. })
  4182. // update vertex data
  4183. buffer.index(this, indices, 1, 'uint16')
  4184. buffer.attr(this, 'position', positions, 2)
  4185. buffer.attr(this, 'uv', uvs, 2)
  4186. // update multipage data
  4187. if (!opt.multipage && 'page' in this.attributes) {
  4188. // disable multipage rendering
  4189. this.removeAttribute('page')
  4190. } else if (opt.multipage) {
  4191. var pages = vertices.pages(glyphs)
  4192. // enable multipage rendering
  4193. buffer.attr(this, 'page', pages, 1)
  4194. }
  4195. }
  4196. TextGeometry.prototype.computeBoundingSphere = function () {
  4197. if (this.boundingSphere === null) {
  4198. this.boundingSphere = new THREE.Sphere()
  4199. }
  4200. var positions = this.attributes.position.array
  4201. var itemSize = this.attributes.position.itemSize
  4202. if (!positions || !itemSize || positions.length < 2) {
  4203. this.boundingSphere.radius = 0
  4204. this.boundingSphere.center.set(0, 0, 0)
  4205. return
  4206. }
  4207. utils.computeSphere(positions, this.boundingSphere)
  4208. if (isNaN(this.boundingSphere.radius)) {
  4209. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  4210. 'Computed radius is NaN. The ' +
  4211. '"position" attribute is likely to have NaN values.')
  4212. }
  4213. }
  4214. TextGeometry.prototype.computeBoundingBox = function () {
  4215. if (this.boundingBox === null) {
  4216. this.boundingBox = new THREE.Box3()
  4217. }
  4218. var bbox = this.boundingBox
  4219. var positions = this.attributes.position.array
  4220. var itemSize = this.attributes.position.itemSize
  4221. if (!positions || !itemSize || positions.length < 2) {
  4222. bbox.makeEmpty()
  4223. return
  4224. }
  4225. utils.computeBox(positions, bbox)
  4226. }
  4227. },{"./lib/utils":38,"./lib/vertices":39,"inherits":18,"layout-bmfont-text":23,"object-assign":26,"quad-indices":35,"three-buffer-vertex-data":40}],38:[function(_dereq_,module,exports){
  4228. var itemSize = 2
  4229. var box = { min: [0, 0], max: [0, 0] }
  4230. function bounds (positions) {
  4231. var count = positions.length / itemSize
  4232. box.min[0] = positions[0]
  4233. box.min[1] = positions[1]
  4234. box.max[0] = positions[0]
  4235. box.max[1] = positions[1]
  4236. for (var i = 0; i < count; i++) {
  4237. var x = positions[i * itemSize + 0]
  4238. var y = positions[i * itemSize + 1]
  4239. box.min[0] = Math.min(x, box.min[0])
  4240. box.min[1] = Math.min(y, box.min[1])
  4241. box.max[0] = Math.max(x, box.max[0])
  4242. box.max[1] = Math.max(y, box.max[1])
  4243. }
  4244. }
  4245. module.exports.computeBox = function (positions, output) {
  4246. bounds(positions)
  4247. output.min.set(box.min[0], box.min[1], 0)
  4248. output.max.set(box.max[0], box.max[1], 0)
  4249. }
  4250. module.exports.computeSphere = function (positions, output) {
  4251. bounds(positions)
  4252. var minX = box.min[0]
  4253. var minY = box.min[1]
  4254. var maxX = box.max[0]
  4255. var maxY = box.max[1]
  4256. var width = maxX - minX
  4257. var height = maxY - minY
  4258. var length = Math.sqrt(width * width + height * height)
  4259. output.center.set(minX + width / 2, minY + height / 2, 0)
  4260. output.radius = length / 2
  4261. }
  4262. },{}],39:[function(_dereq_,module,exports){
  4263. module.exports.pages = function pages (glyphs) {
  4264. var pages = new Float32Array(glyphs.length * 4 * 1)
  4265. var i = 0
  4266. glyphs.forEach(function (glyph) {
  4267. var id = glyph.data.page || 0
  4268. pages[i++] = id
  4269. pages[i++] = id
  4270. pages[i++] = id
  4271. pages[i++] = id
  4272. })
  4273. return pages
  4274. }
  4275. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  4276. var uvs = new Float32Array(glyphs.length * 4 * 2)
  4277. var i = 0
  4278. glyphs.forEach(function (glyph) {
  4279. var bitmap = glyph.data
  4280. var bw = (bitmap.x + bitmap.width)
  4281. var bh = (bitmap.y + bitmap.height)
  4282. // top left position
  4283. var u0 = bitmap.x / texWidth
  4284. var v1 = bitmap.y / texHeight
  4285. var u1 = bw / texWidth
  4286. var v0 = bh / texHeight
  4287. if (flipY) {
  4288. v1 = (texHeight - bitmap.y) / texHeight
  4289. v0 = (texHeight - bh) / texHeight
  4290. }
  4291. // BL
  4292. uvs[i++] = u0
  4293. uvs[i++] = v1
  4294. // TL
  4295. uvs[i++] = u0
  4296. uvs[i++] = v0
  4297. // TR
  4298. uvs[i++] = u1
  4299. uvs[i++] = v0
  4300. // BR
  4301. uvs[i++] = u1
  4302. uvs[i++] = v1
  4303. })
  4304. return uvs
  4305. }
  4306. module.exports.positions = function positions (glyphs) {
  4307. var positions = new Float32Array(glyphs.length * 4 * 2)
  4308. var i = 0
  4309. glyphs.forEach(function (glyph) {
  4310. var bitmap = glyph.data
  4311. // bottom left position
  4312. var x = glyph.position[0] + bitmap.xoffset
  4313. var y = glyph.position[1] + bitmap.yoffset
  4314. // quad size
  4315. var w = bitmap.width
  4316. var h = bitmap.height
  4317. // BL
  4318. positions[i++] = x
  4319. positions[i++] = y
  4320. // TL
  4321. positions[i++] = x
  4322. positions[i++] = y + h
  4323. // TR
  4324. positions[i++] = x + w
  4325. positions[i++] = y + h
  4326. // BR
  4327. positions[i++] = x + w
  4328. positions[i++] = y
  4329. })
  4330. return positions
  4331. }
  4332. },{}],40:[function(_dereq_,module,exports){
  4333. var flatten = _dereq_('flatten-vertex-data')
  4334. var warned = false;
  4335. module.exports.attr = setAttribute
  4336. module.exports.index = setIndex
  4337. function setIndex (geometry, data, itemSize, dtype) {
  4338. if (typeof itemSize !== 'number') itemSize = 1
  4339. if (typeof dtype !== 'string') dtype = 'uint16'
  4340. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  4341. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  4342. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4343. if (newAttrib) {
  4344. if (isR69) geometry.addAttribute('index', newAttrib)
  4345. else geometry.index = newAttrib
  4346. }
  4347. }
  4348. function setAttribute (geometry, key, data, itemSize, dtype) {
  4349. if (typeof itemSize !== 'number') itemSize = 3
  4350. if (typeof dtype !== 'string') dtype = 'float32'
  4351. if (Array.isArray(data) &&
  4352. Array.isArray(data[0]) &&
  4353. data[0].length !== itemSize) {
  4354. throw new Error('Nested vertex array has unexpected size; expected ' +
  4355. itemSize + ' but found ' + data[0].length)
  4356. }
  4357. var attrib = geometry.getAttribute(key)
  4358. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4359. if (newAttrib) {
  4360. geometry.addAttribute(key, newAttrib)
  4361. }
  4362. }
  4363. function updateAttribute (attrib, data, itemSize, dtype) {
  4364. data = data || []
  4365. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4366. // create a new array with desired type
  4367. data = flatten(data, dtype)
  4368. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4369. if (!attrib || needsNewBuffer) {
  4370. // We are on an old version of ThreeJS which can't
  4371. // support growing / shrinking buffers, so we need
  4372. // to build a new buffer
  4373. if (needsNewBuffer && !warned) {
  4374. warned = true
  4375. console.warn([
  4376. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4377. 'however this version of ThreeJS only supports fixed-size buffers.',
  4378. '\nThe old buffer may still be kept in memory.\n',
  4379. 'To avoid memory leaks, it is recommended that you dispose ',
  4380. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4381. 'See here for discussion:\n',
  4382. 'https://github.com/mrdoob/three.js/pull/9631'
  4383. ].join(''))
  4384. }
  4385. // Build a new attribute
  4386. attrib = new THREE.BufferAttribute(data, itemSize);
  4387. }
  4388. attrib.itemSize = itemSize
  4389. attrib.needsUpdate = true
  4390. // New versions of ThreeJS suggest using setArray
  4391. // to change the data. It will use bufferData internally,
  4392. // so you can change the array size without any issues
  4393. if (typeof attrib.setArray === 'function') {
  4394. attrib.setArray(data)
  4395. }
  4396. return attrib
  4397. } else {
  4398. // copy data into the existing array
  4399. flatten(data, attrib.array)
  4400. attrib.needsUpdate = true
  4401. return null
  4402. }
  4403. }
  4404. // Test whether the attribute needs to be re-created,
  4405. // returns false if we can re-use it as-is.
  4406. function rebuildAttribute (attrib, data, itemSize) {
  4407. if (attrib.itemSize !== itemSize) return true
  4408. if (!attrib.array) return true
  4409. var attribLength = attrib.array.length
  4410. if (Array.isArray(data) && Array.isArray(data[0])) {
  4411. // [ [ x, y, z ] ]
  4412. return attribLength !== data.length * itemSize
  4413. } else {
  4414. // [ x, y, z ]
  4415. return attribLength !== data.length
  4416. }
  4417. return false
  4418. }
  4419. },{"flatten-vertex-data":13}],41:[function(_dereq_,module,exports){
  4420. (function (global, factory) {
  4421. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4422. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4423. (factory((global.THREE = {})));
  4424. }(this, (function (exports) { 'use strict';
  4425. // Polyfills
  4426. if ( Number.EPSILON === undefined ) {
  4427. Number.EPSILON = Math.pow( 2, - 52 );
  4428. }
  4429. if ( Number.isInteger === undefined ) {
  4430. // Missing in IE
  4431. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  4432. Number.isInteger = function ( value ) {
  4433. return typeof value === 'number' && isFinite( value ) && Math.floor( value ) === value;
  4434. };
  4435. }
  4436. //
  4437. if ( Math.sign === undefined ) {
  4438. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4439. Math.sign = function ( x ) {
  4440. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4441. };
  4442. }
  4443. if ( 'name' in Function.prototype === false ) {
  4444. // Missing in IE
  4445. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4446. Object.defineProperty( Function.prototype, 'name', {
  4447. get: function () {
  4448. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4449. }
  4450. } );
  4451. }
  4452. if ( Object.assign === undefined ) {
  4453. // Missing in IE
  4454. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4455. ( function () {
  4456. Object.assign = function ( target ) {
  4457. if ( target === undefined || target === null ) {
  4458. throw new TypeError( 'Cannot convert undefined or null to object' );
  4459. }
  4460. var output = Object( target );
  4461. for ( var index = 1; index < arguments.length; index ++ ) {
  4462. var source = arguments[ index ];
  4463. if ( source !== undefined && source !== null ) {
  4464. for ( var nextKey in source ) {
  4465. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4466. output[ nextKey ] = source[ nextKey ];
  4467. }
  4468. }
  4469. }
  4470. }
  4471. return output;
  4472. };
  4473. } )();
  4474. }
  4475. /**
  4476. * https://github.com/mrdoob/eventdispatcher.js/
  4477. */
  4478. function EventDispatcher() {}
  4479. Object.assign( EventDispatcher.prototype, {
  4480. addEventListener: function ( type, listener ) {
  4481. if ( this._listeners === undefined ) this._listeners = {};
  4482. var listeners = this._listeners;
  4483. if ( listeners[ type ] === undefined ) {
  4484. listeners[ type ] = [];
  4485. }
  4486. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4487. listeners[ type ].push( listener );
  4488. }
  4489. },
  4490. hasEventListener: function ( type, listener ) {
  4491. if ( this._listeners === undefined ) return false;
  4492. var listeners = this._listeners;
  4493. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4494. },
  4495. removeEventListener: function ( type, listener ) {
  4496. if ( this._listeners === undefined ) return;
  4497. var listeners = this._listeners;
  4498. var listenerArray = listeners[ type ];
  4499. if ( listenerArray !== undefined ) {
  4500. var index = listenerArray.indexOf( listener );
  4501. if ( index !== - 1 ) {
  4502. listenerArray.splice( index, 1 );
  4503. }
  4504. }
  4505. },
  4506. dispatchEvent: function ( event ) {
  4507. if ( this._listeners === undefined ) return;
  4508. var listeners = this._listeners;
  4509. var listenerArray = listeners[ event.type ];
  4510. if ( listenerArray !== undefined ) {
  4511. event.target = this;
  4512. var array = listenerArray.slice( 0 );
  4513. for ( var i = 0, l = array.length; i < l; i ++ ) {
  4514. array[ i ].call( this, event );
  4515. }
  4516. }
  4517. }
  4518. } );
  4519. var REVISION = '89';
  4520. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4521. var CullFaceNone = 0;
  4522. var CullFaceBack = 1;
  4523. var CullFaceFront = 2;
  4524. var CullFaceFrontBack = 3;
  4525. var FrontFaceDirectionCW = 0;
  4526. var FrontFaceDirectionCCW = 1;
  4527. var BasicShadowMap = 0;
  4528. var PCFShadowMap = 1;
  4529. var PCFSoftShadowMap = 2;
  4530. var FrontSide = 0;
  4531. var BackSide = 1;
  4532. var DoubleSide = 2;
  4533. var FlatShading = 1;
  4534. var SmoothShading = 2;
  4535. var NoColors = 0;
  4536. var FaceColors = 1;
  4537. var VertexColors = 2;
  4538. var NoBlending = 0;
  4539. var NormalBlending = 1;
  4540. var AdditiveBlending = 2;
  4541. var SubtractiveBlending = 3;
  4542. var MultiplyBlending = 4;
  4543. var CustomBlending = 5;
  4544. var AddEquation = 100;
  4545. var SubtractEquation = 101;
  4546. var ReverseSubtractEquation = 102;
  4547. var MinEquation = 103;
  4548. var MaxEquation = 104;
  4549. var ZeroFactor = 200;
  4550. var OneFactor = 201;
  4551. var SrcColorFactor = 202;
  4552. var OneMinusSrcColorFactor = 203;
  4553. var SrcAlphaFactor = 204;
  4554. var OneMinusSrcAlphaFactor = 205;
  4555. var DstAlphaFactor = 206;
  4556. var OneMinusDstAlphaFactor = 207;
  4557. var DstColorFactor = 208;
  4558. var OneMinusDstColorFactor = 209;
  4559. var SrcAlphaSaturateFactor = 210;
  4560. var NeverDepth = 0;
  4561. var AlwaysDepth = 1;
  4562. var LessDepth = 2;
  4563. var LessEqualDepth = 3;
  4564. var EqualDepth = 4;
  4565. var GreaterEqualDepth = 5;
  4566. var GreaterDepth = 6;
  4567. var NotEqualDepth = 7;
  4568. var MultiplyOperation = 0;
  4569. var MixOperation = 1;
  4570. var AddOperation = 2;
  4571. var NoToneMapping = 0;
  4572. var LinearToneMapping = 1;
  4573. var ReinhardToneMapping = 2;
  4574. var Uncharted2ToneMapping = 3;
  4575. var CineonToneMapping = 4;
  4576. var UVMapping = 300;
  4577. var CubeReflectionMapping = 301;
  4578. var CubeRefractionMapping = 302;
  4579. var EquirectangularReflectionMapping = 303;
  4580. var EquirectangularRefractionMapping = 304;
  4581. var SphericalReflectionMapping = 305;
  4582. var CubeUVReflectionMapping = 306;
  4583. var CubeUVRefractionMapping = 307;
  4584. var RepeatWrapping = 1000;
  4585. var ClampToEdgeWrapping = 1001;
  4586. var MirroredRepeatWrapping = 1002;
  4587. var NearestFilter = 1003;
  4588. var NearestMipMapNearestFilter = 1004;
  4589. var NearestMipMapLinearFilter = 1005;
  4590. var LinearFilter = 1006;
  4591. var LinearMipMapNearestFilter = 1007;
  4592. var LinearMipMapLinearFilter = 1008;
  4593. var UnsignedByteType = 1009;
  4594. var ByteType = 1010;
  4595. var ShortType = 1011;
  4596. var UnsignedShortType = 1012;
  4597. var IntType = 1013;
  4598. var UnsignedIntType = 1014;
  4599. var FloatType = 1015;
  4600. var HalfFloatType = 1016;
  4601. var UnsignedShort4444Type = 1017;
  4602. var UnsignedShort5551Type = 1018;
  4603. var UnsignedShort565Type = 1019;
  4604. var UnsignedInt248Type = 1020;
  4605. var AlphaFormat = 1021;
  4606. var RGBFormat = 1022;
  4607. var RGBAFormat = 1023;
  4608. var LuminanceFormat = 1024;
  4609. var LuminanceAlphaFormat = 1025;
  4610. var RGBEFormat = RGBAFormat;
  4611. var DepthFormat = 1026;
  4612. var DepthStencilFormat = 1027;
  4613. var RGB_S3TC_DXT1_Format = 2001;
  4614. var RGBA_S3TC_DXT1_Format = 2002;
  4615. var RGBA_S3TC_DXT3_Format = 2003;
  4616. var RGBA_S3TC_DXT5_Format = 2004;
  4617. var RGB_PVRTC_4BPPV1_Format = 2100;
  4618. var RGB_PVRTC_2BPPV1_Format = 2101;
  4619. var RGBA_PVRTC_4BPPV1_Format = 2102;
  4620. var RGBA_PVRTC_2BPPV1_Format = 2103;
  4621. var RGB_ETC1_Format = 2151;
  4622. var LoopOnce = 2200;
  4623. var LoopRepeat = 2201;
  4624. var LoopPingPong = 2202;
  4625. var InterpolateDiscrete = 2300;
  4626. var InterpolateLinear = 2301;
  4627. var InterpolateSmooth = 2302;
  4628. var ZeroCurvatureEnding = 2400;
  4629. var ZeroSlopeEnding = 2401;
  4630. var WrapAroundEnding = 2402;
  4631. var TrianglesDrawMode = 0;
  4632. var TriangleStripDrawMode = 1;
  4633. var TriangleFanDrawMode = 2;
  4634. var LinearEncoding = 3000;
  4635. var sRGBEncoding = 3001;
  4636. var GammaEncoding = 3007;
  4637. var RGBEEncoding = 3002;
  4638. var LogLuvEncoding = 3003;
  4639. var RGBM7Encoding = 3004;
  4640. var RGBM16Encoding = 3005;
  4641. var RGBDEncoding = 3006;
  4642. var BasicDepthPacking = 3200;
  4643. var RGBADepthPacking = 3201;
  4644. /**
  4645. * @author alteredq / http://alteredqualia.com/
  4646. * @author mrdoob / http://mrdoob.com/
  4647. */
  4648. var _Math = {
  4649. DEG2RAD: Math.PI / 180,
  4650. RAD2DEG: 180 / Math.PI,
  4651. generateUUID: ( function () {
  4652. // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
  4653. var lut = [];
  4654. for ( var i = 0; i < 256; i ++ ) {
  4655. lut[ i ] = ( i < 16 ? '0' : '' ) + ( i ).toString( 16 ).toUpperCase();
  4656. }
  4657. return function () {
  4658. var d0 = Math.random() * 0xffffffff | 0;
  4659. var d1 = Math.random() * 0xffffffff | 0;
  4660. var d2 = Math.random() * 0xffffffff | 0;
  4661. var d3 = Math.random() * 0xffffffff | 0;
  4662. return lut[ d0 & 0xff ] + lut[ d0 >> 8 & 0xff ] + lut[ d0 >> 16 & 0xff ] + lut[ d0 >> 24 & 0xff ] + '-' +
  4663. lut[ d1 & 0xff ] + lut[ d1 >> 8 & 0xff ] + '-' + lut[ d1 >> 16 & 0x0f | 0x40 ] + lut[ d1 >> 24 & 0xff ] + '-' +
  4664. lut[ d2 & 0x3f | 0x80 ] + lut[ d2 >> 8 & 0xff ] + '-' + lut[ d2 >> 16 & 0xff ] + lut[ d2 >> 24 & 0xff ] +
  4665. lut[ d3 & 0xff ] + lut[ d3 >> 8 & 0xff ] + lut[ d3 >> 16 & 0xff ] + lut[ d3 >> 24 & 0xff ];
  4666. };
  4667. } )(),
  4668. clamp: function ( value, min, max ) {
  4669. return Math.max( min, Math.min( max, value ) );
  4670. },
  4671. // compute euclidian modulo of m % n
  4672. // https://en.wikipedia.org/wiki/Modulo_operation
  4673. euclideanModulo: function ( n, m ) {
  4674. return ( ( n % m ) + m ) % m;
  4675. },
  4676. // Linear mapping from range <a1, a2> to range <b1, b2>
  4677. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4678. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4679. },
  4680. // https://en.wikipedia.org/wiki/Linear_interpolation
  4681. lerp: function ( x, y, t ) {
  4682. return ( 1 - t ) * x + t * y;
  4683. },
  4684. // http://en.wikipedia.org/wiki/Smoothstep
  4685. smoothstep: function ( x, min, max ) {
  4686. if ( x <= min ) return 0;
  4687. if ( x >= max ) return 1;
  4688. x = ( x - min ) / ( max - min );
  4689. return x * x * ( 3 - 2 * x );
  4690. },
  4691. smootherstep: function ( x, min, max ) {
  4692. if ( x <= min ) return 0;
  4693. if ( x >= max ) return 1;
  4694. x = ( x - min ) / ( max - min );
  4695. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4696. },
  4697. // Random integer from <low, high> interval
  4698. randInt: function ( low, high ) {
  4699. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4700. },
  4701. // Random float from <low, high> interval
  4702. randFloat: function ( low, high ) {
  4703. return low + Math.random() * ( high - low );
  4704. },
  4705. // Random float from <-range/2, range/2> interval
  4706. randFloatSpread: function ( range ) {
  4707. return range * ( 0.5 - Math.random() );
  4708. },
  4709. degToRad: function ( degrees ) {
  4710. return degrees * _Math.DEG2RAD;
  4711. },
  4712. radToDeg: function ( radians ) {
  4713. return radians * _Math.RAD2DEG;
  4714. },
  4715. isPowerOfTwo: function ( value ) {
  4716. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4717. },
  4718. ceilPowerOfTwo: function ( value ) {
  4719. return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
  4720. },
  4721. floorPowerOfTwo: function ( value ) {
  4722. return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
  4723. }
  4724. };
  4725. /**
  4726. * @author mrdoob / http://mrdoob.com/
  4727. * @author philogb / http://blog.thejit.org/
  4728. * @author egraether / http://egraether.com/
  4729. * @author zz85 / http://www.lab4games.net/zz85/blog
  4730. */
  4731. function Vector2( x, y ) {
  4732. this.x = x || 0;
  4733. this.y = y || 0;
  4734. }
  4735. Object.defineProperties( Vector2.prototype, {
  4736. "width": {
  4737. get: function () {
  4738. return this.x;
  4739. },
  4740. set: function ( value ) {
  4741. this.x = value;
  4742. }
  4743. },
  4744. "height": {
  4745. get: function () {
  4746. return this.y;
  4747. },
  4748. set: function ( value ) {
  4749. this.y = value;
  4750. }
  4751. }
  4752. } );
  4753. Object.assign( Vector2.prototype, {
  4754. isVector2: true,
  4755. set: function ( x, y ) {
  4756. this.x = x;
  4757. this.y = y;
  4758. return this;
  4759. },
  4760. setScalar: function ( scalar ) {
  4761. this.x = scalar;
  4762. this.y = scalar;
  4763. return this;
  4764. },
  4765. setX: function ( x ) {
  4766. this.x = x;
  4767. return this;
  4768. },
  4769. setY: function ( y ) {
  4770. this.y = y;
  4771. return this;
  4772. },
  4773. setComponent: function ( index, value ) {
  4774. switch ( index ) {
  4775. case 0: this.x = value; break;
  4776. case 1: this.y = value; break;
  4777. default: throw new Error( 'index is out of range: ' + index );
  4778. }
  4779. return this;
  4780. },
  4781. getComponent: function ( index ) {
  4782. switch ( index ) {
  4783. case 0: return this.x;
  4784. case 1: return this.y;
  4785. default: throw new Error( 'index is out of range: ' + index );
  4786. }
  4787. },
  4788. clone: function () {
  4789. return new this.constructor( this.x, this.y );
  4790. },
  4791. copy: function ( v ) {
  4792. this.x = v.x;
  4793. this.y = v.y;
  4794. return this;
  4795. },
  4796. add: function ( v, w ) {
  4797. if ( w !== undefined ) {
  4798. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4799. return this.addVectors( v, w );
  4800. }
  4801. this.x += v.x;
  4802. this.y += v.y;
  4803. return this;
  4804. },
  4805. addScalar: function ( s ) {
  4806. this.x += s;
  4807. this.y += s;
  4808. return this;
  4809. },
  4810. addVectors: function ( a, b ) {
  4811. this.x = a.x + b.x;
  4812. this.y = a.y + b.y;
  4813. return this;
  4814. },
  4815. addScaledVector: function ( v, s ) {
  4816. this.x += v.x * s;
  4817. this.y += v.y * s;
  4818. return this;
  4819. },
  4820. sub: function ( v, w ) {
  4821. if ( w !== undefined ) {
  4822. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4823. return this.subVectors( v, w );
  4824. }
  4825. this.x -= v.x;
  4826. this.y -= v.y;
  4827. return this;
  4828. },
  4829. subScalar: function ( s ) {
  4830. this.x -= s;
  4831. this.y -= s;
  4832. return this;
  4833. },
  4834. subVectors: function ( a, b ) {
  4835. this.x = a.x - b.x;
  4836. this.y = a.y - b.y;
  4837. return this;
  4838. },
  4839. multiply: function ( v ) {
  4840. this.x *= v.x;
  4841. this.y *= v.y;
  4842. return this;
  4843. },
  4844. multiplyScalar: function ( scalar ) {
  4845. this.x *= scalar;
  4846. this.y *= scalar;
  4847. return this;
  4848. },
  4849. divide: function ( v ) {
  4850. this.x /= v.x;
  4851. this.y /= v.y;
  4852. return this;
  4853. },
  4854. divideScalar: function ( scalar ) {
  4855. return this.multiplyScalar( 1 / scalar );
  4856. },
  4857. applyMatrix3: function ( m ) {
  4858. var x = this.x, y = this.y;
  4859. var e = m.elements;
  4860. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ];
  4861. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ];
  4862. return this;
  4863. },
  4864. min: function ( v ) {
  4865. this.x = Math.min( this.x, v.x );
  4866. this.y = Math.min( this.y, v.y );
  4867. return this;
  4868. },
  4869. max: function ( v ) {
  4870. this.x = Math.max( this.x, v.x );
  4871. this.y = Math.max( this.y, v.y );
  4872. return this;
  4873. },
  4874. clamp: function ( min, max ) {
  4875. // assumes min < max, componentwise
  4876. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4877. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4878. return this;
  4879. },
  4880. clampScalar: function () {
  4881. var min = new Vector2();
  4882. var max = new Vector2();
  4883. return function clampScalar( minVal, maxVal ) {
  4884. min.set( minVal, minVal );
  4885. max.set( maxVal, maxVal );
  4886. return this.clamp( min, max );
  4887. };
  4888. }(),
  4889. clampLength: function ( min, max ) {
  4890. var length = this.length();
  4891. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  4892. },
  4893. floor: function () {
  4894. this.x = Math.floor( this.x );
  4895. this.y = Math.floor( this.y );
  4896. return this;
  4897. },
  4898. ceil: function () {
  4899. this.x = Math.ceil( this.x );
  4900. this.y = Math.ceil( this.y );
  4901. return this;
  4902. },
  4903. round: function () {
  4904. this.x = Math.round( this.x );
  4905. this.y = Math.round( this.y );
  4906. return this;
  4907. },
  4908. roundToZero: function () {
  4909. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4910. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4911. return this;
  4912. },
  4913. negate: function () {
  4914. this.x = - this.x;
  4915. this.y = - this.y;
  4916. return this;
  4917. },
  4918. dot: function ( v ) {
  4919. return this.x * v.x + this.y * v.y;
  4920. },
  4921. lengthSq: function () {
  4922. return this.x * this.x + this.y * this.y;
  4923. },
  4924. length: function () {
  4925. return Math.sqrt( this.x * this.x + this.y * this.y );
  4926. },
  4927. manhattanLength: function () {
  4928. return Math.abs( this.x ) + Math.abs( this.y );
  4929. },
  4930. normalize: function () {
  4931. return this.divideScalar( this.length() || 1 );
  4932. },
  4933. angle: function () {
  4934. // computes the angle in radians with respect to the positive x-axis
  4935. var angle = Math.atan2( this.y, this.x );
  4936. if ( angle < 0 ) angle += 2 * Math.PI;
  4937. return angle;
  4938. },
  4939. distanceTo: function ( v ) {
  4940. return Math.sqrt( this.distanceToSquared( v ) );
  4941. },
  4942. distanceToSquared: function ( v ) {
  4943. var dx = this.x - v.x, dy = this.y - v.y;
  4944. return dx * dx + dy * dy;
  4945. },
  4946. manhattanDistanceTo: function ( v ) {
  4947. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4948. },
  4949. setLength: function ( length ) {
  4950. return this.normalize().multiplyScalar( length );
  4951. },
  4952. lerp: function ( v, alpha ) {
  4953. this.x += ( v.x - this.x ) * alpha;
  4954. this.y += ( v.y - this.y ) * alpha;
  4955. return this;
  4956. },
  4957. lerpVectors: function ( v1, v2, alpha ) {
  4958. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4959. },
  4960. equals: function ( v ) {
  4961. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4962. },
  4963. fromArray: function ( array, offset ) {
  4964. if ( offset === undefined ) offset = 0;
  4965. this.x = array[ offset ];
  4966. this.y = array[ offset + 1 ];
  4967. return this;
  4968. },
  4969. toArray: function ( array, offset ) {
  4970. if ( array === undefined ) array = [];
  4971. if ( offset === undefined ) offset = 0;
  4972. array[ offset ] = this.x;
  4973. array[ offset + 1 ] = this.y;
  4974. return array;
  4975. },
  4976. fromBufferAttribute: function ( attribute, index, offset ) {
  4977. if ( offset !== undefined ) {
  4978. console.warn( 'THREE.Vector2: offset has been removed from .fromBufferAttribute().' );
  4979. }
  4980. this.x = attribute.getX( index );
  4981. this.y = attribute.getY( index );
  4982. return this;
  4983. },
  4984. rotateAround: function ( center, angle ) {
  4985. var c = Math.cos( angle ), s = Math.sin( angle );
  4986. var x = this.x - center.x;
  4987. var y = this.y - center.y;
  4988. this.x = x * c - y * s + center.x;
  4989. this.y = x * s + y * c + center.y;
  4990. return this;
  4991. }
  4992. } );
  4993. /**
  4994. * @author mrdoob / http://mrdoob.com/
  4995. * @author supereggbert / http://www.paulbrunt.co.uk/
  4996. * @author philogb / http://blog.thejit.org/
  4997. * @author jordi_ros / http://plattsoft.com
  4998. * @author D1plo1d / http://github.com/D1plo1d
  4999. * @author alteredq / http://alteredqualia.com/
  5000. * @author mikael emtinger / http://gomo.se/
  5001. * @author timknip / http://www.floorplanner.com/
  5002. * @author bhouston / http://clara.io
  5003. * @author WestLangley / http://github.com/WestLangley
  5004. */
  5005. function Matrix4() {
  5006. this.elements = [
  5007. 1, 0, 0, 0,
  5008. 0, 1, 0, 0,
  5009. 0, 0, 1, 0,
  5010. 0, 0, 0, 1
  5011. ];
  5012. if ( arguments.length > 0 ) {
  5013. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  5014. }
  5015. }
  5016. Object.assign( Matrix4.prototype, {
  5017. isMatrix4: true,
  5018. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  5019. var te = this.elements;
  5020. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  5021. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  5022. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  5023. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  5024. return this;
  5025. },
  5026. identity: function () {
  5027. this.set(
  5028. 1, 0, 0, 0,
  5029. 0, 1, 0, 0,
  5030. 0, 0, 1, 0,
  5031. 0, 0, 0, 1
  5032. );
  5033. return this;
  5034. },
  5035. clone: function () {
  5036. return new Matrix4().fromArray( this.elements );
  5037. },
  5038. copy: function ( m ) {
  5039. var te = this.elements;
  5040. var me = m.elements;
  5041. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ]; te[ 3 ] = me[ 3 ];
  5042. te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ]; te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ];
  5043. te[ 8 ] = me[ 8 ]; te[ 9 ] = me[ 9 ]; te[ 10 ] = me[ 10 ]; te[ 11 ] = me[ 11 ];
  5044. te[ 12 ] = me[ 12 ]; te[ 13 ] = me[ 13 ]; te[ 14 ] = me[ 14 ]; te[ 15 ] = me[ 15 ];
  5045. return this;
  5046. },
  5047. copyPosition: function ( m ) {
  5048. var te = this.elements, me = m.elements;
  5049. te[ 12 ] = me[ 12 ];
  5050. te[ 13 ] = me[ 13 ];
  5051. te[ 14 ] = me[ 14 ];
  5052. return this;
  5053. },
  5054. extractBasis: function ( xAxis, yAxis, zAxis ) {
  5055. xAxis.setFromMatrixColumn( this, 0 );
  5056. yAxis.setFromMatrixColumn( this, 1 );
  5057. zAxis.setFromMatrixColumn( this, 2 );
  5058. return this;
  5059. },
  5060. makeBasis: function ( xAxis, yAxis, zAxis ) {
  5061. this.set(
  5062. xAxis.x, yAxis.x, zAxis.x, 0,
  5063. xAxis.y, yAxis.y, zAxis.y, 0,
  5064. xAxis.z, yAxis.z, zAxis.z, 0,
  5065. 0, 0, 0, 1
  5066. );
  5067. return this;
  5068. },
  5069. extractRotation: function () {
  5070. var v1 = new Vector3();
  5071. return function extractRotation( m ) {
  5072. var te = this.elements;
  5073. var me = m.elements;
  5074. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  5075. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  5076. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  5077. te[ 0 ] = me[ 0 ] * scaleX;
  5078. te[ 1 ] = me[ 1 ] * scaleX;
  5079. te[ 2 ] = me[ 2 ] * scaleX;
  5080. te[ 4 ] = me[ 4 ] * scaleY;
  5081. te[ 5 ] = me[ 5 ] * scaleY;
  5082. te[ 6 ] = me[ 6 ] * scaleY;
  5083. te[ 8 ] = me[ 8 ] * scaleZ;
  5084. te[ 9 ] = me[ 9 ] * scaleZ;
  5085. te[ 10 ] = me[ 10 ] * scaleZ;
  5086. return this;
  5087. };
  5088. }(),
  5089. makeRotationFromEuler: function ( euler ) {
  5090. if ( ! ( euler && euler.isEuler ) ) {
  5091. console.error( 'THREE.Matrix4: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  5092. }
  5093. var te = this.elements;
  5094. var x = euler.x, y = euler.y, z = euler.z;
  5095. var a = Math.cos( x ), b = Math.sin( x );
  5096. var c = Math.cos( y ), d = Math.sin( y );
  5097. var e = Math.cos( z ), f = Math.sin( z );
  5098. if ( euler.order === 'XYZ' ) {
  5099. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5100. te[ 0 ] = c * e;
  5101. te[ 4 ] = - c * f;
  5102. te[ 8 ] = d;
  5103. te[ 1 ] = af + be * d;
  5104. te[ 5 ] = ae - bf * d;
  5105. te[ 9 ] = - b * c;
  5106. te[ 2 ] = bf - ae * d;
  5107. te[ 6 ] = be + af * d;
  5108. te[ 10 ] = a * c;
  5109. } else if ( euler.order === 'YXZ' ) {
  5110. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5111. te[ 0 ] = ce + df * b;
  5112. te[ 4 ] = de * b - cf;
  5113. te[ 8 ] = a * d;
  5114. te[ 1 ] = a * f;
  5115. te[ 5 ] = a * e;
  5116. te[ 9 ] = - b;
  5117. te[ 2 ] = cf * b - de;
  5118. te[ 6 ] = df + ce * b;
  5119. te[ 10 ] = a * c;
  5120. } else if ( euler.order === 'ZXY' ) {
  5121. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  5122. te[ 0 ] = ce - df * b;
  5123. te[ 4 ] = - a * f;
  5124. te[ 8 ] = de + cf * b;
  5125. te[ 1 ] = cf + de * b;
  5126. te[ 5 ] = a * e;
  5127. te[ 9 ] = df - ce * b;
  5128. te[ 2 ] = - a * d;
  5129. te[ 6 ] = b;
  5130. te[ 10 ] = a * c;
  5131. } else if ( euler.order === 'ZYX' ) {
  5132. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  5133. te[ 0 ] = c * e;
  5134. te[ 4 ] = be * d - af;
  5135. te[ 8 ] = ae * d + bf;
  5136. te[ 1 ] = c * f;
  5137. te[ 5 ] = bf * d + ae;
  5138. te[ 9 ] = af * d - be;
  5139. te[ 2 ] = - d;
  5140. te[ 6 ] = b * c;
  5141. te[ 10 ] = a * c;
  5142. } else if ( euler.order === 'YZX' ) {
  5143. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5144. te[ 0 ] = c * e;
  5145. te[ 4 ] = bd - ac * f;
  5146. te[ 8 ] = bc * f + ad;
  5147. te[ 1 ] = f;
  5148. te[ 5 ] = a * e;
  5149. te[ 9 ] = - b * e;
  5150. te[ 2 ] = - d * e;
  5151. te[ 6 ] = ad * f + bc;
  5152. te[ 10 ] = ac - bd * f;
  5153. } else if ( euler.order === 'XZY' ) {
  5154. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  5155. te[ 0 ] = c * e;
  5156. te[ 4 ] = - f;
  5157. te[ 8 ] = d * e;
  5158. te[ 1 ] = ac * f + bd;
  5159. te[ 5 ] = a * e;
  5160. te[ 9 ] = ad * f - bc;
  5161. te[ 2 ] = bc * f - ad;
  5162. te[ 6 ] = b * e;
  5163. te[ 10 ] = bd * f + ac;
  5164. }
  5165. // last column
  5166. te[ 3 ] = 0;
  5167. te[ 7 ] = 0;
  5168. te[ 11 ] = 0;
  5169. // bottom row
  5170. te[ 12 ] = 0;
  5171. te[ 13 ] = 0;
  5172. te[ 14 ] = 0;
  5173. te[ 15 ] = 1;
  5174. return this;
  5175. },
  5176. makeRotationFromQuaternion: function ( q ) {
  5177. var te = this.elements;
  5178. var x = q._x, y = q._y, z = q._z, w = q._w;
  5179. var x2 = x + x, y2 = y + y, z2 = z + z;
  5180. var xx = x * x2, xy = x * y2, xz = x * z2;
  5181. var yy = y * y2, yz = y * z2, zz = z * z2;
  5182. var wx = w * x2, wy = w * y2, wz = w * z2;
  5183. te[ 0 ] = 1 - ( yy + zz );
  5184. te[ 4 ] = xy - wz;
  5185. te[ 8 ] = xz + wy;
  5186. te[ 1 ] = xy + wz;
  5187. te[ 5 ] = 1 - ( xx + zz );
  5188. te[ 9 ] = yz - wx;
  5189. te[ 2 ] = xz - wy;
  5190. te[ 6 ] = yz + wx;
  5191. te[ 10 ] = 1 - ( xx + yy );
  5192. // last column
  5193. te[ 3 ] = 0;
  5194. te[ 7 ] = 0;
  5195. te[ 11 ] = 0;
  5196. // bottom row
  5197. te[ 12 ] = 0;
  5198. te[ 13 ] = 0;
  5199. te[ 14 ] = 0;
  5200. te[ 15 ] = 1;
  5201. return this;
  5202. },
  5203. lookAt: function () {
  5204. var x = new Vector3();
  5205. var y = new Vector3();
  5206. var z = new Vector3();
  5207. return function lookAt( eye, target, up ) {
  5208. var te = this.elements;
  5209. z.subVectors( eye, target );
  5210. if ( z.lengthSq() === 0 ) {
  5211. // eye and target are in the same position
  5212. z.z = 1;
  5213. }
  5214. z.normalize();
  5215. x.crossVectors( up, z );
  5216. if ( x.lengthSq() === 0 ) {
  5217. // up and z are parallel
  5218. if ( Math.abs( up.z ) === 1 ) {
  5219. z.x += 0.0001;
  5220. } else {
  5221. z.z += 0.0001;
  5222. }
  5223. z.normalize();
  5224. x.crossVectors( up, z );
  5225. }
  5226. x.normalize();
  5227. y.crossVectors( z, x );
  5228. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  5229. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  5230. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  5231. return this;
  5232. };
  5233. }(),
  5234. multiply: function ( m, n ) {
  5235. if ( n !== undefined ) {
  5236. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  5237. return this.multiplyMatrices( m, n );
  5238. }
  5239. return this.multiplyMatrices( this, m );
  5240. },
  5241. premultiply: function ( m ) {
  5242. return this.multiplyMatrices( m, this );
  5243. },
  5244. multiplyMatrices: function ( a, b ) {
  5245. var ae = a.elements;
  5246. var be = b.elements;
  5247. var te = this.elements;
  5248. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  5249. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  5250. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  5251. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  5252. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  5253. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  5254. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  5255. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  5256. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  5257. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  5258. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  5259. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  5260. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  5261. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  5262. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  5263. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  5264. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  5265. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  5266. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  5267. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  5268. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  5269. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  5270. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  5271. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  5272. return this;
  5273. },
  5274. multiplyScalar: function ( s ) {
  5275. var te = this.elements;
  5276. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  5277. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  5278. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  5279. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  5280. return this;
  5281. },
  5282. applyToBufferAttribute: function () {
  5283. var v1 = new Vector3();
  5284. return function applyToBufferAttribute( attribute ) {
  5285. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  5286. v1.x = attribute.getX( i );
  5287. v1.y = attribute.getY( i );
  5288. v1.z = attribute.getZ( i );
  5289. v1.applyMatrix4( this );
  5290. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  5291. }
  5292. return attribute;
  5293. };
  5294. }(),
  5295. determinant: function () {
  5296. var te = this.elements;
  5297. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  5298. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  5299. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  5300. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  5301. //TODO: make this more efficient
  5302. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  5303. return (
  5304. n41 * (
  5305. + n14 * n23 * n32
  5306. - n13 * n24 * n32
  5307. - n14 * n22 * n33
  5308. + n12 * n24 * n33
  5309. + n13 * n22 * n34
  5310. - n12 * n23 * n34
  5311. ) +
  5312. n42 * (
  5313. + n11 * n23 * n34
  5314. - n11 * n24 * n33
  5315. + n14 * n21 * n33
  5316. - n13 * n21 * n34
  5317. + n13 * n24 * n31
  5318. - n14 * n23 * n31
  5319. ) +
  5320. n43 * (
  5321. + n11 * n24 * n32
  5322. - n11 * n22 * n34
  5323. - n14 * n21 * n32
  5324. + n12 * n21 * n34
  5325. + n14 * n22 * n31
  5326. - n12 * n24 * n31
  5327. ) +
  5328. n44 * (
  5329. - n13 * n22 * n31
  5330. - n11 * n23 * n32
  5331. + n11 * n22 * n33
  5332. + n13 * n21 * n32
  5333. - n12 * n21 * n33
  5334. + n12 * n23 * n31
  5335. )
  5336. );
  5337. },
  5338. transpose: function () {
  5339. var te = this.elements;
  5340. var tmp;
  5341. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  5342. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  5343. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  5344. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  5345. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  5346. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  5347. return this;
  5348. },
  5349. setPosition: function ( v ) {
  5350. var te = this.elements;
  5351. te[ 12 ] = v.x;
  5352. te[ 13 ] = v.y;
  5353. te[ 14 ] = v.z;
  5354. return this;
  5355. },
  5356. getInverse: function ( m, throwOnDegenerate ) {
  5357. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  5358. var te = this.elements,
  5359. me = m.elements,
  5360. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  5361. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  5362. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  5363. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  5364. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  5365. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  5366. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  5367. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  5368. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  5369. if ( det === 0 ) {
  5370. var msg = "THREE.Matrix4: .getInverse() can't invert matrix, determinant is 0";
  5371. if ( throwOnDegenerate === true ) {
  5372. throw new Error( msg );
  5373. } else {
  5374. console.warn( msg );
  5375. }
  5376. return this.identity();
  5377. }
  5378. var detInv = 1 / det;
  5379. te[ 0 ] = t11 * detInv;
  5380. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  5381. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  5382. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  5383. te[ 4 ] = t12 * detInv;
  5384. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  5385. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  5386. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  5387. te[ 8 ] = t13 * detInv;
  5388. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  5389. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  5390. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  5391. te[ 12 ] = t14 * detInv;
  5392. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  5393. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  5394. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  5395. return this;
  5396. },
  5397. scale: function ( v ) {
  5398. var te = this.elements;
  5399. var x = v.x, y = v.y, z = v.z;
  5400. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  5401. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  5402. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  5403. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  5404. return this;
  5405. },
  5406. getMaxScaleOnAxis: function () {
  5407. var te = this.elements;
  5408. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  5409. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  5410. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  5411. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  5412. },
  5413. makeTranslation: function ( x, y, z ) {
  5414. this.set(
  5415. 1, 0, 0, x,
  5416. 0, 1, 0, y,
  5417. 0, 0, 1, z,
  5418. 0, 0, 0, 1
  5419. );
  5420. return this;
  5421. },
  5422. makeRotationX: function ( theta ) {
  5423. var c = Math.cos( theta ), s = Math.sin( theta );
  5424. this.set(
  5425. 1, 0, 0, 0,
  5426. 0, c, - s, 0,
  5427. 0, s, c, 0,
  5428. 0, 0, 0, 1
  5429. );
  5430. return this;
  5431. },
  5432. makeRotationY: function ( theta ) {
  5433. var c = Math.cos( theta ), s = Math.sin( theta );
  5434. this.set(
  5435. c, 0, s, 0,
  5436. 0, 1, 0, 0,
  5437. - s, 0, c, 0,
  5438. 0, 0, 0, 1
  5439. );
  5440. return this;
  5441. },
  5442. makeRotationZ: function ( theta ) {
  5443. var c = Math.cos( theta ), s = Math.sin( theta );
  5444. this.set(
  5445. c, - s, 0, 0,
  5446. s, c, 0, 0,
  5447. 0, 0, 1, 0,
  5448. 0, 0, 0, 1
  5449. );
  5450. return this;
  5451. },
  5452. makeRotationAxis: function ( axis, angle ) {
  5453. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  5454. var c = Math.cos( angle );
  5455. var s = Math.sin( angle );
  5456. var t = 1 - c;
  5457. var x = axis.x, y = axis.y, z = axis.z;
  5458. var tx = t * x, ty = t * y;
  5459. this.set(
  5460. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  5461. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  5462. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  5463. 0, 0, 0, 1
  5464. );
  5465. return this;
  5466. },
  5467. makeScale: function ( x, y, z ) {
  5468. this.set(
  5469. x, 0, 0, 0,
  5470. 0, y, 0, 0,
  5471. 0, 0, z, 0,
  5472. 0, 0, 0, 1
  5473. );
  5474. return this;
  5475. },
  5476. makeShear: function ( x, y, z ) {
  5477. this.set(
  5478. 1, y, z, 0,
  5479. x, 1, z, 0,
  5480. x, y, 1, 0,
  5481. 0, 0, 0, 1
  5482. );
  5483. return this;
  5484. },
  5485. compose: function ( position, quaternion, scale ) {
  5486. this.makeRotationFromQuaternion( quaternion );
  5487. this.scale( scale );
  5488. this.setPosition( position );
  5489. return this;
  5490. },
  5491. decompose: function () {
  5492. var vector = new Vector3();
  5493. var matrix = new Matrix4();
  5494. return function decompose( position, quaternion, scale ) {
  5495. var te = this.elements;
  5496. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  5497. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  5498. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  5499. // if determine is negative, we need to invert one scale
  5500. var det = this.determinant();
  5501. if ( det < 0 ) sx = - sx;
  5502. position.x = te[ 12 ];
  5503. position.y = te[ 13 ];
  5504. position.z = te[ 14 ];
  5505. // scale the rotation part
  5506. matrix.copy( this );
  5507. var invSX = 1 / sx;
  5508. var invSY = 1 / sy;
  5509. var invSZ = 1 / sz;
  5510. matrix.elements[ 0 ] *= invSX;
  5511. matrix.elements[ 1 ] *= invSX;
  5512. matrix.elements[ 2 ] *= invSX;
  5513. matrix.elements[ 4 ] *= invSY;
  5514. matrix.elements[ 5 ] *= invSY;
  5515. matrix.elements[ 6 ] *= invSY;
  5516. matrix.elements[ 8 ] *= invSZ;
  5517. matrix.elements[ 9 ] *= invSZ;
  5518. matrix.elements[ 10 ] *= invSZ;
  5519. quaternion.setFromRotationMatrix( matrix );
  5520. scale.x = sx;
  5521. scale.y = sy;
  5522. scale.z = sz;
  5523. return this;
  5524. };
  5525. }(),
  5526. makePerspective: function ( left, right, top, bottom, near, far ) {
  5527. if ( far === undefined ) {
  5528. console.warn( 'THREE.Matrix4: .makePerspective() has been redefined and has a new signature. Please check the docs.' );
  5529. }
  5530. var te = this.elements;
  5531. var x = 2 * near / ( right - left );
  5532. var y = 2 * near / ( top - bottom );
  5533. var a = ( right + left ) / ( right - left );
  5534. var b = ( top + bottom ) / ( top - bottom );
  5535. var c = - ( far + near ) / ( far - near );
  5536. var d = - 2 * far * near / ( far - near );
  5537. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  5538. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  5539. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  5540. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  5541. return this;
  5542. },
  5543. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  5544. var te = this.elements;
  5545. var w = 1.0 / ( right - left );
  5546. var h = 1.0 / ( top - bottom );
  5547. var p = 1.0 / ( far - near );
  5548. var x = ( right + left ) * w;
  5549. var y = ( top + bottom ) * h;
  5550. var z = ( far + near ) * p;
  5551. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  5552. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  5553. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  5554. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  5555. return this;
  5556. },
  5557. equals: function ( matrix ) {
  5558. var te = this.elements;
  5559. var me = matrix.elements;
  5560. for ( var i = 0; i < 16; i ++ ) {
  5561. if ( te[ i ] !== me[ i ] ) return false;
  5562. }
  5563. return true;
  5564. },
  5565. fromArray: function ( array, offset ) {
  5566. if ( offset === undefined ) offset = 0;
  5567. for ( var i = 0; i < 16; i ++ ) {
  5568. this.elements[ i ] = array[ i + offset ];
  5569. }
  5570. return this;
  5571. },
  5572. toArray: function ( array, offset ) {
  5573. if ( array === undefined ) array = [];
  5574. if ( offset === undefined ) offset = 0;
  5575. var te = this.elements;
  5576. array[ offset ] = te[ 0 ];
  5577. array[ offset + 1 ] = te[ 1 ];
  5578. array[ offset + 2 ] = te[ 2 ];
  5579. array[ offset + 3 ] = te[ 3 ];
  5580. array[ offset + 4 ] = te[ 4 ];
  5581. array[ offset + 5 ] = te[ 5 ];
  5582. array[ offset + 6 ] = te[ 6 ];
  5583. array[ offset + 7 ] = te[ 7 ];
  5584. array[ offset + 8 ] = te[ 8 ];
  5585. array[ offset + 9 ] = te[ 9 ];
  5586. array[ offset + 10 ] = te[ 10 ];
  5587. array[ offset + 11 ] = te[ 11 ];
  5588. array[ offset + 12 ] = te[ 12 ];
  5589. array[ offset + 13 ] = te[ 13 ];
  5590. array[ offset + 14 ] = te[ 14 ];
  5591. array[ offset + 15 ] = te[ 15 ];
  5592. return array;
  5593. }
  5594. } );
  5595. /**
  5596. * @author mikael emtinger / http://gomo.se/
  5597. * @author alteredq / http://alteredqualia.com/
  5598. * @author WestLangley / http://github.com/WestLangley
  5599. * @author bhouston / http://clara.io
  5600. */
  5601. function Quaternion( x, y, z, w ) {
  5602. this._x = x || 0;
  5603. this._y = y || 0;
  5604. this._z = z || 0;
  5605. this._w = ( w !== undefined ) ? w : 1;
  5606. }
  5607. Object.assign( Quaternion, {
  5608. slerp: function ( qa, qb, qm, t ) {
  5609. return qm.copy( qa ).slerp( qb, t );
  5610. },
  5611. slerpFlat: function ( dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5612. // fuzz-free, array-based Quaternion SLERP operation
  5613. var x0 = src0[ srcOffset0 + 0 ],
  5614. y0 = src0[ srcOffset0 + 1 ],
  5615. z0 = src0[ srcOffset0 + 2 ],
  5616. w0 = src0[ srcOffset0 + 3 ],
  5617. x1 = src1[ srcOffset1 + 0 ],
  5618. y1 = src1[ srcOffset1 + 1 ],
  5619. z1 = src1[ srcOffset1 + 2 ],
  5620. w1 = src1[ srcOffset1 + 3 ];
  5621. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5622. var s = 1 - t,
  5623. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5624. dir = ( cos >= 0 ? 1 : - 1 ),
  5625. sqrSin = 1 - cos * cos;
  5626. // Skip the Slerp for tiny steps to avoid numeric problems:
  5627. if ( sqrSin > Number.EPSILON ) {
  5628. var sin = Math.sqrt( sqrSin ),
  5629. len = Math.atan2( sin, cos * dir );
  5630. s = Math.sin( s * len ) / sin;
  5631. t = Math.sin( t * len ) / sin;
  5632. }
  5633. var tDir = t * dir;
  5634. x0 = x0 * s + x1 * tDir;
  5635. y0 = y0 * s + y1 * tDir;
  5636. z0 = z0 * s + z1 * tDir;
  5637. w0 = w0 * s + w1 * tDir;
  5638. // Normalize in case we just did a lerp:
  5639. if ( s === 1 - t ) {
  5640. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5641. x0 *= f;
  5642. y0 *= f;
  5643. z0 *= f;
  5644. w0 *= f;
  5645. }
  5646. }
  5647. dst[ dstOffset ] = x0;
  5648. dst[ dstOffset + 1 ] = y0;
  5649. dst[ dstOffset + 2 ] = z0;
  5650. dst[ dstOffset + 3 ] = w0;
  5651. }
  5652. } );
  5653. Object.defineProperties( Quaternion.prototype, {
  5654. x: {
  5655. get: function () {
  5656. return this._x;
  5657. },
  5658. set: function ( value ) {
  5659. this._x = value;
  5660. this.onChangeCallback();
  5661. }
  5662. },
  5663. y: {
  5664. get: function () {
  5665. return this._y;
  5666. },
  5667. set: function ( value ) {
  5668. this._y = value;
  5669. this.onChangeCallback();
  5670. }
  5671. },
  5672. z: {
  5673. get: function () {
  5674. return this._z;
  5675. },
  5676. set: function ( value ) {
  5677. this._z = value;
  5678. this.onChangeCallback();
  5679. }
  5680. },
  5681. w: {
  5682. get: function () {
  5683. return this._w;
  5684. },
  5685. set: function ( value ) {
  5686. this._w = value;
  5687. this.onChangeCallback();
  5688. }
  5689. }
  5690. } );
  5691. Object.assign( Quaternion.prototype, {
  5692. set: function ( x, y, z, w ) {
  5693. this._x = x;
  5694. this._y = y;
  5695. this._z = z;
  5696. this._w = w;
  5697. this.onChangeCallback();
  5698. return this;
  5699. },
  5700. clone: function () {
  5701. return new this.constructor( this._x, this._y, this._z, this._w );
  5702. },
  5703. copy: function ( quaternion ) {
  5704. this._x = quaternion.x;
  5705. this._y = quaternion.y;
  5706. this._z = quaternion.z;
  5707. this._w = quaternion.w;
  5708. this.onChangeCallback();
  5709. return this;
  5710. },
  5711. setFromEuler: function ( euler, update ) {
  5712. if ( ! ( euler && euler.isEuler ) ) {
  5713. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5714. }
  5715. var x = euler._x, y = euler._y, z = euler._z, order = euler.order;
  5716. // http://www.mathworks.com/matlabcentral/fileexchange/
  5717. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5718. // content/SpinCalc.m
  5719. var cos = Math.cos;
  5720. var sin = Math.sin;
  5721. var c1 = cos( x / 2 );
  5722. var c2 = cos( y / 2 );
  5723. var c3 = cos( z / 2 );
  5724. var s1 = sin( x / 2 );
  5725. var s2 = sin( y / 2 );
  5726. var s3 = sin( z / 2 );
  5727. if ( order === 'XYZ' ) {
  5728. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5729. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5730. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5731. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5732. } else if ( order === 'YXZ' ) {
  5733. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5734. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5735. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5736. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5737. } else if ( order === 'ZXY' ) {
  5738. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5739. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5740. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5741. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5742. } else if ( order === 'ZYX' ) {
  5743. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5744. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5745. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5746. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5747. } else if ( order === 'YZX' ) {
  5748. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5749. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5750. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5751. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5752. } else if ( order === 'XZY' ) {
  5753. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5754. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5755. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5756. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5757. }
  5758. if ( update !== false ) this.onChangeCallback();
  5759. return this;
  5760. },
  5761. setFromAxisAngle: function ( axis, angle ) {
  5762. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5763. // assumes axis is normalized
  5764. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5765. this._x = axis.x * s;
  5766. this._y = axis.y * s;
  5767. this._z = axis.z * s;
  5768. this._w = Math.cos( halfAngle );
  5769. this.onChangeCallback();
  5770. return this;
  5771. },
  5772. setFromRotationMatrix: function ( m ) {
  5773. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5774. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5775. var te = m.elements,
  5776. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5777. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5778. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5779. trace = m11 + m22 + m33,
  5780. s;
  5781. if ( trace > 0 ) {
  5782. s = 0.5 / Math.sqrt( trace + 1.0 );
  5783. this._w = 0.25 / s;
  5784. this._x = ( m32 - m23 ) * s;
  5785. this._y = ( m13 - m31 ) * s;
  5786. this._z = ( m21 - m12 ) * s;
  5787. } else if ( m11 > m22 && m11 > m33 ) {
  5788. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5789. this._w = ( m32 - m23 ) / s;
  5790. this._x = 0.25 * s;
  5791. this._y = ( m12 + m21 ) / s;
  5792. this._z = ( m13 + m31 ) / s;
  5793. } else if ( m22 > m33 ) {
  5794. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5795. this._w = ( m13 - m31 ) / s;
  5796. this._x = ( m12 + m21 ) / s;
  5797. this._y = 0.25 * s;
  5798. this._z = ( m23 + m32 ) / s;
  5799. } else {
  5800. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5801. this._w = ( m21 - m12 ) / s;
  5802. this._x = ( m13 + m31 ) / s;
  5803. this._y = ( m23 + m32 ) / s;
  5804. this._z = 0.25 * s;
  5805. }
  5806. this.onChangeCallback();
  5807. return this;
  5808. },
  5809. setFromUnitVectors: function () {
  5810. // assumes direction vectors vFrom and vTo are normalized
  5811. var v1 = new Vector3();
  5812. var r;
  5813. var EPS = 0.000001;
  5814. return function setFromUnitVectors( vFrom, vTo ) {
  5815. if ( v1 === undefined ) v1 = new Vector3();
  5816. r = vFrom.dot( vTo ) + 1;
  5817. if ( r < EPS ) {
  5818. r = 0;
  5819. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5820. v1.set( - vFrom.y, vFrom.x, 0 );
  5821. } else {
  5822. v1.set( 0, - vFrom.z, vFrom.y );
  5823. }
  5824. } else {
  5825. v1.crossVectors( vFrom, vTo );
  5826. }
  5827. this._x = v1.x;
  5828. this._y = v1.y;
  5829. this._z = v1.z;
  5830. this._w = r;
  5831. return this.normalize();
  5832. };
  5833. }(),
  5834. inverse: function () {
  5835. return this.conjugate().normalize();
  5836. },
  5837. conjugate: function () {
  5838. this._x *= - 1;
  5839. this._y *= - 1;
  5840. this._z *= - 1;
  5841. this.onChangeCallback();
  5842. return this;
  5843. },
  5844. dot: function ( v ) {
  5845. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5846. },
  5847. lengthSq: function () {
  5848. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5849. },
  5850. length: function () {
  5851. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5852. },
  5853. normalize: function () {
  5854. var l = this.length();
  5855. if ( l === 0 ) {
  5856. this._x = 0;
  5857. this._y = 0;
  5858. this._z = 0;
  5859. this._w = 1;
  5860. } else {
  5861. l = 1 / l;
  5862. this._x = this._x * l;
  5863. this._y = this._y * l;
  5864. this._z = this._z * l;
  5865. this._w = this._w * l;
  5866. }
  5867. this.onChangeCallback();
  5868. return this;
  5869. },
  5870. multiply: function ( q, p ) {
  5871. if ( p !== undefined ) {
  5872. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5873. return this.multiplyQuaternions( q, p );
  5874. }
  5875. return this.multiplyQuaternions( this, q );
  5876. },
  5877. premultiply: function ( q ) {
  5878. return this.multiplyQuaternions( q, this );
  5879. },
  5880. multiplyQuaternions: function ( a, b ) {
  5881. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5882. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5883. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5884. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5885. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5886. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5887. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5888. this.onChangeCallback();
  5889. return this;
  5890. },
  5891. slerp: function ( qb, t ) {
  5892. if ( t === 0 ) return this;
  5893. if ( t === 1 ) return this.copy( qb );
  5894. var x = this._x, y = this._y, z = this._z, w = this._w;
  5895. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5896. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5897. if ( cosHalfTheta < 0 ) {
  5898. this._w = - qb._w;
  5899. this._x = - qb._x;
  5900. this._y = - qb._y;
  5901. this._z = - qb._z;
  5902. cosHalfTheta = - cosHalfTheta;
  5903. } else {
  5904. this.copy( qb );
  5905. }
  5906. if ( cosHalfTheta >= 1.0 ) {
  5907. this._w = w;
  5908. this._x = x;
  5909. this._y = y;
  5910. this._z = z;
  5911. return this;
  5912. }
  5913. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  5914. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  5915. this._w = 0.5 * ( w + this._w );
  5916. this._x = 0.5 * ( x + this._x );
  5917. this._y = 0.5 * ( y + this._y );
  5918. this._z = 0.5 * ( z + this._z );
  5919. return this;
  5920. }
  5921. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5922. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5923. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5924. this._w = ( w * ratioA + this._w * ratioB );
  5925. this._x = ( x * ratioA + this._x * ratioB );
  5926. this._y = ( y * ratioA + this._y * ratioB );
  5927. this._z = ( z * ratioA + this._z * ratioB );
  5928. this.onChangeCallback();
  5929. return this;
  5930. },
  5931. equals: function ( quaternion ) {
  5932. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5933. },
  5934. fromArray: function ( array, offset ) {
  5935. if ( offset === undefined ) offset = 0;
  5936. this._x = array[ offset ];
  5937. this._y = array[ offset + 1 ];
  5938. this._z = array[ offset + 2 ];
  5939. this._w = array[ offset + 3 ];
  5940. this.onChangeCallback();
  5941. return this;
  5942. },
  5943. toArray: function ( array, offset ) {
  5944. if ( array === undefined ) array = [];
  5945. if ( offset === undefined ) offset = 0;
  5946. array[ offset ] = this._x;
  5947. array[ offset + 1 ] = this._y;
  5948. array[ offset + 2 ] = this._z;
  5949. array[ offset + 3 ] = this._w;
  5950. return array;
  5951. },
  5952. onChange: function ( callback ) {
  5953. this.onChangeCallback = callback;
  5954. return this;
  5955. },
  5956. onChangeCallback: function () {}
  5957. } );
  5958. /**
  5959. * @author mrdoob / http://mrdoob.com/
  5960. * @author kile / http://kile.stravaganza.org/
  5961. * @author philogb / http://blog.thejit.org/
  5962. * @author mikael emtinger / http://gomo.se/
  5963. * @author egraether / http://egraether.com/
  5964. * @author WestLangley / http://github.com/WestLangley
  5965. */
  5966. function Vector3( x, y, z ) {
  5967. this.x = x || 0;
  5968. this.y = y || 0;
  5969. this.z = z || 0;
  5970. }
  5971. Object.assign( Vector3.prototype, {
  5972. isVector3: true,
  5973. set: function ( x, y, z ) {
  5974. this.x = x;
  5975. this.y = y;
  5976. this.z = z;
  5977. return this;
  5978. },
  5979. setScalar: function ( scalar ) {
  5980. this.x = scalar;
  5981. this.y = scalar;
  5982. this.z = scalar;
  5983. return this;
  5984. },
  5985. setX: function ( x ) {
  5986. this.x = x;
  5987. return this;
  5988. },
  5989. setY: function ( y ) {
  5990. this.y = y;
  5991. return this;
  5992. },
  5993. setZ: function ( z ) {
  5994. this.z = z;
  5995. return this;
  5996. },
  5997. setComponent: function ( index, value ) {
  5998. switch ( index ) {
  5999. case 0: this.x = value; break;
  6000. case 1: this.y = value; break;
  6001. case 2: this.z = value; break;
  6002. default: throw new Error( 'index is out of range: ' + index );
  6003. }
  6004. return this;
  6005. },
  6006. getComponent: function ( index ) {
  6007. switch ( index ) {
  6008. case 0: return this.x;
  6009. case 1: return this.y;
  6010. case 2: return this.z;
  6011. default: throw new Error( 'index is out of range: ' + index );
  6012. }
  6013. },
  6014. clone: function () {
  6015. return new this.constructor( this.x, this.y, this.z );
  6016. },
  6017. copy: function ( v ) {
  6018. this.x = v.x;
  6019. this.y = v.y;
  6020. this.z = v.z;
  6021. return this;
  6022. },
  6023. add: function ( v, w ) {
  6024. if ( w !== undefined ) {
  6025. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6026. return this.addVectors( v, w );
  6027. }
  6028. this.x += v.x;
  6029. this.y += v.y;
  6030. this.z += v.z;
  6031. return this;
  6032. },
  6033. addScalar: function ( s ) {
  6034. this.x += s;
  6035. this.y += s;
  6036. this.z += s;
  6037. return this;
  6038. },
  6039. addVectors: function ( a, b ) {
  6040. this.x = a.x + b.x;
  6041. this.y = a.y + b.y;
  6042. this.z = a.z + b.z;
  6043. return this;
  6044. },
  6045. addScaledVector: function ( v, s ) {
  6046. this.x += v.x * s;
  6047. this.y += v.y * s;
  6048. this.z += v.z * s;
  6049. return this;
  6050. },
  6051. sub: function ( v, w ) {
  6052. if ( w !== undefined ) {
  6053. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6054. return this.subVectors( v, w );
  6055. }
  6056. this.x -= v.x;
  6057. this.y -= v.y;
  6058. this.z -= v.z;
  6059. return this;
  6060. },
  6061. subScalar: function ( s ) {
  6062. this.x -= s;
  6063. this.y -= s;
  6064. this.z -= s;
  6065. return this;
  6066. },
  6067. subVectors: function ( a, b ) {
  6068. this.x = a.x - b.x;
  6069. this.y = a.y - b.y;
  6070. this.z = a.z - b.z;
  6071. return this;
  6072. },
  6073. multiply: function ( v, w ) {
  6074. if ( w !== undefined ) {
  6075. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  6076. return this.multiplyVectors( v, w );
  6077. }
  6078. this.x *= v.x;
  6079. this.y *= v.y;
  6080. this.z *= v.z;
  6081. return this;
  6082. },
  6083. multiplyScalar: function ( scalar ) {
  6084. this.x *= scalar;
  6085. this.y *= scalar;
  6086. this.z *= scalar;
  6087. return this;
  6088. },
  6089. multiplyVectors: function ( a, b ) {
  6090. this.x = a.x * b.x;
  6091. this.y = a.y * b.y;
  6092. this.z = a.z * b.z;
  6093. return this;
  6094. },
  6095. applyEuler: function () {
  6096. var quaternion = new Quaternion();
  6097. return function applyEuler( euler ) {
  6098. if ( ! ( euler && euler.isEuler ) ) {
  6099. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  6100. }
  6101. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  6102. };
  6103. }(),
  6104. applyAxisAngle: function () {
  6105. var quaternion = new Quaternion();
  6106. return function applyAxisAngle( axis, angle ) {
  6107. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  6108. };
  6109. }(),
  6110. applyMatrix3: function ( m ) {
  6111. var x = this.x, y = this.y, z = this.z;
  6112. var e = m.elements;
  6113. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  6114. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  6115. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  6116. return this;
  6117. },
  6118. applyMatrix4: function ( m ) {
  6119. var x = this.x, y = this.y, z = this.z;
  6120. var e = m.elements;
  6121. var w = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] );
  6122. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * w;
  6123. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * w;
  6124. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * w;
  6125. return this;
  6126. },
  6127. applyQuaternion: function ( q ) {
  6128. var x = this.x, y = this.y, z = this.z;
  6129. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  6130. // calculate quat * vector
  6131. var ix = qw * x + qy * z - qz * y;
  6132. var iy = qw * y + qz * x - qx * z;
  6133. var iz = qw * z + qx * y - qy * x;
  6134. var iw = - qx * x - qy * y - qz * z;
  6135. // calculate result * inverse quat
  6136. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  6137. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  6138. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6139. return this;
  6140. },
  6141. project: function () {
  6142. var matrix = new Matrix4();
  6143. return function project( camera ) {
  6144. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  6145. return this.applyMatrix4( matrix );
  6146. };
  6147. }(),
  6148. unproject: function () {
  6149. var matrix = new Matrix4();
  6150. return function unproject( camera ) {
  6151. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  6152. return this.applyMatrix4( matrix );
  6153. };
  6154. }(),
  6155. transformDirection: function ( m ) {
  6156. // input: THREE.Matrix4 affine matrix
  6157. // vector interpreted as a direction
  6158. var x = this.x, y = this.y, z = this.z;
  6159. var e = m.elements;
  6160. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6161. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6162. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6163. return this.normalize();
  6164. },
  6165. divide: function ( v ) {
  6166. this.x /= v.x;
  6167. this.y /= v.y;
  6168. this.z /= v.z;
  6169. return this;
  6170. },
  6171. divideScalar: function ( scalar ) {
  6172. return this.multiplyScalar( 1 / scalar );
  6173. },
  6174. min: function ( v ) {
  6175. this.x = Math.min( this.x, v.x );
  6176. this.y = Math.min( this.y, v.y );
  6177. this.z = Math.min( this.z, v.z );
  6178. return this;
  6179. },
  6180. max: function ( v ) {
  6181. this.x = Math.max( this.x, v.x );
  6182. this.y = Math.max( this.y, v.y );
  6183. this.z = Math.max( this.z, v.z );
  6184. return this;
  6185. },
  6186. clamp: function ( min, max ) {
  6187. // assumes min < max, componentwise
  6188. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6189. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6190. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6191. return this;
  6192. },
  6193. clampScalar: function () {
  6194. var min = new Vector3();
  6195. var max = new Vector3();
  6196. return function clampScalar( minVal, maxVal ) {
  6197. min.set( minVal, minVal, minVal );
  6198. max.set( maxVal, maxVal, maxVal );
  6199. return this.clamp( min, max );
  6200. };
  6201. }(),
  6202. clampLength: function ( min, max ) {
  6203. var length = this.length();
  6204. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  6205. },
  6206. floor: function () {
  6207. this.x = Math.floor( this.x );
  6208. this.y = Math.floor( this.y );
  6209. this.z = Math.floor( this.z );
  6210. return this;
  6211. },
  6212. ceil: function () {
  6213. this.x = Math.ceil( this.x );
  6214. this.y = Math.ceil( this.y );
  6215. this.z = Math.ceil( this.z );
  6216. return this;
  6217. },
  6218. round: function () {
  6219. this.x = Math.round( this.x );
  6220. this.y = Math.round( this.y );
  6221. this.z = Math.round( this.z );
  6222. return this;
  6223. },
  6224. roundToZero: function () {
  6225. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6226. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6227. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6228. return this;
  6229. },
  6230. negate: function () {
  6231. this.x = - this.x;
  6232. this.y = - this.y;
  6233. this.z = - this.z;
  6234. return this;
  6235. },
  6236. dot: function ( v ) {
  6237. return this.x * v.x + this.y * v.y + this.z * v.z;
  6238. },
  6239. // TODO lengthSquared?
  6240. lengthSq: function () {
  6241. return this.x * this.x + this.y * this.y + this.z * this.z;
  6242. },
  6243. length: function () {
  6244. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6245. },
  6246. manhattanLength: function () {
  6247. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6248. },
  6249. normalize: function () {
  6250. return this.divideScalar( this.length() || 1 );
  6251. },
  6252. setLength: function ( length ) {
  6253. return this.normalize().multiplyScalar( length );
  6254. },
  6255. lerp: function ( v, alpha ) {
  6256. this.x += ( v.x - this.x ) * alpha;
  6257. this.y += ( v.y - this.y ) * alpha;
  6258. this.z += ( v.z - this.z ) * alpha;
  6259. return this;
  6260. },
  6261. lerpVectors: function ( v1, v2, alpha ) {
  6262. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6263. },
  6264. cross: function ( v, w ) {
  6265. if ( w !== undefined ) {
  6266. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6267. return this.crossVectors( v, w );
  6268. }
  6269. return this.crossVectors( this, v );
  6270. },
  6271. crossVectors: function ( a, b ) {
  6272. var ax = a.x, ay = a.y, az = a.z;
  6273. var bx = b.x, by = b.y, bz = b.z;
  6274. this.x = ay * bz - az * by;
  6275. this.y = az * bx - ax * bz;
  6276. this.z = ax * by - ay * bx;
  6277. return this;
  6278. },
  6279. projectOnVector: function ( vector ) {
  6280. var scalar = vector.dot( this ) / vector.lengthSq();
  6281. return this.copy( vector ).multiplyScalar( scalar );
  6282. },
  6283. projectOnPlane: function () {
  6284. var v1 = new Vector3();
  6285. return function projectOnPlane( planeNormal ) {
  6286. v1.copy( this ).projectOnVector( planeNormal );
  6287. return this.sub( v1 );
  6288. };
  6289. }(),
  6290. reflect: function () {
  6291. // reflect incident vector off plane orthogonal to normal
  6292. // normal is assumed to have unit length
  6293. var v1 = new Vector3();
  6294. return function reflect( normal ) {
  6295. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6296. };
  6297. }(),
  6298. angleTo: function ( v ) {
  6299. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6300. // clamp, to handle numerical problems
  6301. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6302. },
  6303. distanceTo: function ( v ) {
  6304. return Math.sqrt( this.distanceToSquared( v ) );
  6305. },
  6306. distanceToSquared: function ( v ) {
  6307. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6308. return dx * dx + dy * dy + dz * dz;
  6309. },
  6310. manhattanDistanceTo: function ( v ) {
  6311. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6312. },
  6313. setFromSpherical: function ( s ) {
  6314. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  6315. this.x = sinPhiRadius * Math.sin( s.theta );
  6316. this.y = Math.cos( s.phi ) * s.radius;
  6317. this.z = sinPhiRadius * Math.cos( s.theta );
  6318. return this;
  6319. },
  6320. setFromCylindrical: function ( c ) {
  6321. this.x = c.radius * Math.sin( c.theta );
  6322. this.y = c.y;
  6323. this.z = c.radius * Math.cos( c.theta );
  6324. return this;
  6325. },
  6326. setFromMatrixPosition: function ( m ) {
  6327. var e = m.elements;
  6328. this.x = e[ 12 ];
  6329. this.y = e[ 13 ];
  6330. this.z = e[ 14 ];
  6331. return this;
  6332. },
  6333. setFromMatrixScale: function ( m ) {
  6334. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6335. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6336. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6337. this.x = sx;
  6338. this.y = sy;
  6339. this.z = sz;
  6340. return this;
  6341. },
  6342. setFromMatrixColumn: function ( m, index ) {
  6343. return this.fromArray( m.elements, index * 4 );
  6344. },
  6345. equals: function ( v ) {
  6346. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6347. },
  6348. fromArray: function ( array, offset ) {
  6349. if ( offset === undefined ) offset = 0;
  6350. this.x = array[ offset ];
  6351. this.y = array[ offset + 1 ];
  6352. this.z = array[ offset + 2 ];
  6353. return this;
  6354. },
  6355. toArray: function ( array, offset ) {
  6356. if ( array === undefined ) array = [];
  6357. if ( offset === undefined ) offset = 0;
  6358. array[ offset ] = this.x;
  6359. array[ offset + 1 ] = this.y;
  6360. array[ offset + 2 ] = this.z;
  6361. return array;
  6362. },
  6363. fromBufferAttribute: function ( attribute, index, offset ) {
  6364. if ( offset !== undefined ) {
  6365. console.warn( 'THREE.Vector3: offset has been removed from .fromBufferAttribute().' );
  6366. }
  6367. this.x = attribute.getX( index );
  6368. this.y = attribute.getY( index );
  6369. this.z = attribute.getZ( index );
  6370. return this;
  6371. }
  6372. } );
  6373. /**
  6374. * @author alteredq / http://alteredqualia.com/
  6375. * @author WestLangley / http://github.com/WestLangley
  6376. * @author bhouston / http://clara.io
  6377. * @author tschw
  6378. */
  6379. function Matrix3() {
  6380. this.elements = [
  6381. 1, 0, 0,
  6382. 0, 1, 0,
  6383. 0, 0, 1
  6384. ];
  6385. if ( arguments.length > 0 ) {
  6386. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  6387. }
  6388. }
  6389. Object.assign( Matrix3.prototype, {
  6390. isMatrix3: true,
  6391. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  6392. var te = this.elements;
  6393. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  6394. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  6395. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  6396. return this;
  6397. },
  6398. identity: function () {
  6399. this.set(
  6400. 1, 0, 0,
  6401. 0, 1, 0,
  6402. 0, 0, 1
  6403. );
  6404. return this;
  6405. },
  6406. clone: function () {
  6407. return new this.constructor().fromArray( this.elements );
  6408. },
  6409. copy: function ( m ) {
  6410. var te = this.elements;
  6411. var me = m.elements;
  6412. te[ 0 ] = me[ 0 ]; te[ 1 ] = me[ 1 ]; te[ 2 ] = me[ 2 ];
  6413. te[ 3 ] = me[ 3 ]; te[ 4 ] = me[ 4 ]; te[ 5 ] = me[ 5 ];
  6414. te[ 6 ] = me[ 6 ]; te[ 7 ] = me[ 7 ]; te[ 8 ] = me[ 8 ];
  6415. return this;
  6416. },
  6417. setFromMatrix4: function ( m ) {
  6418. var me = m.elements;
  6419. this.set(
  6420. me[ 0 ], me[ 4 ], me[ 8 ],
  6421. me[ 1 ], me[ 5 ], me[ 9 ],
  6422. me[ 2 ], me[ 6 ], me[ 10 ]
  6423. );
  6424. return this;
  6425. },
  6426. applyToBufferAttribute: function () {
  6427. var v1 = new Vector3();
  6428. return function applyToBufferAttribute( attribute ) {
  6429. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6430. v1.x = attribute.getX( i );
  6431. v1.y = attribute.getY( i );
  6432. v1.z = attribute.getZ( i );
  6433. v1.applyMatrix3( this );
  6434. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6435. }
  6436. return attribute;
  6437. };
  6438. }(),
  6439. multiply: function ( m ) {
  6440. return this.multiplyMatrices( this, m );
  6441. },
  6442. premultiply: function ( m ) {
  6443. return this.multiplyMatrices( m, this );
  6444. },
  6445. multiplyMatrices: function ( a, b ) {
  6446. var ae = a.elements;
  6447. var be = b.elements;
  6448. var te = this.elements;
  6449. var a11 = ae[ 0 ], a12 = ae[ 3 ], a13 = ae[ 6 ];
  6450. var a21 = ae[ 1 ], a22 = ae[ 4 ], a23 = ae[ 7 ];
  6451. var a31 = ae[ 2 ], a32 = ae[ 5 ], a33 = ae[ 8 ];
  6452. var b11 = be[ 0 ], b12 = be[ 3 ], b13 = be[ 6 ];
  6453. var b21 = be[ 1 ], b22 = be[ 4 ], b23 = be[ 7 ];
  6454. var b31 = be[ 2 ], b32 = be[ 5 ], b33 = be[ 8 ];
  6455. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31;
  6456. te[ 3 ] = a11 * b12 + a12 * b22 + a13 * b32;
  6457. te[ 6 ] = a11 * b13 + a12 * b23 + a13 * b33;
  6458. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31;
  6459. te[ 4 ] = a21 * b12 + a22 * b22 + a23 * b32;
  6460. te[ 7 ] = a21 * b13 + a22 * b23 + a23 * b33;
  6461. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31;
  6462. te[ 5 ] = a31 * b12 + a32 * b22 + a33 * b32;
  6463. te[ 8 ] = a31 * b13 + a32 * b23 + a33 * b33;
  6464. return this;
  6465. },
  6466. multiplyScalar: function ( s ) {
  6467. var te = this.elements;
  6468. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  6469. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  6470. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  6471. return this;
  6472. },
  6473. determinant: function () {
  6474. var te = this.elements;
  6475. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  6476. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  6477. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  6478. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  6479. },
  6480. getInverse: function ( matrix, throwOnDegenerate ) {
  6481. if ( matrix && matrix.isMatrix4 ) {
  6482. console.error( "THREE.Matrix3: .getInverse() no longer takes a Matrix4 argument." );
  6483. }
  6484. var me = matrix.elements,
  6485. te = this.elements,
  6486. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  6487. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  6488. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  6489. t11 = n33 * n22 - n32 * n23,
  6490. t12 = n32 * n13 - n33 * n12,
  6491. t13 = n23 * n12 - n22 * n13,
  6492. det = n11 * t11 + n21 * t12 + n31 * t13;
  6493. if ( det === 0 ) {
  6494. var msg = "THREE.Matrix3: .getInverse() can't invert matrix, determinant is 0";
  6495. if ( throwOnDegenerate === true ) {
  6496. throw new Error( msg );
  6497. } else {
  6498. console.warn( msg );
  6499. }
  6500. return this.identity();
  6501. }
  6502. var detInv = 1 / det;
  6503. te[ 0 ] = t11 * detInv;
  6504. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  6505. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  6506. te[ 3 ] = t12 * detInv;
  6507. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  6508. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  6509. te[ 6 ] = t13 * detInv;
  6510. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  6511. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  6512. return this;
  6513. },
  6514. transpose: function () {
  6515. var tmp, m = this.elements;
  6516. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  6517. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  6518. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  6519. return this;
  6520. },
  6521. getNormalMatrix: function ( matrix4 ) {
  6522. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  6523. },
  6524. transposeIntoArray: function ( r ) {
  6525. var m = this.elements;
  6526. r[ 0 ] = m[ 0 ];
  6527. r[ 1 ] = m[ 3 ];
  6528. r[ 2 ] = m[ 6 ];
  6529. r[ 3 ] = m[ 1 ];
  6530. r[ 4 ] = m[ 4 ];
  6531. r[ 5 ] = m[ 7 ];
  6532. r[ 6 ] = m[ 2 ];
  6533. r[ 7 ] = m[ 5 ];
  6534. r[ 8 ] = m[ 8 ];
  6535. return this;
  6536. },
  6537. setUvTransform: function ( tx, ty, sx, sy, rotation, cx, cy ) {
  6538. var c = Math.cos( rotation );
  6539. var s = Math.sin( rotation );
  6540. this.set(
  6541. sx * c, sx * s, - sx * ( c * cx + s * cy ) + cx + tx,
  6542. - sy * s, sy * c, - sy * ( - s * cx + c * cy ) + cy + ty,
  6543. 0, 0, 1
  6544. );
  6545. },
  6546. scale: function ( sx, sy ) {
  6547. var te = this.elements;
  6548. te[ 0 ] *= sx; te[ 3 ] *= sx; te[ 6 ] *= sx;
  6549. te[ 1 ] *= sy; te[ 4 ] *= sy; te[ 7 ] *= sy;
  6550. return this;
  6551. },
  6552. rotate: function ( theta ) {
  6553. var c = Math.cos( theta );
  6554. var s = Math.sin( theta );
  6555. var te = this.elements;
  6556. var a11 = te[ 0 ], a12 = te[ 3 ], a13 = te[ 6 ];
  6557. var a21 = te[ 1 ], a22 = te[ 4 ], a23 = te[ 7 ];
  6558. te[ 0 ] = c * a11 + s * a21;
  6559. te[ 3 ] = c * a12 + s * a22;
  6560. te[ 6 ] = c * a13 + s * a23;
  6561. te[ 1 ] = - s * a11 + c * a21;
  6562. te[ 4 ] = - s * a12 + c * a22;
  6563. te[ 7 ] = - s * a13 + c * a23;
  6564. return this;
  6565. },
  6566. translate: function ( tx, ty ) {
  6567. var te = this.elements;
  6568. te[ 0 ] += tx * te[ 2 ]; te[ 3 ] += tx * te[ 5 ]; te[ 6 ] += tx * te[ 8 ];
  6569. te[ 1 ] += ty * te[ 2 ]; te[ 4 ] += ty * te[ 5 ]; te[ 7 ] += ty * te[ 8 ];
  6570. return this;
  6571. },
  6572. equals: function ( matrix ) {
  6573. var te = this.elements;
  6574. var me = matrix.elements;
  6575. for ( var i = 0; i < 9; i ++ ) {
  6576. if ( te[ i ] !== me[ i ] ) return false;
  6577. }
  6578. return true;
  6579. },
  6580. fromArray: function ( array, offset ) {
  6581. if ( offset === undefined ) offset = 0;
  6582. for ( var i = 0; i < 9; i ++ ) {
  6583. this.elements[ i ] = array[ i + offset ];
  6584. }
  6585. return this;
  6586. },
  6587. toArray: function ( array, offset ) {
  6588. if ( array === undefined ) array = [];
  6589. if ( offset === undefined ) offset = 0;
  6590. var te = this.elements;
  6591. array[ offset ] = te[ 0 ];
  6592. array[ offset + 1 ] = te[ 1 ];
  6593. array[ offset + 2 ] = te[ 2 ];
  6594. array[ offset + 3 ] = te[ 3 ];
  6595. array[ offset + 4 ] = te[ 4 ];
  6596. array[ offset + 5 ] = te[ 5 ];
  6597. array[ offset + 6 ] = te[ 6 ];
  6598. array[ offset + 7 ] = te[ 7 ];
  6599. array[ offset + 8 ] = te[ 8 ];
  6600. return array;
  6601. }
  6602. } );
  6603. /**
  6604. * @author mrdoob / http://mrdoob.com/
  6605. * @author alteredq / http://alteredqualia.com/
  6606. * @author szimek / https://github.com/szimek/
  6607. */
  6608. var textureId = 0;
  6609. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6610. Object.defineProperty( this, 'id', { value: textureId ++ } );
  6611. this.uuid = _Math.generateUUID();
  6612. this.name = '';
  6613. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  6614. this.mipmaps = [];
  6615. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  6616. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  6617. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  6618. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  6619. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  6620. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6621. this.format = format !== undefined ? format : RGBAFormat;
  6622. this.type = type !== undefined ? type : UnsignedByteType;
  6623. this.offset = new Vector2( 0, 0 );
  6624. this.repeat = new Vector2( 1, 1 );
  6625. this.center = new Vector2( 0, 0 );
  6626. this.rotation = 0;
  6627. this.matrixAutoUpdate = true;
  6628. this.matrix = new Matrix3();
  6629. this.generateMipmaps = true;
  6630. this.premultiplyAlpha = false;
  6631. this.flipY = true;
  6632. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  6633. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  6634. //
  6635. // Also changing the encoding after already used by a Material will not automatically make the Material
  6636. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  6637. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  6638. this.version = 0;
  6639. this.onUpdate = null;
  6640. }
  6641. Texture.DEFAULT_IMAGE = undefined;
  6642. Texture.DEFAULT_MAPPING = UVMapping;
  6643. Texture.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  6644. constructor: Texture,
  6645. isTexture: true,
  6646. clone: function () {
  6647. return new this.constructor().copy( this );
  6648. },
  6649. copy: function ( source ) {
  6650. this.name = source.name;
  6651. this.image = source.image;
  6652. this.mipmaps = source.mipmaps.slice( 0 );
  6653. this.mapping = source.mapping;
  6654. this.wrapS = source.wrapS;
  6655. this.wrapT = source.wrapT;
  6656. this.magFilter = source.magFilter;
  6657. this.minFilter = source.minFilter;
  6658. this.anisotropy = source.anisotropy;
  6659. this.format = source.format;
  6660. this.type = source.type;
  6661. this.offset.copy( source.offset );
  6662. this.repeat.copy( source.repeat );
  6663. this.center.copy( source.center );
  6664. this.rotation = source.rotation;
  6665. this.matrixAutoUpdate = source.matrixAutoUpdate;
  6666. this.matrix.copy( source.matrix );
  6667. this.generateMipmaps = source.generateMipmaps;
  6668. this.premultiplyAlpha = source.premultiplyAlpha;
  6669. this.flipY = source.flipY;
  6670. this.unpackAlignment = source.unpackAlignment;
  6671. this.encoding = source.encoding;
  6672. return this;
  6673. },
  6674. toJSON: function ( meta ) {
  6675. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  6676. if ( ! isRootObject && meta.textures[ this.uuid ] !== undefined ) {
  6677. return meta.textures[ this.uuid ];
  6678. }
  6679. function getDataURL( image ) {
  6680. var canvas;
  6681. if ( image instanceof HTMLCanvasElement ) {
  6682. canvas = image;
  6683. } else {
  6684. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  6685. canvas.width = image.width;
  6686. canvas.height = image.height;
  6687. var context = canvas.getContext( '2d' );
  6688. if ( image instanceof ImageData ) {
  6689. context.putImageData( image, 0, 0 );
  6690. } else {
  6691. context.drawImage( image, 0, 0, image.width, image.height );
  6692. }
  6693. }
  6694. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  6695. return canvas.toDataURL( 'image/jpeg', 0.6 );
  6696. } else {
  6697. return canvas.toDataURL( 'image/png' );
  6698. }
  6699. }
  6700. var output = {
  6701. metadata: {
  6702. version: 4.5,
  6703. type: 'Texture',
  6704. generator: 'Texture.toJSON'
  6705. },
  6706. uuid: this.uuid,
  6707. name: this.name,
  6708. mapping: this.mapping,
  6709. repeat: [ this.repeat.x, this.repeat.y ],
  6710. offset: [ this.offset.x, this.offset.y ],
  6711. center: [ this.center.x, this.center.y ],
  6712. rotation: this.rotation,
  6713. wrap: [ this.wrapS, this.wrapT ],
  6714. minFilter: this.minFilter,
  6715. magFilter: this.magFilter,
  6716. anisotropy: this.anisotropy,
  6717. flipY: this.flipY
  6718. };
  6719. if ( this.image !== undefined ) {
  6720. // TODO: Move to THREE.Image
  6721. var image = this.image;
  6722. if ( image.uuid === undefined ) {
  6723. image.uuid = _Math.generateUUID(); // UGH
  6724. }
  6725. if ( ! isRootObject && meta.images[ image.uuid ] === undefined ) {
  6726. meta.images[ image.uuid ] = {
  6727. uuid: image.uuid,
  6728. url: getDataURL( image )
  6729. };
  6730. }
  6731. output.image = image.uuid;
  6732. }
  6733. if ( ! isRootObject ) {
  6734. meta.textures[ this.uuid ] = output;
  6735. }
  6736. return output;
  6737. },
  6738. dispose: function () {
  6739. this.dispatchEvent( { type: 'dispose' } );
  6740. },
  6741. transformUv: function ( uv ) {
  6742. if ( this.mapping !== UVMapping ) return;
  6743. uv.applyMatrix3( this.matrix );
  6744. if ( uv.x < 0 || uv.x > 1 ) {
  6745. switch ( this.wrapS ) {
  6746. case RepeatWrapping:
  6747. uv.x = uv.x - Math.floor( uv.x );
  6748. break;
  6749. case ClampToEdgeWrapping:
  6750. uv.x = uv.x < 0 ? 0 : 1;
  6751. break;
  6752. case MirroredRepeatWrapping:
  6753. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  6754. uv.x = Math.ceil( uv.x ) - uv.x;
  6755. } else {
  6756. uv.x = uv.x - Math.floor( uv.x );
  6757. }
  6758. break;
  6759. }
  6760. }
  6761. if ( uv.y < 0 || uv.y > 1 ) {
  6762. switch ( this.wrapT ) {
  6763. case RepeatWrapping:
  6764. uv.y = uv.y - Math.floor( uv.y );
  6765. break;
  6766. case ClampToEdgeWrapping:
  6767. uv.y = uv.y < 0 ? 0 : 1;
  6768. break;
  6769. case MirroredRepeatWrapping:
  6770. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  6771. uv.y = Math.ceil( uv.y ) - uv.y;
  6772. } else {
  6773. uv.y = uv.y - Math.floor( uv.y );
  6774. }
  6775. break;
  6776. }
  6777. }
  6778. if ( this.flipY ) {
  6779. uv.y = 1 - uv.y;
  6780. }
  6781. }
  6782. } );
  6783. Object.defineProperty( Texture.prototype, "needsUpdate", {
  6784. set: function ( value ) {
  6785. if ( value === true ) this.version ++;
  6786. }
  6787. } );
  6788. /**
  6789. * @author supereggbert / http://www.paulbrunt.co.uk/
  6790. * @author philogb / http://blog.thejit.org/
  6791. * @author mikael emtinger / http://gomo.se/
  6792. * @author egraether / http://egraether.com/
  6793. * @author WestLangley / http://github.com/WestLangley
  6794. */
  6795. function Vector4( x, y, z, w ) {
  6796. this.x = x || 0;
  6797. this.y = y || 0;
  6798. this.z = z || 0;
  6799. this.w = ( w !== undefined ) ? w : 1;
  6800. }
  6801. Object.assign( Vector4.prototype, {
  6802. isVector4: true,
  6803. set: function ( x, y, z, w ) {
  6804. this.x = x;
  6805. this.y = y;
  6806. this.z = z;
  6807. this.w = w;
  6808. return this;
  6809. },
  6810. setScalar: function ( scalar ) {
  6811. this.x = scalar;
  6812. this.y = scalar;
  6813. this.z = scalar;
  6814. this.w = scalar;
  6815. return this;
  6816. },
  6817. setX: function ( x ) {
  6818. this.x = x;
  6819. return this;
  6820. },
  6821. setY: function ( y ) {
  6822. this.y = y;
  6823. return this;
  6824. },
  6825. setZ: function ( z ) {
  6826. this.z = z;
  6827. return this;
  6828. },
  6829. setW: function ( w ) {
  6830. this.w = w;
  6831. return this;
  6832. },
  6833. setComponent: function ( index, value ) {
  6834. switch ( index ) {
  6835. case 0: this.x = value; break;
  6836. case 1: this.y = value; break;
  6837. case 2: this.z = value; break;
  6838. case 3: this.w = value; break;
  6839. default: throw new Error( 'index is out of range: ' + index );
  6840. }
  6841. return this;
  6842. },
  6843. getComponent: function ( index ) {
  6844. switch ( index ) {
  6845. case 0: return this.x;
  6846. case 1: return this.y;
  6847. case 2: return this.z;
  6848. case 3: return this.w;
  6849. default: throw new Error( 'index is out of range: ' + index );
  6850. }
  6851. },
  6852. clone: function () {
  6853. return new this.constructor( this.x, this.y, this.z, this.w );
  6854. },
  6855. copy: function ( v ) {
  6856. this.x = v.x;
  6857. this.y = v.y;
  6858. this.z = v.z;
  6859. this.w = ( v.w !== undefined ) ? v.w : 1;
  6860. return this;
  6861. },
  6862. add: function ( v, w ) {
  6863. if ( w !== undefined ) {
  6864. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  6865. return this.addVectors( v, w );
  6866. }
  6867. this.x += v.x;
  6868. this.y += v.y;
  6869. this.z += v.z;
  6870. this.w += v.w;
  6871. return this;
  6872. },
  6873. addScalar: function ( s ) {
  6874. this.x += s;
  6875. this.y += s;
  6876. this.z += s;
  6877. this.w += s;
  6878. return this;
  6879. },
  6880. addVectors: function ( a, b ) {
  6881. this.x = a.x + b.x;
  6882. this.y = a.y + b.y;
  6883. this.z = a.z + b.z;
  6884. this.w = a.w + b.w;
  6885. return this;
  6886. },
  6887. addScaledVector: function ( v, s ) {
  6888. this.x += v.x * s;
  6889. this.y += v.y * s;
  6890. this.z += v.z * s;
  6891. this.w += v.w * s;
  6892. return this;
  6893. },
  6894. sub: function ( v, w ) {
  6895. if ( w !== undefined ) {
  6896. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  6897. return this.subVectors( v, w );
  6898. }
  6899. this.x -= v.x;
  6900. this.y -= v.y;
  6901. this.z -= v.z;
  6902. this.w -= v.w;
  6903. return this;
  6904. },
  6905. subScalar: function ( s ) {
  6906. this.x -= s;
  6907. this.y -= s;
  6908. this.z -= s;
  6909. this.w -= s;
  6910. return this;
  6911. },
  6912. subVectors: function ( a, b ) {
  6913. this.x = a.x - b.x;
  6914. this.y = a.y - b.y;
  6915. this.z = a.z - b.z;
  6916. this.w = a.w - b.w;
  6917. return this;
  6918. },
  6919. multiplyScalar: function ( scalar ) {
  6920. this.x *= scalar;
  6921. this.y *= scalar;
  6922. this.z *= scalar;
  6923. this.w *= scalar;
  6924. return this;
  6925. },
  6926. applyMatrix4: function ( m ) {
  6927. var x = this.x, y = this.y, z = this.z, w = this.w;
  6928. var e = m.elements;
  6929. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  6930. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  6931. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  6932. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  6933. return this;
  6934. },
  6935. divideScalar: function ( scalar ) {
  6936. return this.multiplyScalar( 1 / scalar );
  6937. },
  6938. setAxisAngleFromQuaternion: function ( q ) {
  6939. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  6940. // q is assumed to be normalized
  6941. this.w = 2 * Math.acos( q.w );
  6942. var s = Math.sqrt( 1 - q.w * q.w );
  6943. if ( s < 0.0001 ) {
  6944. this.x = 1;
  6945. this.y = 0;
  6946. this.z = 0;
  6947. } else {
  6948. this.x = q.x / s;
  6949. this.y = q.y / s;
  6950. this.z = q.z / s;
  6951. }
  6952. return this;
  6953. },
  6954. setAxisAngleFromRotationMatrix: function ( m ) {
  6955. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  6956. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  6957. var angle, x, y, z, // variables for result
  6958. epsilon = 0.01, // margin to allow for rounding errors
  6959. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  6960. te = m.elements,
  6961. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  6962. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  6963. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  6964. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  6965. ( Math.abs( m13 - m31 ) < epsilon ) &&
  6966. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  6967. // singularity found
  6968. // first check for identity matrix which must have +1 for all terms
  6969. // in leading diagonal and zero in other terms
  6970. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  6971. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  6972. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  6973. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  6974. // this singularity is identity matrix so angle = 0
  6975. this.set( 1, 0, 0, 0 );
  6976. return this; // zero angle, arbitrary axis
  6977. }
  6978. // otherwise this singularity is angle = 180
  6979. angle = Math.PI;
  6980. var xx = ( m11 + 1 ) / 2;
  6981. var yy = ( m22 + 1 ) / 2;
  6982. var zz = ( m33 + 1 ) / 2;
  6983. var xy = ( m12 + m21 ) / 4;
  6984. var xz = ( m13 + m31 ) / 4;
  6985. var yz = ( m23 + m32 ) / 4;
  6986. if ( ( xx > yy ) && ( xx > zz ) ) {
  6987. // m11 is the largest diagonal term
  6988. if ( xx < epsilon ) {
  6989. x = 0;
  6990. y = 0.707106781;
  6991. z = 0.707106781;
  6992. } else {
  6993. x = Math.sqrt( xx );
  6994. y = xy / x;
  6995. z = xz / x;
  6996. }
  6997. } else if ( yy > zz ) {
  6998. // m22 is the largest diagonal term
  6999. if ( yy < epsilon ) {
  7000. x = 0.707106781;
  7001. y = 0;
  7002. z = 0.707106781;
  7003. } else {
  7004. y = Math.sqrt( yy );
  7005. x = xy / y;
  7006. z = yz / y;
  7007. }
  7008. } else {
  7009. // m33 is the largest diagonal term so base result on this
  7010. if ( zz < epsilon ) {
  7011. x = 0.707106781;
  7012. y = 0.707106781;
  7013. z = 0;
  7014. } else {
  7015. z = Math.sqrt( zz );
  7016. x = xz / z;
  7017. y = yz / z;
  7018. }
  7019. }
  7020. this.set( x, y, z, angle );
  7021. return this; // return 180 deg rotation
  7022. }
  7023. // as we have reached here there are no singularities so we can handle normally
  7024. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  7025. ( m13 - m31 ) * ( m13 - m31 ) +
  7026. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  7027. if ( Math.abs( s ) < 0.001 ) s = 1;
  7028. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  7029. // caught by singularity test above, but I've left it in just in case
  7030. this.x = ( m32 - m23 ) / s;
  7031. this.y = ( m13 - m31 ) / s;
  7032. this.z = ( m21 - m12 ) / s;
  7033. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  7034. return this;
  7035. },
  7036. min: function ( v ) {
  7037. this.x = Math.min( this.x, v.x );
  7038. this.y = Math.min( this.y, v.y );
  7039. this.z = Math.min( this.z, v.z );
  7040. this.w = Math.min( this.w, v.w );
  7041. return this;
  7042. },
  7043. max: function ( v ) {
  7044. this.x = Math.max( this.x, v.x );
  7045. this.y = Math.max( this.y, v.y );
  7046. this.z = Math.max( this.z, v.z );
  7047. this.w = Math.max( this.w, v.w );
  7048. return this;
  7049. },
  7050. clamp: function ( min, max ) {
  7051. // assumes min < max, componentwise
  7052. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  7053. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  7054. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  7055. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  7056. return this;
  7057. },
  7058. clampScalar: function () {
  7059. var min, max;
  7060. return function clampScalar( minVal, maxVal ) {
  7061. if ( min === undefined ) {
  7062. min = new Vector4();
  7063. max = new Vector4();
  7064. }
  7065. min.set( minVal, minVal, minVal, minVal );
  7066. max.set( maxVal, maxVal, maxVal, maxVal );
  7067. return this.clamp( min, max );
  7068. };
  7069. }(),
  7070. clampLength: function ( min, max ) {
  7071. var length = this.length();
  7072. return this.divideScalar( length || 1 ).multiplyScalar( Math.max( min, Math.min( max, length ) ) );
  7073. },
  7074. floor: function () {
  7075. this.x = Math.floor( this.x );
  7076. this.y = Math.floor( this.y );
  7077. this.z = Math.floor( this.z );
  7078. this.w = Math.floor( this.w );
  7079. return this;
  7080. },
  7081. ceil: function () {
  7082. this.x = Math.ceil( this.x );
  7083. this.y = Math.ceil( this.y );
  7084. this.z = Math.ceil( this.z );
  7085. this.w = Math.ceil( this.w );
  7086. return this;
  7087. },
  7088. round: function () {
  7089. this.x = Math.round( this.x );
  7090. this.y = Math.round( this.y );
  7091. this.z = Math.round( this.z );
  7092. this.w = Math.round( this.w );
  7093. return this;
  7094. },
  7095. roundToZero: function () {
  7096. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  7097. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  7098. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  7099. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  7100. return this;
  7101. },
  7102. negate: function () {
  7103. this.x = - this.x;
  7104. this.y = - this.y;
  7105. this.z = - this.z;
  7106. this.w = - this.w;
  7107. return this;
  7108. },
  7109. dot: function ( v ) {
  7110. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  7111. },
  7112. lengthSq: function () {
  7113. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  7114. },
  7115. length: function () {
  7116. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  7117. },
  7118. manhattanLength: function () {
  7119. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  7120. },
  7121. normalize: function () {
  7122. return this.divideScalar( this.length() || 1 );
  7123. },
  7124. setLength: function ( length ) {
  7125. return this.normalize().multiplyScalar( length );
  7126. },
  7127. lerp: function ( v, alpha ) {
  7128. this.x += ( v.x - this.x ) * alpha;
  7129. this.y += ( v.y - this.y ) * alpha;
  7130. this.z += ( v.z - this.z ) * alpha;
  7131. this.w += ( v.w - this.w ) * alpha;
  7132. return this;
  7133. },
  7134. lerpVectors: function ( v1, v2, alpha ) {
  7135. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  7136. },
  7137. equals: function ( v ) {
  7138. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  7139. },
  7140. fromArray: function ( array, offset ) {
  7141. if ( offset === undefined ) offset = 0;
  7142. this.x = array[ offset ];
  7143. this.y = array[ offset + 1 ];
  7144. this.z = array[ offset + 2 ];
  7145. this.w = array[ offset + 3 ];
  7146. return this;
  7147. },
  7148. toArray: function ( array, offset ) {
  7149. if ( array === undefined ) array = [];
  7150. if ( offset === undefined ) offset = 0;
  7151. array[ offset ] = this.x;
  7152. array[ offset + 1 ] = this.y;
  7153. array[ offset + 2 ] = this.z;
  7154. array[ offset + 3 ] = this.w;
  7155. return array;
  7156. },
  7157. fromBufferAttribute: function ( attribute, index, offset ) {
  7158. if ( offset !== undefined ) {
  7159. console.warn( 'THREE.Vector4: offset has been removed from .fromBufferAttribute().' );
  7160. }
  7161. this.x = attribute.getX( index );
  7162. this.y = attribute.getY( index );
  7163. this.z = attribute.getZ( index );
  7164. this.w = attribute.getW( index );
  7165. return this;
  7166. }
  7167. } );
  7168. /**
  7169. * @author szimek / https://github.com/szimek/
  7170. * @author alteredq / http://alteredqualia.com/
  7171. * @author Marius Kintel / https://github.com/kintel
  7172. */
  7173. /*
  7174. In options, we can specify:
  7175. * Texture parameters for an auto-generated target texture
  7176. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  7177. */
  7178. function WebGLRenderTarget( width, height, options ) {
  7179. this.uuid = _Math.generateUUID();
  7180. this.width = width;
  7181. this.height = height;
  7182. this.scissor = new Vector4( 0, 0, width, height );
  7183. this.scissorTest = false;
  7184. this.viewport = new Vector4( 0, 0, width, height );
  7185. options = options || {};
  7186. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  7187. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  7188. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  7189. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  7190. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  7191. }
  7192. WebGLRenderTarget.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  7193. constructor: WebGLRenderTarget,
  7194. isWebGLRenderTarget: true,
  7195. setSize: function ( width, height ) {
  7196. if ( this.width !== width || this.height !== height ) {
  7197. this.width = width;
  7198. this.height = height;
  7199. this.dispose();
  7200. }
  7201. this.viewport.set( 0, 0, width, height );
  7202. this.scissor.set( 0, 0, width, height );
  7203. },
  7204. clone: function () {
  7205. return new this.constructor().copy( this );
  7206. },
  7207. copy: function ( source ) {
  7208. this.width = source.width;
  7209. this.height = source.height;
  7210. this.viewport.copy( source.viewport );
  7211. this.texture = source.texture.clone();
  7212. this.depthBuffer = source.depthBuffer;
  7213. this.stencilBuffer = source.stencilBuffer;
  7214. this.depthTexture = source.depthTexture;
  7215. return this;
  7216. },
  7217. dispose: function () {
  7218. this.dispatchEvent( { type: 'dispose' } );
  7219. }
  7220. } );
  7221. /**
  7222. * @author alteredq / http://alteredqualia.com
  7223. */
  7224. function WebGLRenderTargetCube( width, height, options ) {
  7225. WebGLRenderTarget.call( this, width, height, options );
  7226. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  7227. this.activeMipMapLevel = 0;
  7228. }
  7229. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  7230. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  7231. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  7232. /**
  7233. * @author alteredq / http://alteredqualia.com/
  7234. */
  7235. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7236. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7237. this.image = { data: data, width: width, height: height };
  7238. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7239. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7240. this.generateMipmaps = false;
  7241. this.flipY = false;
  7242. this.unpackAlignment = 1;
  7243. }
  7244. DataTexture.prototype = Object.create( Texture.prototype );
  7245. DataTexture.prototype.constructor = DataTexture;
  7246. DataTexture.prototype.isDataTexture = true;
  7247. /**
  7248. * @author mrdoob / http://mrdoob.com/
  7249. */
  7250. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  7251. images = images !== undefined ? images : [];
  7252. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  7253. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7254. this.flipY = false;
  7255. }
  7256. CubeTexture.prototype = Object.create( Texture.prototype );
  7257. CubeTexture.prototype.constructor = CubeTexture;
  7258. CubeTexture.prototype.isCubeTexture = true;
  7259. Object.defineProperty( CubeTexture.prototype, 'images', {
  7260. get: function () {
  7261. return this.image;
  7262. },
  7263. set: function ( value ) {
  7264. this.image = value;
  7265. }
  7266. } );
  7267. /**
  7268. * @author tschw
  7269. *
  7270. * Uniforms of a program.
  7271. * Those form a tree structure with a special top-level container for the root,
  7272. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  7273. *
  7274. *
  7275. * Properties of inner nodes including the top-level container:
  7276. *
  7277. * .seq - array of nested uniforms
  7278. * .map - nested uniforms by name
  7279. *
  7280. *
  7281. * Methods of all nodes except the top-level container:
  7282. *
  7283. * .setValue( gl, value, [renderer] )
  7284. *
  7285. * uploads a uniform value(s)
  7286. * the 'renderer' parameter is needed for sampler uniforms
  7287. *
  7288. *
  7289. * Static methods of the top-level container (renderer factorizations):
  7290. *
  7291. * .upload( gl, seq, values, renderer )
  7292. *
  7293. * sets uniforms in 'seq' to 'values[id].value'
  7294. *
  7295. * .seqWithValue( seq, values ) : filteredSeq
  7296. *
  7297. * filters 'seq' entries with corresponding entry in values
  7298. *
  7299. *
  7300. * Methods of the top-level container (renderer factorizations):
  7301. *
  7302. * .setValue( gl, name, value )
  7303. *
  7304. * sets uniform with name 'name' to 'value'
  7305. *
  7306. * .set( gl, obj, prop )
  7307. *
  7308. * sets uniform from object and property with same name than uniform
  7309. *
  7310. * .setOptional( gl, obj, prop )
  7311. *
  7312. * like .set for an optional property of the object
  7313. *
  7314. */
  7315. var emptyTexture = new Texture();
  7316. var emptyCubeTexture = new CubeTexture();
  7317. // --- Base for inner nodes (including the root) ---
  7318. function UniformContainer() {
  7319. this.seq = [];
  7320. this.map = {};
  7321. }
  7322. // --- Utilities ---
  7323. // Array Caches (provide typed arrays for temporary by size)
  7324. var arrayCacheF32 = [];
  7325. var arrayCacheI32 = [];
  7326. // Float32Array caches used for uploading Matrix uniforms
  7327. var mat4array = new Float32Array( 16 );
  7328. var mat3array = new Float32Array( 9 );
  7329. // Flattening for arrays of vectors and matrices
  7330. function flatten( array, nBlocks, blockSize ) {
  7331. var firstElem = array[ 0 ];
  7332. if ( firstElem <= 0 || firstElem > 0 ) return array;
  7333. // unoptimized: ! isNaN( firstElem )
  7334. // see http://jacksondunstan.com/articles/983
  7335. var n = nBlocks * blockSize,
  7336. r = arrayCacheF32[ n ];
  7337. if ( r === undefined ) {
  7338. r = new Float32Array( n );
  7339. arrayCacheF32[ n ] = r;
  7340. }
  7341. if ( nBlocks !== 0 ) {
  7342. firstElem.toArray( r, 0 );
  7343. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  7344. offset += blockSize;
  7345. array[ i ].toArray( r, offset );
  7346. }
  7347. }
  7348. return r;
  7349. }
  7350. // Texture unit allocation
  7351. function allocTexUnits( renderer, n ) {
  7352. var r = arrayCacheI32[ n ];
  7353. if ( r === undefined ) {
  7354. r = new Int32Array( n );
  7355. arrayCacheI32[ n ] = r;
  7356. }
  7357. for ( var i = 0; i !== n; ++ i )
  7358. r[ i ] = renderer.allocTextureUnit();
  7359. return r;
  7360. }
  7361. // --- Setters ---
  7362. // Note: Defining these methods externally, because they come in a bunch
  7363. // and this way their names minify.
  7364. // Single scalar
  7365. function setValue1f( gl, v ) {
  7366. gl.uniform1f( this.addr, v );
  7367. }
  7368. function setValue1i( gl, v ) {
  7369. gl.uniform1i( this.addr, v );
  7370. }
  7371. // Single float vector (from flat array or THREE.VectorN)
  7372. function setValue2fv( gl, v ) {
  7373. if ( v.x === undefined ) {
  7374. gl.uniform2fv( this.addr, v );
  7375. } else {
  7376. gl.uniform2f( this.addr, v.x, v.y );
  7377. }
  7378. }
  7379. function setValue3fv( gl, v ) {
  7380. if ( v.x !== undefined ) {
  7381. gl.uniform3f( this.addr, v.x, v.y, v.z );
  7382. } else if ( v.r !== undefined ) {
  7383. gl.uniform3f( this.addr, v.r, v.g, v.b );
  7384. } else {
  7385. gl.uniform3fv( this.addr, v );
  7386. }
  7387. }
  7388. function setValue4fv( gl, v ) {
  7389. if ( v.x === undefined ) {
  7390. gl.uniform4fv( this.addr, v );
  7391. } else {
  7392. gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  7393. }
  7394. }
  7395. // Single matrix (from flat array or MatrixN)
  7396. function setValue2fm( gl, v ) {
  7397. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  7398. }
  7399. function setValue3fm( gl, v ) {
  7400. if ( v.elements === undefined ) {
  7401. gl.uniformMatrix3fv( this.addr, false, v );
  7402. } else {
  7403. mat3array.set( v.elements );
  7404. gl.uniformMatrix3fv( this.addr, false, mat3array );
  7405. }
  7406. }
  7407. function setValue4fm( gl, v ) {
  7408. if ( v.elements === undefined ) {
  7409. gl.uniformMatrix4fv( this.addr, false, v );
  7410. } else {
  7411. mat4array.set( v.elements );
  7412. gl.uniformMatrix4fv( this.addr, false, mat4array );
  7413. }
  7414. }
  7415. // Single texture (2D / Cube)
  7416. function setValueT1( gl, v, renderer ) {
  7417. var unit = renderer.allocTextureUnit();
  7418. gl.uniform1i( this.addr, unit );
  7419. renderer.setTexture2D( v || emptyTexture, unit );
  7420. }
  7421. function setValueT6( gl, v, renderer ) {
  7422. var unit = renderer.allocTextureUnit();
  7423. gl.uniform1i( this.addr, unit );
  7424. renderer.setTextureCube( v || emptyCubeTexture, unit );
  7425. }
  7426. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  7427. function setValue2iv( gl, v ) {
  7428. gl.uniform2iv( this.addr, v );
  7429. }
  7430. function setValue3iv( gl, v ) {
  7431. gl.uniform3iv( this.addr, v );
  7432. }
  7433. function setValue4iv( gl, v ) {
  7434. gl.uniform4iv( this.addr, v );
  7435. }
  7436. // Helper to pick the right setter for the singular case
  7437. function getSingularSetter( type ) {
  7438. switch ( type ) {
  7439. case 0x1406: return setValue1f; // FLOAT
  7440. case 0x8b50: return setValue2fv; // _VEC2
  7441. case 0x8b51: return setValue3fv; // _VEC3
  7442. case 0x8b52: return setValue4fv; // _VEC4
  7443. case 0x8b5a: return setValue2fm; // _MAT2
  7444. case 0x8b5b: return setValue3fm; // _MAT3
  7445. case 0x8b5c: return setValue4fm; // _MAT4
  7446. case 0x8b5e: case 0x8d66: return setValueT1; // SAMPLER_2D, SAMPLER_EXTERNAL_OES
  7447. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  7448. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  7449. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7450. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7451. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7452. }
  7453. }
  7454. // Array of scalars
  7455. function setValue1fv( gl, v ) {
  7456. gl.uniform1fv( this.addr, v );
  7457. }
  7458. function setValue1iv( gl, v ) {
  7459. gl.uniform1iv( this.addr, v );
  7460. }
  7461. // Array of vectors (flat or from THREE classes)
  7462. function setValueV2a( gl, v ) {
  7463. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  7464. }
  7465. function setValueV3a( gl, v ) {
  7466. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  7467. }
  7468. function setValueV4a( gl, v ) {
  7469. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  7470. }
  7471. // Array of matrices (flat or from THREE clases)
  7472. function setValueM2a( gl, v ) {
  7473. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  7474. }
  7475. function setValueM3a( gl, v ) {
  7476. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  7477. }
  7478. function setValueM4a( gl, v ) {
  7479. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  7480. }
  7481. // Array of textures (2D / Cube)
  7482. function setValueT1a( gl, v, renderer ) {
  7483. var n = v.length,
  7484. units = allocTexUnits( renderer, n );
  7485. gl.uniform1iv( this.addr, units );
  7486. for ( var i = 0; i !== n; ++ i ) {
  7487. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  7488. }
  7489. }
  7490. function setValueT6a( gl, v, renderer ) {
  7491. var n = v.length,
  7492. units = allocTexUnits( renderer, n );
  7493. gl.uniform1iv( this.addr, units );
  7494. for ( var i = 0; i !== n; ++ i ) {
  7495. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  7496. }
  7497. }
  7498. // Helper to pick the right setter for a pure (bottom-level) array
  7499. function getPureArraySetter( type ) {
  7500. switch ( type ) {
  7501. case 0x1406: return setValue1fv; // FLOAT
  7502. case 0x8b50: return setValueV2a; // _VEC2
  7503. case 0x8b51: return setValueV3a; // _VEC3
  7504. case 0x8b52: return setValueV4a; // _VEC4
  7505. case 0x8b5a: return setValueM2a; // _MAT2
  7506. case 0x8b5b: return setValueM3a; // _MAT3
  7507. case 0x8b5c: return setValueM4a; // _MAT4
  7508. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  7509. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  7510. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  7511. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7512. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7513. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7514. }
  7515. }
  7516. // --- Uniform Classes ---
  7517. function SingleUniform( id, activeInfo, addr ) {
  7518. this.id = id;
  7519. this.addr = addr;
  7520. this.setValue = getSingularSetter( activeInfo.type );
  7521. // this.path = activeInfo.name; // DEBUG
  7522. }
  7523. function PureArrayUniform( id, activeInfo, addr ) {
  7524. this.id = id;
  7525. this.addr = addr;
  7526. this.size = activeInfo.size;
  7527. this.setValue = getPureArraySetter( activeInfo.type );
  7528. // this.path = activeInfo.name; // DEBUG
  7529. }
  7530. function StructuredUniform( id ) {
  7531. this.id = id;
  7532. UniformContainer.call( this ); // mix-in
  7533. }
  7534. StructuredUniform.prototype.setValue = function ( gl, value ) {
  7535. // Note: Don't need an extra 'renderer' parameter, since samplers
  7536. // are not allowed in structured uniforms.
  7537. var seq = this.seq;
  7538. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7539. var u = seq[ i ];
  7540. u.setValue( gl, value[ u.id ] );
  7541. }
  7542. };
  7543. // --- Top-level ---
  7544. // Parser - builds up the property tree from the path strings
  7545. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  7546. // extracts
  7547. // - the identifier (member name or array index)
  7548. // - followed by an optional right bracket (found when array index)
  7549. // - followed by an optional left bracket or dot (type of subscript)
  7550. //
  7551. // Note: These portions can be read in a non-overlapping fashion and
  7552. // allow straightforward parsing of the hierarchy that WebGL encodes
  7553. // in the uniform names.
  7554. function addUniform( container, uniformObject ) {
  7555. container.seq.push( uniformObject );
  7556. container.map[ uniformObject.id ] = uniformObject;
  7557. }
  7558. function parseUniform( activeInfo, addr, container ) {
  7559. var path = activeInfo.name,
  7560. pathLength = path.length;
  7561. // reset RegExp object, because of the early exit of a previous run
  7562. RePathPart.lastIndex = 0;
  7563. for ( ; ; ) {
  7564. var match = RePathPart.exec( path ),
  7565. matchEnd = RePathPart.lastIndex,
  7566. id = match[ 1 ],
  7567. idIsIndex = match[ 2 ] === ']',
  7568. subscript = match[ 3 ];
  7569. if ( idIsIndex ) id = id | 0; // convert to integer
  7570. if ( subscript === undefined || subscript === '[' && matchEnd + 2 === pathLength ) {
  7571. // bare name or "pure" bottom-level array "[0]" suffix
  7572. addUniform( container, subscript === undefined ?
  7573. new SingleUniform( id, activeInfo, addr ) :
  7574. new PureArrayUniform( id, activeInfo, addr ) );
  7575. break;
  7576. } else {
  7577. // step into inner node / create it in case it doesn't exist
  7578. var map = container.map, next = map[ id ];
  7579. if ( next === undefined ) {
  7580. next = new StructuredUniform( id );
  7581. addUniform( container, next );
  7582. }
  7583. container = next;
  7584. }
  7585. }
  7586. }
  7587. // Root Container
  7588. function WebGLUniforms( gl, program, renderer ) {
  7589. UniformContainer.call( this );
  7590. this.renderer = renderer;
  7591. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  7592. for ( var i = 0; i < n; ++ i ) {
  7593. var info = gl.getActiveUniform( program, i ),
  7594. path = info.name,
  7595. addr = gl.getUniformLocation( program, path );
  7596. parseUniform( info, addr, this );
  7597. }
  7598. }
  7599. WebGLUniforms.prototype.setValue = function ( gl, name, value ) {
  7600. var u = this.map[ name ];
  7601. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  7602. };
  7603. WebGLUniforms.prototype.setOptional = function ( gl, object, name ) {
  7604. var v = object[ name ];
  7605. if ( v !== undefined ) this.setValue( gl, name, v );
  7606. };
  7607. // Static interface
  7608. WebGLUniforms.upload = function ( gl, seq, values, renderer ) {
  7609. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7610. var u = seq[ i ],
  7611. v = values[ u.id ];
  7612. if ( v.needsUpdate !== false ) {
  7613. // note: always updating when .needsUpdate is undefined
  7614. u.setValue( gl, v.value, renderer );
  7615. }
  7616. }
  7617. };
  7618. WebGLUniforms.seqWithValue = function ( seq, values ) {
  7619. var r = [];
  7620. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7621. var u = seq[ i ];
  7622. if ( u.id in values ) r.push( u );
  7623. }
  7624. return r;
  7625. };
  7626. /**
  7627. * @author mrdoob / http://mrdoob.com/
  7628. */
  7629. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7630. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7631. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7632. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7633. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7634. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7635. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7636. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7637. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7638. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7639. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7640. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7641. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7642. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7643. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7644. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7645. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7646. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7647. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7648. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'rebeccapurple': 0x663399, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7649. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7650. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7651. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7652. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7653. function Color( r, g, b ) {
  7654. if ( g === undefined && b === undefined ) {
  7655. // r is THREE.Color, hex or string
  7656. return this.set( r );
  7657. }
  7658. return this.setRGB( r, g, b );
  7659. }
  7660. Object.assign( Color.prototype, {
  7661. isColor: true,
  7662. r: 1, g: 1, b: 1,
  7663. set: function ( value ) {
  7664. if ( value && value.isColor ) {
  7665. this.copy( value );
  7666. } else if ( typeof value === 'number' ) {
  7667. this.setHex( value );
  7668. } else if ( typeof value === 'string' ) {
  7669. this.setStyle( value );
  7670. }
  7671. return this;
  7672. },
  7673. setScalar: function ( scalar ) {
  7674. this.r = scalar;
  7675. this.g = scalar;
  7676. this.b = scalar;
  7677. return this;
  7678. },
  7679. setHex: function ( hex ) {
  7680. hex = Math.floor( hex );
  7681. this.r = ( hex >> 16 & 255 ) / 255;
  7682. this.g = ( hex >> 8 & 255 ) / 255;
  7683. this.b = ( hex & 255 ) / 255;
  7684. return this;
  7685. },
  7686. setRGB: function ( r, g, b ) {
  7687. this.r = r;
  7688. this.g = g;
  7689. this.b = b;
  7690. return this;
  7691. },
  7692. setHSL: function () {
  7693. function hue2rgb( p, q, t ) {
  7694. if ( t < 0 ) t += 1;
  7695. if ( t > 1 ) t -= 1;
  7696. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7697. if ( t < 1 / 2 ) return q;
  7698. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7699. return p;
  7700. }
  7701. return function setHSL( h, s, l ) {
  7702. // h,s,l ranges are in 0.0 - 1.0
  7703. h = _Math.euclideanModulo( h, 1 );
  7704. s = _Math.clamp( s, 0, 1 );
  7705. l = _Math.clamp( l, 0, 1 );
  7706. if ( s === 0 ) {
  7707. this.r = this.g = this.b = l;
  7708. } else {
  7709. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7710. var q = ( 2 * l ) - p;
  7711. this.r = hue2rgb( q, p, h + 1 / 3 );
  7712. this.g = hue2rgb( q, p, h );
  7713. this.b = hue2rgb( q, p, h - 1 / 3 );
  7714. }
  7715. return this;
  7716. };
  7717. }(),
  7718. setStyle: function ( style ) {
  7719. function handleAlpha( string ) {
  7720. if ( string === undefined ) return;
  7721. if ( parseFloat( string ) < 1 ) {
  7722. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7723. }
  7724. }
  7725. var m;
  7726. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7727. // rgb / hsl
  7728. var color;
  7729. var name = m[ 1 ];
  7730. var components = m[ 2 ];
  7731. switch ( name ) {
  7732. case 'rgb':
  7733. case 'rgba':
  7734. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7735. // rgb(255,0,0) rgba(255,0,0,0.5)
  7736. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7737. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7738. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7739. handleAlpha( color[ 5 ] );
  7740. return this;
  7741. }
  7742. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7743. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7744. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7745. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7746. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7747. handleAlpha( color[ 5 ] );
  7748. return this;
  7749. }
  7750. break;
  7751. case 'hsl':
  7752. case 'hsla':
  7753. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7754. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7755. var h = parseFloat( color[ 1 ] ) / 360;
  7756. var s = parseInt( color[ 2 ], 10 ) / 100;
  7757. var l = parseInt( color[ 3 ], 10 ) / 100;
  7758. handleAlpha( color[ 5 ] );
  7759. return this.setHSL( h, s, l );
  7760. }
  7761. break;
  7762. }
  7763. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7764. // hex color
  7765. var hex = m[ 1 ];
  7766. var size = hex.length;
  7767. if ( size === 3 ) {
  7768. // #ff0
  7769. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7770. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7771. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7772. return this;
  7773. } else if ( size === 6 ) {
  7774. // #ff0000
  7775. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7776. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7777. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7778. return this;
  7779. }
  7780. }
  7781. if ( style && style.length > 0 ) {
  7782. // color keywords
  7783. var hex = ColorKeywords[ style ];
  7784. if ( hex !== undefined ) {
  7785. // red
  7786. this.setHex( hex );
  7787. } else {
  7788. // unknown color
  7789. console.warn( 'THREE.Color: Unknown color ' + style );
  7790. }
  7791. }
  7792. return this;
  7793. },
  7794. clone: function () {
  7795. return new this.constructor( this.r, this.g, this.b );
  7796. },
  7797. copy: function ( color ) {
  7798. this.r = color.r;
  7799. this.g = color.g;
  7800. this.b = color.b;
  7801. return this;
  7802. },
  7803. copyGammaToLinear: function ( color, gammaFactor ) {
  7804. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7805. this.r = Math.pow( color.r, gammaFactor );
  7806. this.g = Math.pow( color.g, gammaFactor );
  7807. this.b = Math.pow( color.b, gammaFactor );
  7808. return this;
  7809. },
  7810. copyLinearToGamma: function ( color, gammaFactor ) {
  7811. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7812. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7813. this.r = Math.pow( color.r, safeInverse );
  7814. this.g = Math.pow( color.g, safeInverse );
  7815. this.b = Math.pow( color.b, safeInverse );
  7816. return this;
  7817. },
  7818. convertGammaToLinear: function () {
  7819. var r = this.r, g = this.g, b = this.b;
  7820. this.r = r * r;
  7821. this.g = g * g;
  7822. this.b = b * b;
  7823. return this;
  7824. },
  7825. convertLinearToGamma: function () {
  7826. this.r = Math.sqrt( this.r );
  7827. this.g = Math.sqrt( this.g );
  7828. this.b = Math.sqrt( this.b );
  7829. return this;
  7830. },
  7831. getHex: function () {
  7832. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7833. },
  7834. getHexString: function () {
  7835. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7836. },
  7837. getHSL: function ( optionalTarget ) {
  7838. // h,s,l ranges are in 0.0 - 1.0
  7839. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  7840. var r = this.r, g = this.g, b = this.b;
  7841. var max = Math.max( r, g, b );
  7842. var min = Math.min( r, g, b );
  7843. var hue, saturation;
  7844. var lightness = ( min + max ) / 2.0;
  7845. if ( min === max ) {
  7846. hue = 0;
  7847. saturation = 0;
  7848. } else {
  7849. var delta = max - min;
  7850. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  7851. switch ( max ) {
  7852. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  7853. case g: hue = ( b - r ) / delta + 2; break;
  7854. case b: hue = ( r - g ) / delta + 4; break;
  7855. }
  7856. hue /= 6;
  7857. }
  7858. hsl.h = hue;
  7859. hsl.s = saturation;
  7860. hsl.l = lightness;
  7861. return hsl;
  7862. },
  7863. getStyle: function () {
  7864. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  7865. },
  7866. offsetHSL: function ( h, s, l ) {
  7867. var hsl = this.getHSL();
  7868. hsl.h += h; hsl.s += s; hsl.l += l;
  7869. this.setHSL( hsl.h, hsl.s, hsl.l );
  7870. return this;
  7871. },
  7872. add: function ( color ) {
  7873. this.r += color.r;
  7874. this.g += color.g;
  7875. this.b += color.b;
  7876. return this;
  7877. },
  7878. addColors: function ( color1, color2 ) {
  7879. this.r = color1.r + color2.r;
  7880. this.g = color1.g + color2.g;
  7881. this.b = color1.b + color2.b;
  7882. return this;
  7883. },
  7884. addScalar: function ( s ) {
  7885. this.r += s;
  7886. this.g += s;
  7887. this.b += s;
  7888. return this;
  7889. },
  7890. sub: function ( color ) {
  7891. this.r = Math.max( 0, this.r - color.r );
  7892. this.g = Math.max( 0, this.g - color.g );
  7893. this.b = Math.max( 0, this.b - color.b );
  7894. return this;
  7895. },
  7896. multiply: function ( color ) {
  7897. this.r *= color.r;
  7898. this.g *= color.g;
  7899. this.b *= color.b;
  7900. return this;
  7901. },
  7902. multiplyScalar: function ( s ) {
  7903. this.r *= s;
  7904. this.g *= s;
  7905. this.b *= s;
  7906. return this;
  7907. },
  7908. lerp: function ( color, alpha ) {
  7909. this.r += ( color.r - this.r ) * alpha;
  7910. this.g += ( color.g - this.g ) * alpha;
  7911. this.b += ( color.b - this.b ) * alpha;
  7912. return this;
  7913. },
  7914. equals: function ( c ) {
  7915. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  7916. },
  7917. fromArray: function ( array, offset ) {
  7918. if ( offset === undefined ) offset = 0;
  7919. this.r = array[ offset ];
  7920. this.g = array[ offset + 1 ];
  7921. this.b = array[ offset + 2 ];
  7922. return this;
  7923. },
  7924. toArray: function ( array, offset ) {
  7925. if ( array === undefined ) array = [];
  7926. if ( offset === undefined ) offset = 0;
  7927. array[ offset ] = this.r;
  7928. array[ offset + 1 ] = this.g;
  7929. array[ offset + 2 ] = this.b;
  7930. return array;
  7931. },
  7932. toJSON: function () {
  7933. return this.getHex();
  7934. }
  7935. } );
  7936. /**
  7937. * Uniforms library for shared webgl shaders
  7938. */
  7939. var UniformsLib = {
  7940. common: {
  7941. diffuse: { value: new Color( 0xeeeeee ) },
  7942. opacity: { value: 1.0 },
  7943. map: { value: null },
  7944. uvTransform: { value: new Matrix3() },
  7945. alphaMap: { value: null },
  7946. },
  7947. specularmap: {
  7948. specularMap: { value: null },
  7949. },
  7950. envmap: {
  7951. envMap: { value: null },
  7952. flipEnvMap: { value: - 1 },
  7953. reflectivity: { value: 1.0 },
  7954. refractionRatio: { value: 0.98 }
  7955. },
  7956. aomap: {
  7957. aoMap: { value: null },
  7958. aoMapIntensity: { value: 1 }
  7959. },
  7960. lightmap: {
  7961. lightMap: { value: null },
  7962. lightMapIntensity: { value: 1 }
  7963. },
  7964. emissivemap: {
  7965. emissiveMap: { value: null }
  7966. },
  7967. bumpmap: {
  7968. bumpMap: { value: null },
  7969. bumpScale: { value: 1 }
  7970. },
  7971. normalmap: {
  7972. normalMap: { value: null },
  7973. normalScale: { value: new Vector2( 1, 1 ) }
  7974. },
  7975. displacementmap: {
  7976. displacementMap: { value: null },
  7977. displacementScale: { value: 1 },
  7978. displacementBias: { value: 0 }
  7979. },
  7980. roughnessmap: {
  7981. roughnessMap: { value: null }
  7982. },
  7983. metalnessmap: {
  7984. metalnessMap: { value: null }
  7985. },
  7986. gradientmap: {
  7987. gradientMap: { value: null }
  7988. },
  7989. fog: {
  7990. fogDensity: { value: 0.00025 },
  7991. fogNear: { value: 1 },
  7992. fogFar: { value: 2000 },
  7993. fogColor: { value: new Color( 0xffffff ) }
  7994. },
  7995. lights: {
  7996. ambientLightColor: { value: [] },
  7997. directionalLights: { value: [], properties: {
  7998. direction: {},
  7999. color: {},
  8000. shadow: {},
  8001. shadowBias: {},
  8002. shadowRadius: {},
  8003. shadowMapSize: {}
  8004. } },
  8005. directionalShadowMap: { value: [] },
  8006. directionalShadowMatrix: { value: [] },
  8007. spotLights: { value: [], properties: {
  8008. color: {},
  8009. position: {},
  8010. direction: {},
  8011. distance: {},
  8012. coneCos: {},
  8013. penumbraCos: {},
  8014. decay: {},
  8015. shadow: {},
  8016. shadowBias: {},
  8017. shadowRadius: {},
  8018. shadowMapSize: {}
  8019. } },
  8020. spotShadowMap: { value: [] },
  8021. spotShadowMatrix: { value: [] },
  8022. pointLights: { value: [], properties: {
  8023. color: {},
  8024. position: {},
  8025. decay: {},
  8026. distance: {},
  8027. shadow: {},
  8028. shadowBias: {},
  8029. shadowRadius: {},
  8030. shadowMapSize: {},
  8031. shadowCameraNear: {},
  8032. shadowCameraFar: {}
  8033. } },
  8034. pointShadowMap: { value: [] },
  8035. pointShadowMatrix: { value: [] },
  8036. hemisphereLights: { value: [], properties: {
  8037. direction: {},
  8038. skyColor: {},
  8039. groundColor: {}
  8040. } },
  8041. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  8042. rectAreaLights: { value: [], properties: {
  8043. color: {},
  8044. position: {},
  8045. width: {},
  8046. height: {}
  8047. } }
  8048. },
  8049. points: {
  8050. diffuse: { value: new Color( 0xeeeeee ) },
  8051. opacity: { value: 1.0 },
  8052. size: { value: 1.0 },
  8053. scale: { value: 1.0 },
  8054. map: { value: null },
  8055. uvTransform: { value: new Matrix3() }
  8056. }
  8057. };
  8058. /**
  8059. * Uniform Utilities
  8060. */
  8061. var UniformsUtils = {
  8062. merge: function ( uniforms ) {
  8063. var merged = {};
  8064. for ( var u = 0; u < uniforms.length; u ++ ) {
  8065. var tmp = this.clone( uniforms[ u ] );
  8066. for ( var p in tmp ) {
  8067. merged[ p ] = tmp[ p ];
  8068. }
  8069. }
  8070. return merged;
  8071. },
  8072. clone: function ( uniforms_src ) {
  8073. var uniforms_dst = {};
  8074. for ( var u in uniforms_src ) {
  8075. uniforms_dst[ u ] = {};
  8076. for ( var p in uniforms_src[ u ] ) {
  8077. var parameter_src = uniforms_src[ u ][ p ];
  8078. if ( parameter_src && ( parameter_src.isColor ||
  8079. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  8080. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  8081. parameter_src.isTexture ) ) {
  8082. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8083. } else if ( Array.isArray( parameter_src ) ) {
  8084. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8085. } else {
  8086. uniforms_dst[ u ][ p ] = parameter_src;
  8087. }
  8088. }
  8089. }
  8090. return uniforms_dst;
  8091. }
  8092. };
  8093. var alphamap_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\r\n\r\n#endif\r\n";
  8094. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\r\n\r\n\tuniform sampler2D alphaMap;\r\n\r\n#endif\r\n";
  8095. var alphatest_fragment = "#ifdef ALPHATEST\r\n\r\n\tif ( diffuseColor.a < ALPHATEST ) discard;\r\n\r\n#endif\r\n";
  8096. var aomap_fragment = "#ifdef USE_AOMAP\r\n\r\n\t// reads channel R, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\r\n\r\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8097. var aomap_pars_fragment = "#ifdef USE_AOMAP\r\n\r\n\tuniform sampler2D aoMap;\r\n\tuniform float aoMapIntensity;\r\n\r\n#endif";
  8098. var begin_vertex = "\r\nvec3 transformed = vec3( position );\r\n";
  8099. var beginnormal_vertex = "\r\nvec3 objectNormal = vec3( normal );\r\n";
  8100. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\r\n\r\n\tif( decayExponent > 0.0 ) {\r\n\r\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\r\n\r\n\t\t// based upon Frostbite 3 Moving to Physically-based Rendering\r\n\t\t// page 32, equation 26: E[window1]\r\n\t\t// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\n\t\t// this is intended to be used on spot and point lights who are represented as luminous intensity\r\n\t\t// but who must be converted to luminous irradiance for surface lighting calculation\r\n\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\r\n\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\r\n\t\treturn distanceFalloff * maxDistanceCutoffFactor;\r\n\r\n#else\r\n\r\n\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\r\n\r\n#endif\r\n\r\n\t}\r\n\r\n\treturn 1.0;\r\n\r\n}\r\n\r\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\r\n\r\n\treturn RECIPROCAL_PI * diffuseColor;\r\n\r\n} // validated\r\n\r\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\r\n\r\n\t// Original approximation by Christophe Schlick '94\r\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\r\n\r\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\r\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\r\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\r\n\r\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\r\n\r\n} // validated\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (34)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\t// geometry term (normalized) = G(l)⋅G(v) / 4(n⋅l)(n⋅v)\r\n\t// also see #12151\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\r\n\treturn 1.0 / ( gl * gv );\r\n\r\n} // validated\r\n\r\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\r\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\r\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\r\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\r\n\r\n\treturn 0.5 / max( gv + gl, EPSILON );\r\n\r\n}\r\n\r\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\r\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\r\n// alpha is \"roughness squared\" in Disney’s reparameterization\r\nfloat D_GGX( const in float alpha, const in float dotNH ) {\r\n\r\n\tfloat a2 = pow2( alpha );\r\n\r\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; // avoid alpha = 0 with dotNH = 1\r\n\r\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\r\n\r\n}\r\n\r\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\r\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat alpha = pow2( roughness ); // UE4's roughness\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\r\n\r\n\tfloat D = D_GGX( alpha, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n// Rect Area Light\r\n\r\n// Area light computation code adapted from:\r\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\r\n// By: Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt\r\n// https://drive.google.com/file/d/0BzvWIdpUpRx_d09ndGVjNVJzZjA/view\r\n// https://eheitzresearch.wordpress.com/415-2/\r\n// http://blog.selfshadow.com/sandbox/ltc.html\r\n\r\nvec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) {\r\n\r\n\tconst float LUT_SIZE = 64.0;\r\n\tconst float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE;\r\n\tconst float LUT_BIAS = 0.5 / LUT_SIZE;\r\n\r\n\tfloat theta = acos( dot( N, V ) );\r\n\r\n\t// Parameterization of texture:\r\n\t// sqrt(roughness) -> [0,1]\r\n\t// theta -> [0, PI/2]\r\n\tvec2 uv = vec2(\r\n\t\tsqrt( saturate( roughness ) ),\r\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\r\n\r\n\t// Ensure we don't have nonlinearities at the look-up table's edges\r\n\t// see: http://http.developer.nvidia.com/GPUGems2/gpugems2_chapter24.html\r\n\t// \"Shader Analysis\" section\r\n\tuv = uv * LUT_SCALE + LUT_BIAS;\r\n\r\n\treturn uv;\r\n\r\n}\r\n\r\n// Real-Time Area Lighting: a Journey from Research to Production\r\n// By: Stephen Hill & Eric Heitz\r\n// http://advances.realtimerendering.com/s2016/s2016_ltc_rnd.pdf\r\n// An approximation for the form factor of a clipped rectangle.\r\nfloat LTC_ClippedSphereFormFactor( const in vec3 f ) {\r\n\r\n\tfloat l = length( f );\r\n\r\n\treturn max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 );\r\n\r\n}\r\n\r\n// Real-Time Polygonal-Light Shading with Linearly Transformed Cosines\r\n// also Real-Time Area Lighting: a Journey from Research to Production\r\n// http://advances.realtimerendering.com/s2016/s2016_ltc_rnd.pdf\r\n// Normalization by 2*PI is incorporated in this function itself.\r\n// theta/sin(theta) is approximated by rational polynomial\r\nvec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) {\r\n\r\n\tfloat x = dot( v1, v2 );\r\n\r\n\tfloat y = abs( x );\r\n\tfloat a = 0.86267 + (0.49788 + 0.01436 * y ) * y;\r\n\tfloat b = 3.45068 + (4.18814 + y) * y;\r\n\tfloat v = a / b;\r\n\r\n\tfloat theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt( 1.0 - x * x ) - v;\r\n\r\n\treturn cross( v1, v2 ) * theta_sintheta;\r\n\r\n}\r\n\r\nvec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) {\r\n\r\n\t// bail if point is on back side of plane of light\r\n\t// assumes ccw winding order of light vertices\r\n\tvec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ];\r\n\tvec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ];\r\n\tvec3 lightNormal = cross( v1, v2 );\r\n\r\n\tif( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 );\r\n\r\n\t// construct orthonormal basis around N\r\n\tvec3 T1, T2;\r\n\tT1 = normalize( V - N * dot( V, N ) );\r\n\tT2 = - cross( N, T1 ); // negated from paper; possibly due to a different assumed handedness of world coordinate system\r\n\r\n\t// compute transform\r\n\tmat3 mat = mInv * transposeMat3( mat3( T1, T2, N ) );\r\n\r\n\t// transform rect\r\n\tvec3 coords[ 4 ];\r\n\tcoords[ 0 ] = mat * ( rectCoords[ 0 ] - P );\r\n\tcoords[ 1 ] = mat * ( rectCoords[ 1 ] - P );\r\n\tcoords[ 2 ] = mat * ( rectCoords[ 2 ] - P );\r\n\tcoords[ 3 ] = mat * ( rectCoords[ 3 ] - P );\r\n\r\n\t// project rect onto sphere\r\n\tcoords[ 0 ] = normalize( coords[ 0 ] );\r\n\tcoords[ 1 ] = normalize( coords[ 1 ] );\r\n\tcoords[ 2 ] = normalize( coords[ 2 ] );\r\n\tcoords[ 3 ] = normalize( coords[ 3 ] );\r\n\r\n\t// calculate vector form factor\r\n\tvec3 vectorFormFactor = vec3( 0.0 );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] );\r\n\tvectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] );\r\n\r\n\t// adjust for horizon clipping\r\n\tvec3 result = vec3( LTC_ClippedSphereFormFactor( vectorFormFactor ) );\r\n\r\n\treturn result;\r\n\r\n}\r\n\r\n// End Rect Area Light\r\n\r\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\r\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\r\n\r\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\r\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\r\n\r\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\r\n\r\n\tvec4 r = roughness * c0 + c1;\r\n\r\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\r\n\r\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\r\n\r\n\treturn specularColor * AB.x + AB.y;\r\n\r\n} // validated\r\n\r\n\r\nfloat G_BlinnPhong_Implicit( ) {\r\n\r\n\t// geometry term is (n dot l)(n dot v) / 4(n dot l)(n dot v)\r\n\treturn 0.25;\r\n\r\n}\r\n\r\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\r\n\r\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\r\n\r\n}\r\n\r\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\r\n\r\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\r\n\r\n\t//float dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\r\n\t//float dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\r\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\r\n\r\n\tvec3 F = F_Schlick( specularColor, dotLH );\r\n\r\n\tfloat G = G_BlinnPhong_Implicit( );\r\n\r\n\tfloat D = D_BlinnPhong( shininess, dotNH );\r\n\r\n\treturn F * ( G * D );\r\n\r\n} // validated\r\n\r\n// source: http://simonstechblog.blogspot.ca/2011/12/microfacet-brdf.html\r\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\r\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\r\n}\r\n\r\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\r\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\r\n}\r\n";
  8101. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\r\n\r\n\tuniform sampler2D bumpMap;\r\n\tuniform float bumpScale;\r\n\r\n\t// Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen\r\n\t// http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html\r\n\r\n\t// Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)\r\n\r\n\tvec2 dHdxy_fwd() {\r\n\r\n\t\tvec2 dSTdx = dFdx( vUv );\r\n\t\tvec2 dSTdy = dFdy( vUv );\r\n\r\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\r\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\r\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\r\n\r\n\t\treturn vec2( dBx, dBy );\r\n\r\n\t}\r\n\r\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\r\n\r\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\r\n\r\n\t\tvec3 vSigmaX = vec3( dFdx( surf_pos.x ), dFdx( surf_pos.y ), dFdx( surf_pos.z ) );\r\n\t\tvec3 vSigmaY = vec3( dFdy( surf_pos.x ), dFdy( surf_pos.y ), dFdy( surf_pos.z ) );\r\n\t\tvec3 vN = surf_norm;\t\t// normalized\r\n\r\n\t\tvec3 R1 = cross( vSigmaY, vN );\r\n\t\tvec3 R2 = cross( vN, vSigmaX );\r\n\r\n\t\tfloat fDet = dot( vSigmaX, R1 );\r\n\r\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\r\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8102. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\r\n\r\n\t\tvec4 plane = clippingPlanes[ i ];\r\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\r\n\r\n\t}\r\n\t\t\r\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\r\n\r\n\t\tbool clipped = true;\r\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\r\n\t\t\tvec4 plane = clippingPlanes[ i ];\r\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\r\n\t\t}\r\n\r\n\t\tif ( clipped ) discard;\r\n\t\r\n\t#endif\r\n\r\n#endif\r\n";
  8103. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\r\n\r\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\t\tvarying vec3 vViewPosition;\r\n\t#endif\r\n\r\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\r\n\r\n#endif\r\n";
  8104. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\tvarying vec3 vViewPosition;\r\n#endif\r\n";
  8105. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\r\n\tvViewPosition = - mvPosition.xyz;\r\n#endif\r\n\r\n";
  8106. var color_fragment = "#ifdef USE_COLOR\r\n\r\n\tdiffuseColor.rgb *= vColor;\r\n\r\n#endif";
  8107. var color_pars_fragment = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif\r\n";
  8108. var color_pars_vertex = "#ifdef USE_COLOR\r\n\r\n\tvarying vec3 vColor;\r\n\r\n#endif";
  8109. var color_vertex = "#ifdef USE_COLOR\r\n\r\n\tvColor.xyz = color.xyz;\r\n\r\n#endif";
  8110. var common = "#define PI 3.14159265359\r\n#define PI2 6.28318530718\r\n#define PI_HALF 1.5707963267949\r\n#define RECIPROCAL_PI 0.31830988618\r\n#define RECIPROCAL_PI2 0.15915494\r\n#define LOG2 1.442695\r\n#define EPSILON 1e-6\r\n\r\n#define saturate(a) clamp( a, 0.0, 1.0 )\r\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\r\n\r\nfloat pow2( const in float x ) { return x*x; }\r\nfloat pow3( const in float x ) { return x*x*x; }\r\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\r\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\r\n// expects values in the range of [0,1]x[0,1], returns values in the [0,1] range.\r\n// do not collapse into a single function per: http://byteblacksmith.com/improvements-to-the-canonical-one-liner-glsl-rand-for-opengl-es-2-0/\r\nhighp float rand( const in vec2 uv ) {\r\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\r\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\r\n\treturn fract(sin(sn) * c);\r\n}\r\n\r\nstruct IncidentLight {\r\n\tvec3 color;\r\n\tvec3 direction;\r\n\tbool visible;\r\n};\r\n\r\nstruct ReflectedLight {\r\n\tvec3 directDiffuse;\r\n\tvec3 directSpecular;\r\n\tvec3 indirectDiffuse;\r\n\tvec3 indirectSpecular;\r\n};\r\n\r\nstruct GeometricContext {\r\n\tvec3 position;\r\n\tvec3 normal;\r\n\tvec3 viewDir;\r\n};\r\n\r\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\r\n\r\n}\r\n\r\n// http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations\r\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\r\n\r\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\r\n\r\n}\r\n\r\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\r\n\r\n\treturn - distance * planeNormal + point;\r\n\r\n}\r\n\r\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\r\n\r\n}\r\n\r\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\r\n\r\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\r\n\r\n}\r\n\r\nmat3 transposeMat3( const in mat3 m ) {\r\n\r\n\tmat3 tmp;\r\n\r\n\ttmp[ 0 ] = vec3( m[ 0 ].x, m[ 1 ].x, m[ 2 ].x );\r\n\ttmp[ 1 ] = vec3( m[ 0 ].y, m[ 1 ].y, m[ 2 ].y );\r\n\ttmp[ 2 ] = vec3( m[ 0 ].z, m[ 1 ].z, m[ 2 ].z );\r\n\r\n\treturn tmp;\r\n\r\n}\r\n\r\n// https://en.wikipedia.org/wiki/Relative_luminance\r\nfloat linearToRelativeLuminance( const in vec3 color ) {\r\n\r\n\tvec3 weights = vec3( 0.2126, 0.7152, 0.0722 );\r\n\r\n\treturn dot( weights, color.rgb );\r\n\r\n}\r\n";
  8111. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\r\n\r\n#define cubeUV_textureSize (1024.0)\r\n\r\nint getFaceFromDirection(vec3 direction) {\r\n\tvec3 absDirection = abs(direction);\r\n\tint face = -1;\r\n\tif( absDirection.x > absDirection.z ) {\r\n\t\tif(absDirection.x > absDirection.y )\r\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\telse {\r\n\t\tif(absDirection.z > absDirection.y )\r\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\r\n\t\telse\r\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\r\n\t}\r\n\treturn face;\r\n}\r\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\r\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\r\n\r\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\r\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\r\n\tfloat dxRoughness = dFdx(roughness);\r\n\tfloat dyRoughness = dFdy(roughness);\r\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\r\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\r\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\r\n\t// Clamp the value to the max mip level counts. hard coded to 6 mips\r\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\r\n\tfloat mipLevel = 0.5 * log2(d);\r\n\treturn vec2(floor(mipLevel), fract(mipLevel));\r\n}\r\n\r\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\r\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\r\n\r\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\r\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\r\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\r\n\r\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\r\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\r\n\t// float powScale = exp2(roughnessLevel + mipLevel);\r\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\r\n\t// float scale = 1.0 / exp2(roughnessLevel + 2.0 + mipLevel);\r\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\r\n\t// float mipOffset = 0.75*(1.0 - 1.0/exp2(mipLevel))/exp2(roughnessLevel);\r\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\r\n\r\n\tbool bRes = mipLevel == 0.0;\r\n\tscale = bRes && (scale < a) ? a : scale;\r\n\r\n\tvec3 r;\r\n\tvec2 offset;\r\n\tint face = getFaceFromDirection(direction);\r\n\r\n\tfloat rcpPowScale = 1.0 / powScale;\r\n\r\n\tif( face == 0) {\r\n\t\tr = vec3(direction.x, -direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 1) {\r\n\t\tr = vec3(direction.y, direction.x, direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 2) {\r\n\t\tr = vec3(direction.z, direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\r\n\t}\r\n\telse if( face == 3) {\r\n\t\tr = vec3(direction.x, direction.z, direction.y);\r\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse if( face == 4) {\r\n\t\tr = vec3(direction.y, direction.x, -direction.z);\r\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\telse {\r\n\t\tr = vec3(direction.z, -direction.x, direction.y);\r\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\r\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\r\n\t}\r\n\tr = normalize(r);\r\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\r\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\r\n\tvec2 base = offset + vec2( texelOffset );\r\n\treturn base + s * ( scale - 2.0 * texelOffset );\r\n}\r\n\r\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\r\n\r\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\r\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\r\n\tfloat r1 = floor(roughnessVal);\r\n\tfloat r2 = r1 + 1.0;\r\n\tfloat t = fract(roughnessVal);\r\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\r\n\tfloat s = mipInfo.y;\r\n\tfloat level0 = mipInfo.x;\r\n\tfloat level1 = level0 + 1.0;\r\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\r\n\r\n\t// round to nearest mipmap if we are not interpolating.\r\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\r\n\r\n\t// Tri linear interpolation.\r\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\r\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\r\n\r\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\r\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\r\n\r\n\tvec4 result = mix(color10, color20, t);\r\n\r\n\treturn vec4(result.rgb, 1.0);\r\n}\r\n\r\n#endif\r\n";
  8112. var defaultnormal_vertex = "vec3 transformedNormal = normalMatrix * objectNormal;\r\n\r\n#ifdef FLIP_SIDED\r\n\r\n\ttransformedNormal = - transformedNormal;\r\n\r\n#endif\r\n";
  8113. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\tuniform sampler2D displacementMap;\r\n\tuniform float displacementScale;\r\n\tuniform float displacementBias;\r\n\r\n#endif\r\n";
  8114. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\r\n\r\n\ttransformed += normalize( objectNormal ) * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\r\n\r\n#endif\r\n";
  8115. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\r\n\r\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\r\n\r\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\r\n\r\n#endif\r\n";
  8116. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\r\n\r\n\tuniform sampler2D emissiveMap;\r\n\r\n#endif\r\n";
  8117. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\r\n";
  8118. var encodings_pars_fragment = "// For a discussion of what this is, please read this: http://lousodrome.net/blog/light/2013/05/26/gamma-correct-and-hdr-rendering-in-a-32-bits-buffer/\r\n\r\nvec4 LinearToLinear( in vec4 value ) {\r\n\treturn value;\r\n}\r\n\r\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\r\n}\r\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\r\n\treturn vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\r\n}\r\n\r\nvec4 sRGBToLinear( in vec4 value ) {\r\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 );\r\n}\r\nvec4 LinearTosRGB( in vec4 value ) {\r\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 );\r\n}\r\n\r\nvec4 RGBEToLinear( in vec4 value ) {\r\n\treturn vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\r\n}\r\nvec4 LinearToRGBE( in vec4 value ) {\r\n\tfloat maxComponent = max( max( value.r, value.g ), value.b );\r\n\tfloat fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\r\n\treturn vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\r\n// return vec4( value.brg, ( 3.0 + 128.0 ) / 256.0 );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.xyz * value.w * maxRange, 1.0 );\r\n}\r\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\r\n\tfloat M = clamp( maxRGB / maxRange, 0.0, 1.0 );\r\n\tM = ceil( M * 255.0 ) / 255.0;\r\n\treturn vec4( value.rgb / ( M * maxRange ), M );\r\n}\r\n\r\n// reference: http://iwasbeingirony.blogspot.ca/2010/06/difference-between-rgbm-and-rgbd.html\r\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\r\n\treturn vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\r\n}\r\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\r\n\tfloat maxRGB = max( value.x, max( value.g, value.b ) );\r\n\tfloat D = max( maxRange / maxRGB, 1.0 );\r\n\tD = min( floor( D ) / 255.0, 1.0 );\r\n\treturn vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\r\n}\r\n\r\n// LogLuv reference: http://graphicrants.blogspot.ca/2009/04/rgbm-color-encoding.html\r\n\r\n// M matrix, for encoding\r\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\r\nvec4 LinearToLogLuv( in vec4 value ) {\r\n\tvec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\r\n\tXp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\r\n\tvec4 vResult;\r\n\tvResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\r\n\tfloat Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\r\n\tvResult.w = fract(Le);\r\n\tvResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\r\n\treturn vResult;\r\n}\r\n\r\n// Inverse M matrix, for decoding\r\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\r\nvec4 LogLuvToLinear( in vec4 value ) {\r\n\tfloat Le = value.z * 255.0 + value.w;\r\n\tvec3 Xp_Y_XYZp;\r\n\tXp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\r\n\tXp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\r\n\tXp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\r\n\tvec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\r\n\treturn vec4( max(vRGB, 0.0), 1.0 );\r\n}\r\n";
  8119. var envmap_fragment = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\r\n\r\n\t\t// Transforming Normal Vectors with the Inverse Transformation\r\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#else\r\n\r\n\t\tvec3 reflectVec = vReflect;\r\n\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\tvec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\r\n\r\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\tvec2 sampleUV;\r\n\r\n\t\treflectVec = normalize( reflectVec );\r\n\r\n\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\r\n\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\r\n\r\n\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\treflectVec = normalize( reflectVec );\r\n\r\n\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\r\n\r\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\r\n\r\n\t#else\r\n\r\n\t\tvec4 envColor = vec4( 0.0 );\r\n\r\n\t#endif\r\n\r\n\tenvColor = envMapTexelToLinear( envColor );\r\n\r\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\r\n\r\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_MIX )\r\n\r\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\r\n\r\n\t#elif defined( ENVMAP_BLENDING_ADD )\r\n\r\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8120. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\r\n\tuniform float reflectivity;\r\n\tuniform float envMapIntensity;\r\n#endif\r\n\r\n#ifdef USE_ENVMAP\r\n\r\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\r\n\t\tvarying vec3 vWorldPosition;\r\n\t#endif\r\n\r\n\t#ifdef ENVMAP_TYPE_CUBE\r\n\t\tuniform samplerCube envMap;\r\n\t#else\r\n\t\tuniform sampler2D envMap;\r\n\t#endif\r\n\tuniform float flipEnvMap;\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\r\n\t\tuniform float refractionRatio;\r\n\t#else\r\n\t\tvarying vec3 vReflect;\r\n\t#endif\r\n\r\n#endif\r\n";
  8121. var envmap_pars_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\t\tvarying vec3 vWorldPosition;\r\n\r\n\t#else\r\n\r\n\t\tvarying vec3 vReflect;\r\n\t\tuniform float refractionRatio;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8122. var envmap_vertex = "#ifdef USE_ENVMAP\r\n\r\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\r\n\r\n\t\tvWorldPosition = worldPosition.xyz;\r\n\r\n\t#else\r\n\r\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8123. var fog_vertex = "\r\n#ifdef USE_FOG\r\nfogDepth = -mvPosition.z;\r\n#endif";
  8124. var fog_pars_vertex = "#ifdef USE_FOG\r\n\r\n varying float fogDepth;\r\n\r\n#endif\r\n";
  8125. var fog_fragment = "#ifdef USE_FOG\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 ) );\r\n\r\n\t#else\r\n\r\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, fogDepth );\r\n\r\n\t#endif\r\n\r\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\r\n\r\n#endif\r\n";
  8126. var fog_pars_fragment = "#ifdef USE_FOG\r\n\r\n\tuniform vec3 fogColor;\r\n\tvarying float fogDepth;\r\n\r\n\t#ifdef FOG_EXP2\r\n\r\n\t\tuniform float fogDensity;\r\n\r\n\t#else\r\n\r\n\t\tuniform float fogNear;\r\n\t\tuniform float fogFar;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8127. var gradientmap_pars_fragment = "#ifdef TOON\r\n\r\n\tuniform sampler2D gradientMap;\r\n\r\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\r\n\r\n\t\t// dotNL will be from -1.0 to 1.0\r\n\t\tfloat dotNL = dot( normal, lightDirection );\r\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\r\n\r\n\t\t#ifdef USE_GRADIENTMAP\r\n\r\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\r\n\r\n\t\t#else\r\n\r\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\r\n\r\n\t\t#endif\r\n\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8128. var lightmap_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity; // factor of PI should not be present; included here to prevent breakage\r\n\r\n#endif\r\n";
  8129. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\r\n\r\n\tuniform sampler2D lightMap;\r\n\tuniform float lightMapIntensity;\r\n\r\n#endif";
  8130. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\r\n\r\nGeometricContext geometry;\r\ngeometry.position = mvPosition.xyz;\r\ngeometry.normal = normalize( transformedNormal );\r\ngeometry.viewDir = normalize( -mvPosition.xyz );\r\n\r\nGeometricContext backGeometry;\r\nbackGeometry.position = geometry.position;\r\nbackGeometry.normal = -geometry.normal;\r\nbackGeometry.viewDir = geometry.viewDir;\r\n\r\nvLightFront = vec3( 0.0 );\r\n\r\n#ifdef DOUBLE_SIDED\r\n\tvLightBack = vec3( 0.0 );\r\n#endif\r\n\r\nIncidentLight directLight;\r\nfloat dotNL;\r\nvec3 directLightColor_Diffuse;\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\r\n\r\n\t\tdotNL = dot( geometry.normal, directLight.direction );\r\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\r\n\r\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t#ifdef DOUBLE_SIDED\r\n\r\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8131. var lights_pars = "uniform vec3 ambientLightColor;\r\n\r\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\r\n\r\n\tvec3 irradiance = ambientLightColor;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI;\r\n\r\n\t#endif\r\n\r\n\treturn irradiance;\r\n\r\n}\r\n\r\n#if NUM_DIR_LIGHTS > 0\r\n\r\n\tstruct DirectionalLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\r\n\r\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tdirectLight.color = directionalLight.color;\r\n\t\tdirectLight.direction = directionalLight.direction;\r\n\t\tdirectLight.visible = true;\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_POINT_LIGHTS > 0\r\n\r\n\tstruct PointLight {\r\n\t\tvec3 position;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t\tfloat shadowCameraNear;\r\n\t\tfloat shadowCameraFar;\r\n\t};\r\n\r\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = pointLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\r\n\t\tdirectLight.color = pointLight.color;\r\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\r\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tstruct SpotLight {\r\n\t\tvec3 position;\r\n\t\tvec3 direction;\r\n\t\tvec3 color;\r\n\t\tfloat distance;\r\n\t\tfloat decay;\r\n\t\tfloat coneCos;\r\n\t\tfloat penumbraCos;\r\n\r\n\t\tint shadow;\r\n\t\tfloat shadowBias;\r\n\t\tfloat shadowRadius;\r\n\t\tvec2 shadowMapSize;\r\n\t};\r\n\r\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\r\n\r\n\t// directLight is an out parameter as having it as a return value caused compiler errors on some devices\r\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\r\n\r\n\t\tvec3 lVector = spotLight.position - geometry.position;\r\n\t\tdirectLight.direction = normalize( lVector );\r\n\r\n\t\tfloat lightDistance = length( lVector );\r\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\r\n\r\n\t\tif ( angleCos > spotLight.coneCos ) {\r\n\r\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\r\n\r\n\t\t\tdirectLight.color = spotLight.color;\r\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\r\n\t\t\tdirectLight.visible = true;\r\n\r\n\t\t} else {\r\n\r\n\t\t\tdirectLight.color = vec3( 0.0 );\r\n\t\t\tdirectLight.visible = false;\r\n\r\n\t\t}\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\r\n\tstruct RectAreaLight {\r\n\t\tvec3 color;\r\n\t\tvec3 position;\r\n\t\tvec3 halfWidth;\r\n\t\tvec3 halfHeight;\r\n\t};\r\n\r\n\t// Pre-computed values of LinearTransformedCosine approximation of BRDF\r\n\t// BRDF approximation Texture is 64x64\r\n\tuniform sampler2D ltcMat; // RGBA Float\r\n\tuniform sampler2D ltcMag; // Alpha Float (only has w component)\r\n\r\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\r\n\r\n#endif\r\n\r\n\r\n#if NUM_HEMI_LIGHTS > 0\r\n\r\n\tstruct HemisphereLight {\r\n\t\tvec3 direction;\r\n\t\tvec3 skyColor;\r\n\t\tvec3 groundColor;\r\n\t};\r\n\r\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\r\n\r\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\r\n\r\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\r\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\r\n\r\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tirradiance *= PI;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn irradiance;\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n\r\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\r\n\r\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\r\n\r\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\r\n\t\t\t// TODO: replace with properly filtered cubemaps and access the irradiance LOD level, be it the last LOD level\r\n\t\t\t// of a specular cubemap, or just the default level of a specially created irradiance cubemap.\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\t// force the bias high to get the last LOD level as it is the most blurred.\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec4 envMapColor = vec4( 0.0 );\r\n\r\n\t\t#endif\r\n\r\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n\t// taken from here: http://casual-effects.blogspot.ca/2011/08/plausible-environment-lighting-in-two.html\r\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t//float envMapWidth = pow( 2.0, maxMIPLevelScalar );\r\n\t\t//float desiredMIPLevel = log2( envMapWidth * sqrt( 3.0 ) ) - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\r\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar + 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\r\n\r\n\t\t// clamp to allowable LOD ranges.\r\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\r\n\r\n\t}\r\n\r\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\r\n\r\n\t\t#ifdef ENVMAP_MODE_REFLECTION\r\n\r\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\r\n\r\n\t\t#else\r\n\r\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\r\n\r\n\t\t#endif\r\n\r\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\r\n\r\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\r\n\r\n\t\t#ifdef ENVMAP_TYPE_CUBE\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\r\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\r\n\r\n\t\t\tvec2 sampleUV;\r\n\t\t\tsampleUV.y = asin( clamp( reflectVec.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\r\n\r\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\r\n\r\n\t\t\t#ifdef TEXTURE_LOD_EXT\r\n\r\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#else\r\n\r\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\r\n\r\n\t\t\t#endif\r\n\r\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\r\n\r\n\t\t#endif\r\n\r\n\t\treturn envMapColor.rgb * envMapIntensity;\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8132. var lights_phong_fragment = "BlinnPhongMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb;\r\nmaterial.specularColor = specular;\r\nmaterial.specularShininess = shininess;\r\nmaterial.specularStrength = specularStrength;\r\n";
  8133. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n\r\nstruct BlinnPhongMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tvec3\tspecularColor;\r\n\tfloat\tspecularShininess;\r\n\tfloat\tspecularStrength;\r\n\r\n};\r\n\r\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifdef TOON\r\n\r\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\r\n\r\n\t#else\r\n\r\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\t\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#endif\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\r\n\r\n#define Material_LightProbeLOD( material )\t(0)\r\n";
  8134. var lights_physical_fragment = "PhysicalMaterial material;\r\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\r\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\r\n#ifdef STANDARD\r\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\r\n#else\r\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\r\n\tmaterial.clearCoat = saturate( clearCoat ); // Burley clearcoat model\r\n\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\r\n#endif\r\n";
  8135. var lights_physical_pars_fragment = "struct PhysicalMaterial {\r\n\r\n\tvec3\tdiffuseColor;\r\n\tfloat\tspecularRoughness;\r\n\tvec3\tspecularColor;\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoat;\r\n\t\tfloat clearCoatRoughness;\r\n\t#endif\r\n\r\n};\r\n\r\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\r\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\r\n\r\n// Clear coat directional hemishperical reflectance (this approximation should be improved)\r\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\r\n\r\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\r\n\r\n}\r\n\r\n#if NUM_RECT_AREA_LIGHTS > 0\r\n\r\n\tvoid RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t\tvec3 normal = geometry.normal;\r\n\t\tvec3 viewDir = geometry.viewDir;\r\n\t\tvec3 position = geometry.position;\r\n\t\tvec3 lightPos = rectAreaLight.position;\r\n\t\tvec3 halfWidth = rectAreaLight.halfWidth;\r\n\t\tvec3 halfHeight = rectAreaLight.halfHeight;\r\n\t\tvec3 lightColor = rectAreaLight.color;\r\n\t\tfloat roughness = material.specularRoughness;\r\n\r\n\t\tvec3 rectCoords[ 4 ];\r\n\t\trectCoords[ 0 ] = lightPos - halfWidth - halfHeight; // counterclockwise\r\n\t\trectCoords[ 1 ] = lightPos + halfWidth - halfHeight;\r\n\t\trectCoords[ 2 ] = lightPos + halfWidth + halfHeight;\r\n\t\trectCoords[ 3 ] = lightPos - halfWidth + halfHeight;\r\n\r\n\t\tvec2 uv = LTC_Uv( normal, viewDir, roughness );\r\n\r\n\t\tfloat norm = texture2D( ltcMag, uv ).a;\r\n\r\n\t\tvec4 t = texture2D( ltcMat, uv );\r\n\r\n\t\tmat3 mInv = mat3(\r\n\t\t\tvec3( 1, 0, t.y ),\r\n\t\t\tvec3( 0, t.z, 0 ),\r\n\t\t\tvec3( t.w, 0, t.x )\r\n\t\t);\r\n\r\n\t\treflectedLight.directSpecular += lightColor * material.specularColor * norm * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); // no fresnel\r\n\r\n\t\treflectedLight.directDiffuse += lightColor * material.diffuseColor * LTC_Evaluate( normal, viewDir, position, mat3( 1 ), rectCoords );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\r\n\r\n\tvec3 irradiance = dotNL * directLight.color;\r\n\r\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\tirradiance *= PI; // punctual light\r\n\r\n\t#endif\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\r\n\r\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\r\n\r\n}\r\n\r\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\r\n\r\n\t#ifndef STANDARD\r\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\r\n\t\tfloat dotNL = dotNV;\r\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\r\n\t#else\r\n\t\tfloat clearCoatDHR = 0.0;\r\n\t#endif\r\n\r\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\r\n\r\n\t#ifndef STANDARD\r\n\r\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\r\n\r\n\t#endif\r\n\r\n}\r\n\r\n#define RE_Direct\t\t\t\tRE_Direct_Physical\r\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\r\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\r\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\r\n\r\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\r\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\r\n\r\n// ref: https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\r\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\r\n\r\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\r\n\r\n}\r\n";
  8136. var lights_template = "\r\n\r\nGeometricContext geometry;\r\n\r\ngeometry.position = - vViewPosition;\r\ngeometry.normal = normal;\r\ngeometry.viewDir = normalize( vViewPosition );\r\n\r\nIncidentLight directLight;\r\n\r\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tPointLight pointLight;\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\r\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\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;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tSpotLight spotLight;\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\r\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\r\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\r\n\r\n\t\t#ifdef USE_SHADOWMAP\r\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\t\t#endif\r\n\r\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\r\n\r\n\tRectAreaLight rectAreaLight;\r\n\r\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\r\n\r\n\t\trectAreaLight = rectAreaLights[ i ];\r\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\r\n\r\n\t}\r\n\r\n#endif\r\n\r\n#if defined( RE_IndirectDiffuse )\r\n\r\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\r\n\r\n\t\t\tlightMapIrradiance *= PI; // factor of PI should not be present; included here to prevent breakage\r\n\r\n\t\t#endif\r\n\r\n\t\tirradiance += lightMapIrradiance;\r\n\r\n\t#endif\r\n\r\n\t#if ( NUM_HEMI_LIGHTS > 0 )\r\n\r\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\r\n\r\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\r\n\r\n\t\t// TODO, replace 8 with the real maxMIPLevel\r\n\t\tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\r\n\r\n\t#endif\r\n\r\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n\r\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\r\n\r\n\t// TODO, replace 8 with the real maxMIPLevel\r\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\r\n\r\n\t#ifndef STANDARD\r\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\r\n\t#else\r\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\r\n\t#endif\r\n\r\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\r\n\r\n#endif\r\n";
  8137. var logdepthbuf_fragment = "#if defined( USE_LOGDEPTHBUF ) && defined( USE_LOGDEPTHBUF_EXT )\r\n\r\n\tgl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;\r\n\r\n#endif";
  8138. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\tuniform float logDepthBufFC;\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvarying float vFragDepth;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8139. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvarying float vFragDepth;\r\n\r\n\t#endif\r\n\r\n\tuniform float logDepthBufFC;\r\n\r\n#endif";
  8140. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\r\n\r\n\t#ifdef USE_LOGDEPTHBUF_EXT\r\n\r\n\t\tvFragDepth = 1.0 + gl_Position.w;\r\n\r\n\t#else\r\n\r\n\t\tgl_Position.z = log2( max( EPSILON, gl_Position.w + 1.0 ) ) * logDepthBufFC - 1.0;\r\n\r\n\t\tgl_Position.z *= gl_Position.w;\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8141. var map_fragment = "#ifdef USE_MAP\r\n\r\n\tvec4 texelColor = texture2D( map, vUv );\r\n\r\n\ttexelColor = mapTexelToLinear( texelColor );\r\n\tdiffuseColor *= texelColor;\r\n\r\n#endif\r\n";
  8142. var map_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  8143. var map_particle_fragment = "#ifdef USE_MAP\r\n\r\n\tvec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy;\r\n\tvec4 mapTexel = texture2D( map, uv );\r\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\r\n\r\n#endif\r\n";
  8144. var map_particle_pars_fragment = "#ifdef USE_MAP\r\n\r\n\tuniform mat3 uvTransform;\r\n\tuniform sampler2D map;\r\n\r\n#endif\r\n";
  8145. var metalnessmap_fragment = "float metalnessFactor = metalness;\r\n\r\n#ifdef USE_METALNESSMAP\r\n\r\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\r\n\r\n\t// reads channel B, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\tmetalnessFactor *= texelMetalness.b;\r\n\r\n#endif\r\n";
  8146. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\r\n\r\n\tuniform sampler2D metalnessMap;\r\n\r\n#endif";
  8147. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\r\n\r\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\r\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\r\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\r\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\r\n\r\n#endif\r\n";
  8148. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\tuniform float morphTargetInfluences[ 8 ];\r\n\r\n\t#else\r\n\r\n\tuniform float morphTargetInfluences[ 4 ];\r\n\r\n\t#endif\r\n\r\n#endif";
  8149. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\r\n\r\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\r\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\r\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\r\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\r\n\r\n\t#ifndef USE_MORPHNORMALS\r\n\r\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\r\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\r\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\r\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8150. var normal_fragment = "#ifdef FLAT_SHADED\r\n\r\n\t// Workaround for Adreno/Nexus5 not able able to do dFdx( vViewPosition ) ...\r\n\r\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\r\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\r\n\tvec3 normal = normalize( cross( fdx, fdy ) );\r\n\r\n#else\r\n\r\n\tvec3 normal = normalize( vNormal );\r\n\r\n\t#ifdef DOUBLE_SIDED\r\n\r\n\t\tnormal = normal * ( float( gl_FrontFacing ) * 2.0 - 1.0 );\r\n\r\n\t#endif\r\n\r\n#endif\r\n\r\n#ifdef USE_NORMALMAP\r\n\r\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\r\n\r\n#elif defined( USE_BUMPMAP )\r\n\r\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\r\n\r\n#endif\r\n";
  8151. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\r\n\r\n\tuniform sampler2D normalMap;\r\n\tuniform vec2 normalScale;\r\n\r\n\t// Per-Pixel Tangent Space Normal Mapping\r\n\t// http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html\r\n\r\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\r\n\r\n\t\t// Workaround for Adreno 3XX dFd*( vec3 ) bug. See #9988\r\n\r\n\t\tvec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );\r\n\t\tvec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );\r\n\t\tvec2 st0 = dFdx( vUv.st );\r\n\t\tvec2 st1 = dFdy( vUv.st );\r\n\r\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\r\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\r\n\t\tvec3 N = normalize( surf_norm );\r\n\r\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\r\n\t\tmapN.xy = normalScale * mapN.xy;\r\n\t\tmat3 tsn = mat3( S, T, N );\r\n\t\treturn normalize( tsn * mapN );\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8152. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\r\n\treturn normalize( normal ) * 0.5 + 0.5;\r\n}\r\n\r\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\r\n\treturn 2.0 * rgb.xyz - 1.0;\r\n}\r\n\r\nconst float PackUpscale = 256. / 255.; // fraction -> 0..1 (including 1)\r\nconst float UnpackDownscale = 255. / 256.; // 0..1 -> fraction (excluding 1)\r\n\r\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\r\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\r\n\r\nconst float ShiftRight8 = 1. / 256.;\r\n\r\nvec4 packDepthToRGBA( const in float v ) {\r\n\tvec4 r = vec4( fract( v * PackFactors ), v );\r\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\r\n\treturn r * PackUpscale;\r\n}\r\n\r\nfloat unpackRGBAToDepth( const in vec4 v ) {\r\n\treturn dot( v, UnpackFactors );\r\n}\r\n\r\n// NOTE: viewZ/eyeZ is < 0 when in front of the camera per OpenGL conventions\r\n\r\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn ( viewZ + near ) / ( near - far );\r\n}\r\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\r\n\treturn linearClipZ * ( near - far ) - near;\r\n}\r\n\r\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\r\n\treturn (( near + viewZ ) * far ) / (( far - near ) * viewZ );\r\n}\r\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\r\n\treturn ( near * far ) / ( ( far - near ) * invClipZ - far );\r\n}\r\n";
  8153. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\r\n\r\n\t// Get get normal blending with premultipled, use with CustomBlending, OneFactor, OneMinusSrcAlphaFactor, AddEquation.\r\n\tgl_FragColor.rgb *= gl_FragColor.a;\r\n\r\n#endif\r\n";
  8154. var project_vertex = "vec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\r\n\r\ngl_Position = projectionMatrix * mvPosition;\r\n";
  8155. var dithering_fragment = "#if defined( DITHERING )\r\n\r\n gl_FragColor.rgb = dithering( gl_FragColor.rgb );\r\n\r\n#endif\r\n";
  8156. var dithering_pars_fragment = "#if defined( DITHERING )\r\n\r\n\t// based on https://www.shadertoy.com/view/MslGR8\r\n\tvec3 dithering( vec3 color ) {\r\n\t\t//Calculate grid position\r\n\t\tfloat grid_position = rand( gl_FragCoord.xy );\r\n\r\n\t\t//Shift the individual colors differently, thus making it even harder to see the dithering pattern\r\n\t\tvec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 );\r\n\r\n\t\t//modify shift acording to grid position.\r\n\t\tdither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position );\r\n\r\n\t\t//shift the color by dither_shift\r\n\t\treturn color + dither_shift_RGB;\r\n\t}\r\n\r\n#endif\r\n";
  8157. var roughnessmap_fragment = "float roughnessFactor = roughness;\r\n\r\n#ifdef USE_ROUGHNESSMAP\r\n\r\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\r\n\r\n\t// reads channel G, compatible with a combined OcclusionRoughnessMetallic (RGB) texture\r\n\troughnessFactor *= texelRoughness.g;\r\n\r\n#endif\r\n";
  8158. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\r\n\r\n\tuniform sampler2D roughnessMap;\r\n\r\n#endif";
  8159. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\r\n\r\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\r\n\r\n\t}\r\n\r\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\r\n\r\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\r\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\r\n\r\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\r\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\r\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\r\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\r\n\r\n\t\tvec2 f = fract( uv * size + 0.5 );\r\n\r\n\t\tfloat a = mix( lb, lt, f.y );\r\n\t\tfloat b = mix( rb, rt, f.y );\r\n\t\tfloat c = mix( a, b, f.x );\r\n\r\n\t\treturn c;\r\n\r\n\t}\r\n\r\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\r\n\r\n\t\tfloat shadow = 1.0;\r\n\r\n\t\tshadowCoord.xyz /= shadowCoord.w;\r\n\t\tshadowCoord.z += shadowBias;\r\n\r\n\t\t// if ( something && something ) breaks ATI OpenGL shader compiler\r\n\t\t// if ( all( something, something ) ) using this instead\r\n\r\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\r\n\t\tbool inFrustum = all( inFrustumVec );\r\n\r\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\r\n\r\n\t\tbool frustumTest = all( frustumTestVec );\r\n\r\n\t\tif ( frustumTest ) {\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\tshadow = (\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\r\n\r\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\r\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\r\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\r\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\r\n\r\n\t\t\tshadow = (\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\r\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering:\r\n\r\n\t\t\tshadow = texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\r\n\r\n\t\t#endif\r\n\r\n\t\t}\r\n\r\n\t\treturn shadow;\r\n\r\n\t}\r\n\r\n\t// cubeToUV() maps a 3D direction vector suitable for cube texture mapping to a 2D\r\n\t// vector suitable for 2D texture mapping. This code uses the following layout for the\r\n\t// 2D texture:\r\n\t//\r\n\t// xzXZ\r\n\t// y Y\r\n\t//\r\n\t// Y - Positive y direction\r\n\t// y - Negative y direction\r\n\t// X - Positive x direction\r\n\t// x - Negative x direction\r\n\t// Z - Positive z direction\r\n\t// z - Negative z direction\r\n\t//\r\n\t// Source and test bed:\r\n\t// https://gist.github.com/tschw/da10c43c467ce8afd0c4\r\n\r\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\r\n\r\n\t\t// Number of texels to avoid at the edge of each square\r\n\r\n\t\tvec3 absV = abs( v );\r\n\r\n\t\t// Intersect unit cube\r\n\r\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\r\n\t\tabsV *= scaleToCube;\r\n\r\n\t\t// Apply scale to avoid seams\r\n\r\n\t\t// two texels less per square (one texel will do for NEAREST)\r\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\r\n\r\n\t\t// Unwrap\r\n\r\n\t\t// space: -1 ... 1 range for each square\r\n\t\t//\r\n\t\t// #X##\t\tdim := ( 4 , 2 )\r\n\t\t// # #\t\tcenter := ( 1 , 1 )\r\n\r\n\t\tvec2 planar = v.xy;\r\n\r\n\t\tfloat almostATexel = 1.5 * texelSizeY;\r\n\t\tfloat almostOne = 1.0 - almostATexel;\r\n\r\n\t\tif ( absV.z >= almostOne ) {\r\n\r\n\t\t\tif ( v.z > 0.0 )\r\n\t\t\t\tplanar.x = 4.0 - v.x;\r\n\r\n\t\t} else if ( absV.x >= almostOne ) {\r\n\r\n\t\t\tfloat signX = sign( v.x );\r\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\r\n\r\n\t\t} else if ( absV.y >= almostOne ) {\r\n\r\n\t\t\tfloat signY = sign( v.y );\r\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\r\n\t\t\tplanar.y = v.z * signY - 2.0;\r\n\r\n\t\t}\r\n\r\n\t\t// Transform to UV space\r\n\r\n\t\t// scale := 0.5 / dim\r\n\t\t// translate := ( center + 0.5 ) / dim\r\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\r\n\r\n\t}\r\n\r\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) {\r\n\r\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\r\n\r\n\t\t// for point lights, the uniform @vShadowCoord is re-purposed to hold\r\n\t\t// the vector from the light to the world-space position of the fragment.\r\n\t\tvec3 lightToPosition = shadowCoord.xyz;\r\n\r\n\t\t// dp = normalized distance from light to fragment position\r\n\t\tfloat dp = ( length( lightToPosition ) - shadowCameraNear ) / ( shadowCameraFar - shadowCameraNear ); // need to clamp?\r\n\t\tdp += shadowBias;\r\n\r\n\t\t// bd3D = base direction 3D\r\n\t\tvec3 bd3D = normalize( lightToPosition );\r\n\r\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\r\n\r\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\r\n\r\n\t\t\treturn (\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\r\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\r\n\t\t\t) * ( 1.0 / 9.0 );\r\n\r\n\t\t#else // no percentage-closer filtering\r\n\r\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\r\n\r\n\t\t#endif\r\n\r\n\t}\r\n\r\n#endif\r\n";
  8160. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\r\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\r\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\r\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  8161. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n#endif\r\n";
  8162. var shadowmask_pars_fragment = "float getShadowMask() {\r\n\r\n\tfloat shadow = 1.0;\r\n\r\n\t#ifdef USE_SHADOWMAP\r\n\r\n\t#if NUM_DIR_LIGHTS > 0\r\n\r\n\tDirectionalLight directionalLight;\r\n\r\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\r\n\r\n\t\tdirectionalLight = directionalLights[ i ];\r\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_SPOT_LIGHTS > 0\r\n\r\n\tSpotLight spotLight;\r\n\r\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\r\n\r\n\t\tspotLight = spotLights[ i ];\r\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\t#if NUM_POINT_LIGHTS > 0\r\n\r\n\tPointLight pointLight;\r\n\r\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\r\n\r\n\t\tpointLight = pointLights[ i ];\r\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0;\r\n\r\n\t}\r\n\r\n\t#endif\r\n\r\n\r\n\r\n\t#endif\r\n\r\n\treturn shadow;\r\n\r\n}\r\n";
  8163. var skinbase_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\r\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\r\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\r\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\r\n\r\n#endif";
  8164. var skinning_pars_vertex = "#ifdef USE_SKINNING\r\n\r\n\tuniform mat4 bindMatrix;\r\n\tuniform mat4 bindMatrixInverse;\r\n\r\n\t#ifdef BONE_TEXTURE\r\n\r\n\t\tuniform sampler2D boneTexture;\r\n\t\tuniform int boneTextureSize;\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tfloat j = i * 4.0;\r\n\t\t\tfloat x = mod( j, float( boneTextureSize ) );\r\n\t\t\tfloat y = floor( j / float( boneTextureSize ) );\r\n\r\n\t\t\tfloat dx = 1.0 / float( boneTextureSize );\r\n\t\t\tfloat dy = 1.0 / float( boneTextureSize );\r\n\r\n\t\t\ty = dy * ( y + 0.5 );\r\n\r\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\r\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\r\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\r\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\r\n\r\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\r\n\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#else\r\n\r\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\r\n\r\n\t\tmat4 getBoneMatrix( const in float i ) {\r\n\r\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\r\n\t\t\treturn bone;\r\n\r\n\t\t}\r\n\r\n\t#endif\r\n\r\n#endif\r\n";
  8165. var skinning_vertex = "#ifdef USE_SKINNING\r\n\r\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\r\n\r\n\tvec4 skinned = vec4( 0.0 );\r\n\tskinned += boneMatX * skinVertex * skinWeight.x;\r\n\tskinned += boneMatY * skinVertex * skinWeight.y;\r\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\r\n\tskinned += boneMatW * skinVertex * skinWeight.w;\r\n\r\n\ttransformed = ( bindMatrixInverse * skinned ).xyz;\r\n\r\n#endif\r\n";
  8166. var skinnormal_vertex = "#ifdef USE_SKINNING\r\n\r\n\tmat4 skinMatrix = mat4( 0.0 );\r\n\tskinMatrix += skinWeight.x * boneMatX;\r\n\tskinMatrix += skinWeight.y * boneMatY;\r\n\tskinMatrix += skinWeight.z * boneMatZ;\r\n\tskinMatrix += skinWeight.w * boneMatW;\r\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\r\n\r\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\r\n\r\n#endif\r\n";
  8167. var specularmap_fragment = "float specularStrength;\r\n\r\n#ifdef USE_SPECULARMAP\r\n\r\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\r\n\tspecularStrength = texelSpecular.r;\r\n\r\n#else\r\n\r\n\tspecularStrength = 1.0;\r\n\r\n#endif";
  8168. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\r\n\r\n\tuniform sampler2D specularMap;\r\n\r\n#endif";
  8169. var tonemapping_fragment = "#if defined( TONE_MAPPING )\r\n\r\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\r\n\r\n#endif\r\n";
  8170. var tonemapping_pars_fragment = "#ifndef saturate\r\n\t#define saturate(a) clamp( a, 0.0, 1.0 )\r\n#endif\r\n\r\nuniform float toneMappingExposure;\r\nuniform float toneMappingWhitePoint;\r\n\r\n// exposure only\r\nvec3 LinearToneMapping( vec3 color ) {\r\n\r\n\treturn toneMappingExposure * color;\r\n\r\n}\r\n\r\n// source: https://www.cs.utah.edu/~reinhard/cdrom/\r\nvec3 ReinhardToneMapping( vec3 color ) {\r\n\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( color / ( vec3( 1.0 ) + color ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\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 ) )\r\nvec3 Uncharted2ToneMapping( vec3 color ) {\r\n\r\n\t// John Hable's filmic operator from Uncharted 2 video game\r\n\tcolor *= toneMappingExposure;\r\n\treturn saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\r\n\r\n}\r\n\r\n// source: http://filmicgames.com/archives/75\r\nvec3 OptimizedCineonToneMapping( vec3 color ) {\r\n\r\n\t// optimized filmic operator by Jim Hejl and Richard Burgess-Dawson\r\n\tcolor *= toneMappingExposure;\r\n\tcolor = max( vec3( 0.0 ), color - 0.004 );\r\n\treturn pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\r\n\r\n}\r\n";
  8171. 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 )\r\n\r\n\tvarying vec2 vUv;\r\n\r\n#endif";
  8172. 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 )\r\n\r\n\tvarying vec2 vUv;\r\n\tuniform mat3 uvTransform;\r\n\r\n#endif\r\n";
  8173. 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 )\r\n\r\n\tvUv = ( uvTransform * vec3( uv, 1 ) ).xy;\r\n\r\n#endif";
  8174. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  8175. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tattribute vec2 uv2;\r\n\tvarying vec2 vUv2;\r\n\r\n#endif";
  8176. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\r\n\r\n\tvUv2 = uv2;\r\n\r\n#endif";
  8177. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP )\r\n\r\n\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\r\n\r\n#endif\r\n";
  8178. var cube_frag = "uniform samplerCube tCube;\r\nuniform float tFlip;\r\nuniform float opacity;\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\nvoid main() {\r\n\r\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\r\n\tgl_FragColor.a *= opacity;\r\n\r\n}\r\n";
  8179. var cube_vert = "varying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldPosition = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n\tgl_Position.z = gl_Position.w; // set z to camera.far\r\n\r\n}\r\n";
  8180. var depth_frag = "#if DEPTH_PACKING == 3200\r\n\r\n\tuniform float opacity;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( 1.0 );\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tdiffuseColor.a = opacity;\r\n\r\n\t#endif\r\n\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\r\n\t#if DEPTH_PACKING == 3200\r\n\r\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\r\n\r\n\t#elif DEPTH_PACKING == 3201\r\n\r\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\r\n\r\n\t#endif\r\n\r\n}\r\n";
  8181. var depth_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_DISPLACEMENTMAP\r\n\r\n\t\t#include <beginnormal_vertex>\r\n\t\t#include <morphnormal_vertex>\r\n\t\t#include <skinnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n}\r\n";
  8182. var distanceRGBA_frag = "#define DISTANCE\r\n\r\nuniform vec3 referencePosition;\r\nuniform float nearDistance;\r\nuniform float farDistance;\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main () {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( 1.0 );\r\n\r\n\t#include <map_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\tfloat dist = length( vWorldPosition - referencePosition );\r\n\tdist = ( dist - nearDistance ) / ( farDistance - nearDistance );\r\n\tdist = saturate( dist ); // clamp to [ 0, 1 ]\r\n\r\n\tgl_FragColor = packDepthToRGBA( dist );\r\n\r\n}\r\n";
  8183. var distanceRGBA_vert = "#define DISTANCE\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_DISPLACEMENTMAP\r\n\r\n\t\t#include <beginnormal_vertex>\r\n\t\t#include <morphnormal_vertex>\r\n\t\t#include <skinnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvWorldPosition = worldPosition.xyz;\r\n\r\n}\r\n";
  8184. var equirect_frag = "uniform sampler2D tEquirect;\r\n\r\nvarying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvec3 direction = normalize( vWorldPosition );\r\n\r\n\tvec2 sampleUV;\r\n\r\n\tsampleUV.y = asin( clamp( direction.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5;\r\n\r\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\r\n\r\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\r\n\r\n}\r\n";
  8185. var equirect_vert = "varying vec3 vWorldPosition;\r\n\r\n#include <common>\r\n\r\nvoid main() {\r\n\r\n\tvWorldPosition = transformDirection( position, modelMatrix );\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n}\r\n";
  8186. var linedashed_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\nuniform float dashSize;\r\nuniform float totalSize;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\r\n\r\n\t\tdiscard;\r\n\r\n\t}\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <color_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb; // simple shader\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  8187. var linedashed_vert = "uniform float scale;\r\nattribute float lineDistance;\r\n\r\nvarying float vLineDistance;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\r\n\tvLineDistance = scale * lineDistance;\r\n\r\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\r\n\tgl_Position = projectionMatrix * mvPosition;\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8188. var meshbasic_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\r\n\t// accumulation (baked indirect lighting only)\r\n\t#ifdef USE_LIGHTMAP\r\n\r\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\r\n\r\n\t#endif\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\r\n\r\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  8189. var meshbasic_vert = "#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\t#include <skinbase_vertex>\r\n\r\n\t#ifdef USE_ENVMAP\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8190. var meshlambert_frag = "uniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float opacity;\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <fog_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\r\n\r\n\t#include <lightmap_fragment>\r\n\r\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\r\n\r\n\t#ifdef DOUBLE_SIDED\r\n\r\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\r\n\r\n\t#else\r\n\r\n\t\treflectedLight.directDiffuse = vLightFront;\r\n\r\n\t#endif\r\n\r\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  8191. var meshlambert_vert = "#define LAMBERT\r\n\r\nvarying vec3 vLightFront;\r\n\r\n#ifdef DOUBLE_SIDED\r\n\r\n\tvarying vec3 vLightBack;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <lights_lambert_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8192. var meshphong_frag = "#define PHONG\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform vec3 specular;\r\nuniform float shininess;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <gradientmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <lights_phong_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <specularmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <specularmap_fragment>\r\n\t#include <normal_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_phong_fragment>\r\n\t#include <lights_template>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\t#include <envmap_fragment>\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  8193. var meshphong_vert = "#define PHONG\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <envmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <envmap_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8194. var meshphysical_frag = "#define PHYSICAL\r\n\r\nuniform vec3 diffuse;\r\nuniform vec3 emissive;\r\nuniform float roughness;\r\nuniform float metalness;\r\nuniform float opacity;\r\n\r\n#ifndef STANDARD\r\n\tuniform float clearCoat;\r\n\tuniform float clearCoatRoughness;\r\n#endif\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <dithering_pars_fragment>\r\n#include <color_pars_fragment>\r\n#include <uv_pars_fragment>\r\n#include <uv2_pars_fragment>\r\n#include <map_pars_fragment>\r\n#include <alphamap_pars_fragment>\r\n#include <aomap_pars_fragment>\r\n#include <lightmap_pars_fragment>\r\n#include <emissivemap_pars_fragment>\r\n#include <envmap_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <cube_uv_reflection_fragment>\r\n#include <lights_pars>\r\n#include <lights_physical_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <roughnessmap_pars_fragment>\r\n#include <metalnessmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\r\n\tvec3 totalEmissiveRadiance = emissive;\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphamap_fragment>\r\n\t#include <alphatest_fragment>\r\n\t#include <roughnessmap_fragment>\r\n\t#include <metalnessmap_fragment>\r\n\t#include <normal_fragment>\r\n\t#include <emissivemap_fragment>\r\n\r\n\t// accumulation\r\n\t#include <lights_physical_fragment>\r\n\t#include <lights_template>\r\n\r\n\t// modulation\r\n\t#include <aomap_fragment>\r\n\r\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <dithering_fragment>\r\n\r\n}\r\n";
  8195. var meshphysical_vert = "#define PHYSICAL\r\n\r\nvarying vec3 vViewPosition;\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <common>\r\n#include <uv_pars_vertex>\r\n#include <uv2_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\t#include <uv2_vertex>\r\n\t#include <color_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8196. var normal_frag = "#define NORMAL\r\n\r\nuniform float opacity;\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <packing>\r\n#include <uv_pars_fragment>\r\n#include <bumpmap_pars_fragment>\r\n#include <normalmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <normal_fragment>\r\n\r\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\r\n\r\n}\r\n";
  8197. var normal_vert = "#define NORMAL\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvarying vec3 vViewPosition;\r\n\r\n#endif\r\n\r\n#ifndef FLAT_SHADED\r\n\r\n\tvarying vec3 vNormal;\r\n\r\n#endif\r\n\r\n#include <uv_pars_vertex>\r\n#include <displacementmap_pars_vertex>\r\n#include <morphtarget_pars_vertex>\r\n#include <skinning_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <uv_vertex>\r\n\r\n\t#include <beginnormal_vertex>\r\n\t#include <morphnormal_vertex>\r\n\t#include <skinbase_vertex>\r\n\t#include <skinnormal_vertex>\r\n\t#include <defaultnormal_vertex>\r\n\r\n#ifndef FLAT_SHADED // Normal computed with derivatives when FLAT_SHADED\r\n\r\n\tvNormal = normalize( transformedNormal );\r\n\r\n#endif\r\n\r\n\t#include <begin_vertex>\r\n\t#include <morphtarget_vertex>\r\n\t#include <skinning_vertex>\r\n\t#include <displacementmap_vertex>\r\n\t#include <project_vertex>\r\n\t#include <logdepthbuf_vertex>\r\n\r\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\r\n\r\n\tvViewPosition = - mvPosition.xyz;\r\n\r\n#endif\r\n\r\n}\r\n";
  8198. var points_frag = "uniform vec3 diffuse;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <color_pars_fragment>\r\n#include <map_particle_pars_fragment>\r\n#include <fog_pars_fragment>\r\n#include <shadowmap_pars_fragment>\r\n#include <logdepthbuf_pars_fragment>\r\n#include <clipping_planes_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\t#include <clipping_planes_fragment>\r\n\r\n\tvec3 outgoingLight = vec3( 0.0 );\r\n\tvec4 diffuseColor = vec4( diffuse, opacity );\r\n\r\n\t#include <logdepthbuf_fragment>\r\n\t#include <map_particle_fragment>\r\n\t#include <color_fragment>\r\n\t#include <alphatest_fragment>\r\n\r\n\toutgoingLight = diffuseColor.rgb;\r\n\r\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\r\n\r\n\t#include <premultiplied_alpha_fragment>\r\n\t#include <tonemapping_fragment>\r\n\t#include <encodings_fragment>\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  8199. var points_vert = "uniform float size;\r\nuniform float scale;\r\n\r\n#include <common>\r\n#include <color_pars_vertex>\r\n#include <fog_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n#include <logdepthbuf_pars_vertex>\r\n#include <clipping_planes_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <color_vertex>\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\r\n\t#ifdef USE_SIZEATTENUATION\r\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\r\n\t#else\r\n\t\tgl_PointSize = size;\r\n\t#endif\r\n\r\n\t#include <logdepthbuf_vertex>\r\n\t#include <clipping_planes_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8200. var shadow_frag = "uniform vec3 color;\r\nuniform float opacity;\r\n\r\n#include <common>\r\n#include <packing>\r\n#include <fog_pars_fragment>\r\n#include <bsdfs>\r\n#include <lights_pars>\r\n#include <shadowmap_pars_fragment>\r\n#include <shadowmask_pars_fragment>\r\n\r\nvoid main() {\r\n\r\n\tgl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) );\r\n\r\n\t#include <fog_fragment>\r\n\r\n}\r\n";
  8201. var shadow_vert = "#include <fog_pars_vertex>\r\n#include <shadowmap_pars_vertex>\r\n\r\nvoid main() {\r\n\r\n\t#include <begin_vertex>\r\n\t#include <project_vertex>\r\n\t#include <worldpos_vertex>\r\n\t#include <shadowmap_vertex>\r\n\t#include <fog_vertex>\r\n\r\n}\r\n";
  8202. var ShaderChunk = {
  8203. alphamap_fragment: alphamap_fragment,
  8204. alphamap_pars_fragment: alphamap_pars_fragment,
  8205. alphatest_fragment: alphatest_fragment,
  8206. aomap_fragment: aomap_fragment,
  8207. aomap_pars_fragment: aomap_pars_fragment,
  8208. begin_vertex: begin_vertex,
  8209. beginnormal_vertex: beginnormal_vertex,
  8210. bsdfs: bsdfs,
  8211. bumpmap_pars_fragment: bumpmap_pars_fragment,
  8212. clipping_planes_fragment: clipping_planes_fragment,
  8213. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  8214. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  8215. clipping_planes_vertex: clipping_planes_vertex,
  8216. color_fragment: color_fragment,
  8217. color_pars_fragment: color_pars_fragment,
  8218. color_pars_vertex: color_pars_vertex,
  8219. color_vertex: color_vertex,
  8220. common: common,
  8221. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  8222. defaultnormal_vertex: defaultnormal_vertex,
  8223. displacementmap_pars_vertex: displacementmap_pars_vertex,
  8224. displacementmap_vertex: displacementmap_vertex,
  8225. emissivemap_fragment: emissivemap_fragment,
  8226. emissivemap_pars_fragment: emissivemap_pars_fragment,
  8227. encodings_fragment: encodings_fragment,
  8228. encodings_pars_fragment: encodings_pars_fragment,
  8229. envmap_fragment: envmap_fragment,
  8230. envmap_pars_fragment: envmap_pars_fragment,
  8231. envmap_pars_vertex: envmap_pars_vertex,
  8232. envmap_vertex: envmap_vertex,
  8233. fog_vertex: fog_vertex,
  8234. fog_pars_vertex: fog_pars_vertex,
  8235. fog_fragment: fog_fragment,
  8236. fog_pars_fragment: fog_pars_fragment,
  8237. gradientmap_pars_fragment: gradientmap_pars_fragment,
  8238. lightmap_fragment: lightmap_fragment,
  8239. lightmap_pars_fragment: lightmap_pars_fragment,
  8240. lights_lambert_vertex: lights_lambert_vertex,
  8241. lights_pars: lights_pars,
  8242. lights_phong_fragment: lights_phong_fragment,
  8243. lights_phong_pars_fragment: lights_phong_pars_fragment,
  8244. lights_physical_fragment: lights_physical_fragment,
  8245. lights_physical_pars_fragment: lights_physical_pars_fragment,
  8246. lights_template: lights_template,
  8247. logdepthbuf_fragment: logdepthbuf_fragment,
  8248. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  8249. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  8250. logdepthbuf_vertex: logdepthbuf_vertex,
  8251. map_fragment: map_fragment,
  8252. map_pars_fragment: map_pars_fragment,
  8253. map_particle_fragment: map_particle_fragment,
  8254. map_particle_pars_fragment: map_particle_pars_fragment,
  8255. metalnessmap_fragment: metalnessmap_fragment,
  8256. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  8257. morphnormal_vertex: morphnormal_vertex,
  8258. morphtarget_pars_vertex: morphtarget_pars_vertex,
  8259. morphtarget_vertex: morphtarget_vertex,
  8260. normal_fragment: normal_fragment,
  8261. normalmap_pars_fragment: normalmap_pars_fragment,
  8262. packing: packing,
  8263. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  8264. project_vertex: project_vertex,
  8265. dithering_fragment: dithering_fragment,
  8266. dithering_pars_fragment: dithering_pars_fragment,
  8267. roughnessmap_fragment: roughnessmap_fragment,
  8268. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  8269. shadowmap_pars_fragment: shadowmap_pars_fragment,
  8270. shadowmap_pars_vertex: shadowmap_pars_vertex,
  8271. shadowmap_vertex: shadowmap_vertex,
  8272. shadowmask_pars_fragment: shadowmask_pars_fragment,
  8273. skinbase_vertex: skinbase_vertex,
  8274. skinning_pars_vertex: skinning_pars_vertex,
  8275. skinning_vertex: skinning_vertex,
  8276. skinnormal_vertex: skinnormal_vertex,
  8277. specularmap_fragment: specularmap_fragment,
  8278. specularmap_pars_fragment: specularmap_pars_fragment,
  8279. tonemapping_fragment: tonemapping_fragment,
  8280. tonemapping_pars_fragment: tonemapping_pars_fragment,
  8281. uv_pars_fragment: uv_pars_fragment,
  8282. uv_pars_vertex: uv_pars_vertex,
  8283. uv_vertex: uv_vertex,
  8284. uv2_pars_fragment: uv2_pars_fragment,
  8285. uv2_pars_vertex: uv2_pars_vertex,
  8286. uv2_vertex: uv2_vertex,
  8287. worldpos_vertex: worldpos_vertex,
  8288. cube_frag: cube_frag,
  8289. cube_vert: cube_vert,
  8290. depth_frag: depth_frag,
  8291. depth_vert: depth_vert,
  8292. distanceRGBA_frag: distanceRGBA_frag,
  8293. distanceRGBA_vert: distanceRGBA_vert,
  8294. equirect_frag: equirect_frag,
  8295. equirect_vert: equirect_vert,
  8296. linedashed_frag: linedashed_frag,
  8297. linedashed_vert: linedashed_vert,
  8298. meshbasic_frag: meshbasic_frag,
  8299. meshbasic_vert: meshbasic_vert,
  8300. meshlambert_frag: meshlambert_frag,
  8301. meshlambert_vert: meshlambert_vert,
  8302. meshphong_frag: meshphong_frag,
  8303. meshphong_vert: meshphong_vert,
  8304. meshphysical_frag: meshphysical_frag,
  8305. meshphysical_vert: meshphysical_vert,
  8306. normal_frag: normal_frag,
  8307. normal_vert: normal_vert,
  8308. points_frag: points_frag,
  8309. points_vert: points_vert,
  8310. shadow_frag: shadow_frag,
  8311. shadow_vert: shadow_vert
  8312. };
  8313. /**
  8314. * @author alteredq / http://alteredqualia.com/
  8315. * @author mrdoob / http://mrdoob.com/
  8316. * @author mikael emtinger / http://gomo.se/
  8317. */
  8318. var ShaderLib = {
  8319. basic: {
  8320. uniforms: UniformsUtils.merge( [
  8321. UniformsLib.common,
  8322. UniformsLib.specularmap,
  8323. UniformsLib.envmap,
  8324. UniformsLib.aomap,
  8325. UniformsLib.lightmap,
  8326. UniformsLib.fog
  8327. ] ),
  8328. vertexShader: ShaderChunk.meshbasic_vert,
  8329. fragmentShader: ShaderChunk.meshbasic_frag
  8330. },
  8331. lambert: {
  8332. uniforms: UniformsUtils.merge( [
  8333. UniformsLib.common,
  8334. UniformsLib.specularmap,
  8335. UniformsLib.envmap,
  8336. UniformsLib.aomap,
  8337. UniformsLib.lightmap,
  8338. UniformsLib.emissivemap,
  8339. UniformsLib.fog,
  8340. UniformsLib.lights,
  8341. {
  8342. emissive: { value: new Color( 0x000000 ) }
  8343. }
  8344. ] ),
  8345. vertexShader: ShaderChunk.meshlambert_vert,
  8346. fragmentShader: ShaderChunk.meshlambert_frag
  8347. },
  8348. phong: {
  8349. uniforms: UniformsUtils.merge( [
  8350. UniformsLib.common,
  8351. UniformsLib.specularmap,
  8352. UniformsLib.envmap,
  8353. UniformsLib.aomap,
  8354. UniformsLib.lightmap,
  8355. UniformsLib.emissivemap,
  8356. UniformsLib.bumpmap,
  8357. UniformsLib.normalmap,
  8358. UniformsLib.displacementmap,
  8359. UniformsLib.gradientmap,
  8360. UniformsLib.fog,
  8361. UniformsLib.lights,
  8362. {
  8363. emissive: { value: new Color( 0x000000 ) },
  8364. specular: { value: new Color( 0x111111 ) },
  8365. shininess: { value: 30 }
  8366. }
  8367. ] ),
  8368. vertexShader: ShaderChunk.meshphong_vert,
  8369. fragmentShader: ShaderChunk.meshphong_frag
  8370. },
  8371. standard: {
  8372. uniforms: UniformsUtils.merge( [
  8373. UniformsLib.common,
  8374. UniformsLib.envmap,
  8375. UniformsLib.aomap,
  8376. UniformsLib.lightmap,
  8377. UniformsLib.emissivemap,
  8378. UniformsLib.bumpmap,
  8379. UniformsLib.normalmap,
  8380. UniformsLib.displacementmap,
  8381. UniformsLib.roughnessmap,
  8382. UniformsLib.metalnessmap,
  8383. UniformsLib.fog,
  8384. UniformsLib.lights,
  8385. {
  8386. emissive: { value: new Color( 0x000000 ) },
  8387. roughness: { value: 0.5 },
  8388. metalness: { value: 0.5 },
  8389. envMapIntensity: { value: 1 } // temporary
  8390. }
  8391. ] ),
  8392. vertexShader: ShaderChunk.meshphysical_vert,
  8393. fragmentShader: ShaderChunk.meshphysical_frag
  8394. },
  8395. points: {
  8396. uniforms: UniformsUtils.merge( [
  8397. UniformsLib.points,
  8398. UniformsLib.fog
  8399. ] ),
  8400. vertexShader: ShaderChunk.points_vert,
  8401. fragmentShader: ShaderChunk.points_frag
  8402. },
  8403. dashed: {
  8404. uniforms: UniformsUtils.merge( [
  8405. UniformsLib.common,
  8406. UniformsLib.fog,
  8407. {
  8408. scale: { value: 1 },
  8409. dashSize: { value: 1 },
  8410. totalSize: { value: 2 }
  8411. }
  8412. ] ),
  8413. vertexShader: ShaderChunk.linedashed_vert,
  8414. fragmentShader: ShaderChunk.linedashed_frag
  8415. },
  8416. depth: {
  8417. uniforms: UniformsUtils.merge( [
  8418. UniformsLib.common,
  8419. UniformsLib.displacementmap
  8420. ] ),
  8421. vertexShader: ShaderChunk.depth_vert,
  8422. fragmentShader: ShaderChunk.depth_frag
  8423. },
  8424. normal: {
  8425. uniforms: UniformsUtils.merge( [
  8426. UniformsLib.common,
  8427. UniformsLib.bumpmap,
  8428. UniformsLib.normalmap,
  8429. UniformsLib.displacementmap,
  8430. {
  8431. opacity: { value: 1.0 }
  8432. }
  8433. ] ),
  8434. vertexShader: ShaderChunk.normal_vert,
  8435. fragmentShader: ShaderChunk.normal_frag
  8436. },
  8437. /* -------------------------------------------------------------------------
  8438. // Cube map shader
  8439. ------------------------------------------------------------------------- */
  8440. cube: {
  8441. uniforms: {
  8442. tCube: { value: null },
  8443. tFlip: { value: - 1 },
  8444. opacity: { value: 1.0 }
  8445. },
  8446. vertexShader: ShaderChunk.cube_vert,
  8447. fragmentShader: ShaderChunk.cube_frag
  8448. },
  8449. equirect: {
  8450. uniforms: {
  8451. tEquirect: { value: null },
  8452. },
  8453. vertexShader: ShaderChunk.equirect_vert,
  8454. fragmentShader: ShaderChunk.equirect_frag
  8455. },
  8456. distanceRGBA: {
  8457. uniforms: UniformsUtils.merge( [
  8458. UniformsLib.common,
  8459. UniformsLib.displacementmap,
  8460. {
  8461. referencePosition: { value: new Vector3() },
  8462. nearDistance: { value: 1 },
  8463. farDistance: { value: 1000 }
  8464. }
  8465. ] ),
  8466. vertexShader: ShaderChunk.distanceRGBA_vert,
  8467. fragmentShader: ShaderChunk.distanceRGBA_frag
  8468. },
  8469. shadow: {
  8470. uniforms: UniformsUtils.merge( [
  8471. UniformsLib.lights,
  8472. UniformsLib.fog,
  8473. {
  8474. color: { value: new Color( 0x00000 ) },
  8475. opacity: { value: 1.0 }
  8476. },
  8477. ] ),
  8478. vertexShader: ShaderChunk.shadow_vert,
  8479. fragmentShader: ShaderChunk.shadow_frag
  8480. }
  8481. };
  8482. ShaderLib.physical = {
  8483. uniforms: UniformsUtils.merge( [
  8484. ShaderLib.standard.uniforms,
  8485. {
  8486. clearCoat: { value: 0 },
  8487. clearCoatRoughness: { value: 0 }
  8488. }
  8489. ] ),
  8490. vertexShader: ShaderChunk.meshphysical_vert,
  8491. fragmentShader: ShaderChunk.meshphysical_frag
  8492. };
  8493. /**
  8494. * @author bhouston / http://clara.io
  8495. */
  8496. function Box2( min, max ) {
  8497. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  8498. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  8499. }
  8500. Object.assign( Box2.prototype, {
  8501. set: function ( min, max ) {
  8502. this.min.copy( min );
  8503. this.max.copy( max );
  8504. return this;
  8505. },
  8506. setFromPoints: function ( points ) {
  8507. this.makeEmpty();
  8508. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8509. this.expandByPoint( points[ i ] );
  8510. }
  8511. return this;
  8512. },
  8513. setFromCenterAndSize: function () {
  8514. var v1 = new Vector2();
  8515. return function setFromCenterAndSize( center, size ) {
  8516. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  8517. this.min.copy( center ).sub( halfSize );
  8518. this.max.copy( center ).add( halfSize );
  8519. return this;
  8520. };
  8521. }(),
  8522. clone: function () {
  8523. return new this.constructor().copy( this );
  8524. },
  8525. copy: function ( box ) {
  8526. this.min.copy( box.min );
  8527. this.max.copy( box.max );
  8528. return this;
  8529. },
  8530. makeEmpty: function () {
  8531. this.min.x = this.min.y = + Infinity;
  8532. this.max.x = this.max.y = - Infinity;
  8533. return this;
  8534. },
  8535. isEmpty: function () {
  8536. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8537. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  8538. },
  8539. getCenter: function ( optionalTarget ) {
  8540. var result = optionalTarget || new Vector2();
  8541. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  8542. },
  8543. getSize: function ( optionalTarget ) {
  8544. var result = optionalTarget || new Vector2();
  8545. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  8546. },
  8547. expandByPoint: function ( point ) {
  8548. this.min.min( point );
  8549. this.max.max( point );
  8550. return this;
  8551. },
  8552. expandByVector: function ( vector ) {
  8553. this.min.sub( vector );
  8554. this.max.add( vector );
  8555. return this;
  8556. },
  8557. expandByScalar: function ( scalar ) {
  8558. this.min.addScalar( - scalar );
  8559. this.max.addScalar( scalar );
  8560. return this;
  8561. },
  8562. containsPoint: function ( point ) {
  8563. return point.x < this.min.x || point.x > this.max.x ||
  8564. point.y < this.min.y || point.y > this.max.y ? false : true;
  8565. },
  8566. containsBox: function ( box ) {
  8567. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  8568. this.min.y <= box.min.y && box.max.y <= this.max.y;
  8569. },
  8570. getParameter: function ( point, optionalTarget ) {
  8571. // This can potentially have a divide by zero if the box
  8572. // has a size dimension of 0.
  8573. var result = optionalTarget || new Vector2();
  8574. return result.set(
  8575. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  8576. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  8577. );
  8578. },
  8579. intersectsBox: function ( box ) {
  8580. // using 4 splitting planes to rule out intersections
  8581. return box.max.x < this.min.x || box.min.x > this.max.x ||
  8582. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  8583. },
  8584. clampPoint: function ( point, optionalTarget ) {
  8585. var result = optionalTarget || new Vector2();
  8586. return result.copy( point ).clamp( this.min, this.max );
  8587. },
  8588. distanceToPoint: function () {
  8589. var v1 = new Vector2();
  8590. return function distanceToPoint( point ) {
  8591. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  8592. return clampedPoint.sub( point ).length();
  8593. };
  8594. }(),
  8595. intersect: function ( box ) {
  8596. this.min.max( box.min );
  8597. this.max.min( box.max );
  8598. return this;
  8599. },
  8600. union: function ( box ) {
  8601. this.min.min( box.min );
  8602. this.max.max( box.max );
  8603. return this;
  8604. },
  8605. translate: function ( offset ) {
  8606. this.min.add( offset );
  8607. this.max.add( offset );
  8608. return this;
  8609. },
  8610. equals: function ( box ) {
  8611. return box.min.equals( this.min ) && box.max.equals( this.max );
  8612. }
  8613. } );
  8614. /**
  8615. * @author mikael emtinger / http://gomo.se/
  8616. * @author alteredq / http://alteredqualia.com/
  8617. */
  8618. function WebGLFlareRenderer( renderer, gl, state, textures, capabilities ) {
  8619. var vertexBuffer, elementBuffer;
  8620. var shader, program, attributes, uniforms;
  8621. var tempTexture, occlusionTexture;
  8622. function init() {
  8623. var vertices = new Float32Array( [
  8624. - 1, - 1, 0, 0,
  8625. 1, - 1, 1, 0,
  8626. 1, 1, 1, 1,
  8627. - 1, 1, 0, 1
  8628. ] );
  8629. var faces = new Uint16Array( [
  8630. 0, 1, 2,
  8631. 0, 2, 3
  8632. ] );
  8633. // buffers
  8634. vertexBuffer = gl.createBuffer();
  8635. elementBuffer = gl.createBuffer();
  8636. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8637. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8638. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8639. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8640. // textures
  8641. tempTexture = gl.createTexture();
  8642. occlusionTexture = gl.createTexture();
  8643. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8644. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  8645. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8646. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8647. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8648. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8649. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8650. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  8651. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8652. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8653. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8654. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8655. shader = {
  8656. vertexShader: [
  8657. 'uniform lowp int renderType;',
  8658. 'uniform vec3 screenPosition;',
  8659. 'uniform vec2 scale;',
  8660. 'uniform float rotation;',
  8661. 'uniform sampler2D occlusionMap;',
  8662. 'attribute vec2 position;',
  8663. 'attribute vec2 uv;',
  8664. 'varying vec2 vUV;',
  8665. 'varying float vVisibility;',
  8666. 'void main() {',
  8667. ' vUV = uv;',
  8668. ' vec2 pos = position;',
  8669. ' if ( renderType == 2 ) {',
  8670. ' vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );',
  8671. ' visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );',
  8672. ' visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );',
  8673. ' visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );',
  8674. ' visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );',
  8675. ' visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );',
  8676. ' visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );',
  8677. ' visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );',
  8678. ' visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );',
  8679. ' vVisibility = visibility.r / 9.0;',
  8680. ' vVisibility *= 1.0 - visibility.g / 9.0;',
  8681. ' vVisibility *= visibility.b / 9.0;',
  8682. ' vVisibility *= 1.0 - visibility.a / 9.0;',
  8683. ' pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;',
  8684. ' pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;',
  8685. ' }',
  8686. ' gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );',
  8687. '}'
  8688. ].join( '\n' ),
  8689. fragmentShader: [
  8690. 'uniform lowp int renderType;',
  8691. 'uniform sampler2D map;',
  8692. 'uniform float opacity;',
  8693. 'uniform vec3 color;',
  8694. 'varying vec2 vUV;',
  8695. 'varying float vVisibility;',
  8696. 'void main() {',
  8697. // pink square
  8698. ' if ( renderType == 0 ) {',
  8699. ' gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );',
  8700. // restore
  8701. ' } else if ( renderType == 1 ) {',
  8702. ' gl_FragColor = texture2D( map, vUV );',
  8703. // flare
  8704. ' } else {',
  8705. ' vec4 texture = texture2D( map, vUV );',
  8706. ' texture.a *= opacity * vVisibility;',
  8707. ' gl_FragColor = texture;',
  8708. ' gl_FragColor.rgb *= color;',
  8709. ' }',
  8710. '}'
  8711. ].join( '\n' )
  8712. };
  8713. program = createProgram( shader );
  8714. attributes = {
  8715. vertex: gl.getAttribLocation( program, 'position' ),
  8716. uv: gl.getAttribLocation( program, 'uv' )
  8717. };
  8718. uniforms = {
  8719. renderType: gl.getUniformLocation( program, 'renderType' ),
  8720. map: gl.getUniformLocation( program, 'map' ),
  8721. occlusionMap: gl.getUniformLocation( program, 'occlusionMap' ),
  8722. opacity: gl.getUniformLocation( program, 'opacity' ),
  8723. color: gl.getUniformLocation( program, 'color' ),
  8724. scale: gl.getUniformLocation( program, 'scale' ),
  8725. rotation: gl.getUniformLocation( program, 'rotation' ),
  8726. screenPosition: gl.getUniformLocation( program, 'screenPosition' )
  8727. };
  8728. }
  8729. /*
  8730. * Render lens flares
  8731. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  8732. * reads these back and calculates occlusion.
  8733. */
  8734. this.render = function ( flares, scene, camera, viewport ) {
  8735. if ( flares.length === 0 ) return;
  8736. var tempPosition = new Vector3();
  8737. var invAspect = viewport.w / viewport.z,
  8738. halfViewportWidth = viewport.z * 0.5,
  8739. halfViewportHeight = viewport.w * 0.5;
  8740. var size = 16 / viewport.w,
  8741. scale = new Vector2( size * invAspect, size );
  8742. var screenPosition = new Vector3( 1, 1, 0 ),
  8743. screenPositionPixels = new Vector2( 1, 1 );
  8744. var validArea = new Box2();
  8745. validArea.min.set( viewport.x, viewport.y );
  8746. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  8747. if ( program === undefined ) {
  8748. init();
  8749. }
  8750. state.useProgram( program );
  8751. state.initAttributes();
  8752. state.enableAttribute( attributes.vertex );
  8753. state.enableAttribute( attributes.uv );
  8754. state.disableUnusedAttributes();
  8755. // loop through all lens flares to update their occlusion and positions
  8756. // setup gl and common used attribs/uniforms
  8757. gl.uniform1i( uniforms.occlusionMap, 0 );
  8758. gl.uniform1i( uniforms.map, 1 );
  8759. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8760. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  8761. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8762. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8763. state.disable( gl.CULL_FACE );
  8764. state.buffers.depth.setMask( false );
  8765. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  8766. size = 16 / viewport.w;
  8767. scale.set( size * invAspect, size );
  8768. // calc object screen position
  8769. var flare = flares[ i ];
  8770. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  8771. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  8772. tempPosition.applyMatrix4( camera.projectionMatrix );
  8773. // setup arrays for gl programs
  8774. screenPosition.copy( tempPosition );
  8775. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  8776. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  8777. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  8778. // screen cull
  8779. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  8780. // save current RGB to temp texture
  8781. state.activeTexture( gl.TEXTURE0 );
  8782. state.bindTexture( gl.TEXTURE_2D, null );
  8783. state.activeTexture( gl.TEXTURE1 );
  8784. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8785. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8786. // render pink quad
  8787. gl.uniform1i( uniforms.renderType, 0 );
  8788. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8789. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8790. state.disable( gl.BLEND );
  8791. state.enable( gl.DEPTH_TEST );
  8792. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8793. // copy result to occlusionMap
  8794. state.activeTexture( gl.TEXTURE0 );
  8795. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8796. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8797. // restore graphics
  8798. gl.uniform1i( uniforms.renderType, 1 );
  8799. state.disable( gl.DEPTH_TEST );
  8800. state.activeTexture( gl.TEXTURE1 );
  8801. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8802. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8803. // update object positions
  8804. flare.positionScreen.copy( screenPosition );
  8805. if ( flare.customUpdateCallback ) {
  8806. flare.customUpdateCallback( flare );
  8807. } else {
  8808. flare.updateLensFlares();
  8809. }
  8810. // render flares
  8811. gl.uniform1i( uniforms.renderType, 2 );
  8812. state.enable( gl.BLEND );
  8813. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  8814. var sprite = flare.lensFlares[ j ];
  8815. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  8816. screenPosition.x = sprite.x;
  8817. screenPosition.y = sprite.y;
  8818. screenPosition.z = sprite.z;
  8819. size = sprite.size * sprite.scale / viewport.w;
  8820. scale.x = size * invAspect;
  8821. scale.y = size;
  8822. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8823. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8824. gl.uniform1f( uniforms.rotation, sprite.rotation );
  8825. gl.uniform1f( uniforms.opacity, sprite.opacity );
  8826. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8827. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8828. textures.setTexture2D( sprite.texture, 1 );
  8829. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8830. }
  8831. }
  8832. }
  8833. }
  8834. // restore gl
  8835. state.enable( gl.CULL_FACE );
  8836. state.enable( gl.DEPTH_TEST );
  8837. state.buffers.depth.setMask( true );
  8838. state.reset();
  8839. };
  8840. function createProgram( shader ) {
  8841. var program = gl.createProgram();
  8842. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8843. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8844. var prefix = 'precision ' + capabilities.precision + ' float;\n';
  8845. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  8846. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  8847. gl.compileShader( fragmentShader );
  8848. gl.compileShader( vertexShader );
  8849. gl.attachShader( program, fragmentShader );
  8850. gl.attachShader( program, vertexShader );
  8851. gl.linkProgram( program );
  8852. return program;
  8853. }
  8854. }
  8855. /**
  8856. * @author mrdoob / http://mrdoob.com/
  8857. */
  8858. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8859. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8860. this.needsUpdate = true;
  8861. }
  8862. CanvasTexture.prototype = Object.create( Texture.prototype );
  8863. CanvasTexture.prototype.constructor = CanvasTexture;
  8864. /**
  8865. * @author mikael emtinger / http://gomo.se/
  8866. * @author alteredq / http://alteredqualia.com/
  8867. */
  8868. function WebGLSpriteRenderer( renderer, gl, state, textures, capabilities ) {
  8869. var vertexBuffer, elementBuffer;
  8870. var program, attributes, uniforms;
  8871. var texture;
  8872. // decompose matrixWorld
  8873. var spritePosition = new Vector3();
  8874. var spriteRotation = new Quaternion();
  8875. var spriteScale = new Vector3();
  8876. function init() {
  8877. var vertices = new Float32Array( [
  8878. - 0.5, - 0.5, 0, 0,
  8879. 0.5, - 0.5, 1, 0,
  8880. 0.5, 0.5, 1, 1,
  8881. - 0.5, 0.5, 0, 1
  8882. ] );
  8883. var faces = new Uint16Array( [
  8884. 0, 1, 2,
  8885. 0, 2, 3
  8886. ] );
  8887. vertexBuffer = gl.createBuffer();
  8888. elementBuffer = gl.createBuffer();
  8889. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8890. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8891. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8892. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8893. program = createProgram();
  8894. attributes = {
  8895. position: gl.getAttribLocation( program, 'position' ),
  8896. uv: gl.getAttribLocation( program, 'uv' )
  8897. };
  8898. uniforms = {
  8899. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  8900. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  8901. rotation: gl.getUniformLocation( program, 'rotation' ),
  8902. scale: gl.getUniformLocation( program, 'scale' ),
  8903. color: gl.getUniformLocation( program, 'color' ),
  8904. map: gl.getUniformLocation( program, 'map' ),
  8905. opacity: gl.getUniformLocation( program, 'opacity' ),
  8906. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  8907. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  8908. fogType: gl.getUniformLocation( program, 'fogType' ),
  8909. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  8910. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  8911. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  8912. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  8913. fogDepth: gl.getUniformLocation( program, 'fogDepth' ),
  8914. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  8915. };
  8916. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8917. canvas.width = 8;
  8918. canvas.height = 8;
  8919. var context = canvas.getContext( '2d' );
  8920. context.fillStyle = 'white';
  8921. context.fillRect( 0, 0, 8, 8 );
  8922. texture = new CanvasTexture( canvas );
  8923. }
  8924. this.render = function ( sprites, scene, camera ) {
  8925. if ( sprites.length === 0 ) return;
  8926. // setup gl
  8927. if ( program === undefined ) {
  8928. init();
  8929. }
  8930. state.useProgram( program );
  8931. state.initAttributes();
  8932. state.enableAttribute( attributes.position );
  8933. state.enableAttribute( attributes.uv );
  8934. state.disableUnusedAttributes();
  8935. state.disable( gl.CULL_FACE );
  8936. state.enable( gl.BLEND );
  8937. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8938. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  8939. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8940. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8941. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  8942. state.activeTexture( gl.TEXTURE0 );
  8943. gl.uniform1i( uniforms.map, 0 );
  8944. var oldFogType = 0;
  8945. var sceneFogType = 0;
  8946. var fog = scene.fog;
  8947. if ( fog ) {
  8948. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  8949. if ( fog.isFog ) {
  8950. gl.uniform1f( uniforms.fogNear, fog.near );
  8951. gl.uniform1f( uniforms.fogFar, fog.far );
  8952. gl.uniform1i( uniforms.fogType, 1 );
  8953. oldFogType = 1;
  8954. sceneFogType = 1;
  8955. } else if ( fog.isFogExp2 ) {
  8956. gl.uniform1f( uniforms.fogDensity, fog.density );
  8957. gl.uniform1i( uniforms.fogType, 2 );
  8958. oldFogType = 2;
  8959. sceneFogType = 2;
  8960. }
  8961. } else {
  8962. gl.uniform1i( uniforms.fogType, 0 );
  8963. oldFogType = 0;
  8964. sceneFogType = 0;
  8965. }
  8966. // update positions and sort
  8967. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8968. var sprite = sprites[ i ];
  8969. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  8970. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  8971. }
  8972. sprites.sort( painterSortStable );
  8973. // render all sprites
  8974. var scale = [];
  8975. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8976. var sprite = sprites[ i ];
  8977. var material = sprite.material;
  8978. if ( material.visible === false ) continue;
  8979. sprite.onBeforeRender( renderer, scene, camera, undefined, material, undefined );
  8980. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  8981. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  8982. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  8983. scale[ 0 ] = spriteScale.x;
  8984. scale[ 1 ] = spriteScale.y;
  8985. var fogType = 0;
  8986. if ( scene.fog && material.fog ) {
  8987. fogType = sceneFogType;
  8988. }
  8989. if ( oldFogType !== fogType ) {
  8990. gl.uniform1i( uniforms.fogType, fogType );
  8991. oldFogType = fogType;
  8992. }
  8993. if ( material.map !== null ) {
  8994. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  8995. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  8996. } else {
  8997. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  8998. gl.uniform2f( uniforms.uvScale, 1, 1 );
  8999. }
  9000. gl.uniform1f( uniforms.opacity, material.opacity );
  9001. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  9002. gl.uniform1f( uniforms.rotation, material.rotation );
  9003. gl.uniform2fv( uniforms.scale, scale );
  9004. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha );
  9005. state.buffers.depth.setTest( material.depthTest );
  9006. state.buffers.depth.setMask( material.depthWrite );
  9007. state.buffers.color.setMask( material.colorWrite );
  9008. textures.setTexture2D( material.map || texture, 0 );
  9009. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  9010. sprite.onAfterRender( renderer, scene, camera, undefined, material, undefined );
  9011. }
  9012. // restore gl
  9013. state.enable( gl.CULL_FACE );
  9014. state.reset();
  9015. };
  9016. function createProgram() {
  9017. var program = gl.createProgram();
  9018. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  9019. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  9020. gl.shaderSource( vertexShader, [
  9021. 'precision ' + capabilities.precision + ' float;',
  9022. '#define SHADER_NAME ' + 'SpriteMaterial',
  9023. 'uniform mat4 modelViewMatrix;',
  9024. 'uniform mat4 projectionMatrix;',
  9025. 'uniform float rotation;',
  9026. 'uniform vec2 scale;',
  9027. 'uniform vec2 uvOffset;',
  9028. 'uniform vec2 uvScale;',
  9029. 'attribute vec2 position;',
  9030. 'attribute vec2 uv;',
  9031. 'varying vec2 vUV;',
  9032. 'varying float fogDepth;',
  9033. 'void main() {',
  9034. ' vUV = uvOffset + uv * uvScale;',
  9035. ' vec2 alignedPosition = position * scale;',
  9036. ' vec2 rotatedPosition;',
  9037. ' rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  9038. ' rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  9039. ' vec4 mvPosition;',
  9040. ' mvPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  9041. ' mvPosition.xy += rotatedPosition;',
  9042. ' gl_Position = projectionMatrix * mvPosition;',
  9043. ' fogDepth = - mvPosition.z;',
  9044. '}'
  9045. ].join( '\n' ) );
  9046. gl.shaderSource( fragmentShader, [
  9047. 'precision ' + capabilities.precision + ' float;',
  9048. '#define SHADER_NAME ' + 'SpriteMaterial',
  9049. 'uniform vec3 color;',
  9050. 'uniform sampler2D map;',
  9051. 'uniform float opacity;',
  9052. 'uniform int fogType;',
  9053. 'uniform vec3 fogColor;',
  9054. 'uniform float fogDensity;',
  9055. 'uniform float fogNear;',
  9056. 'uniform float fogFar;',
  9057. 'uniform float alphaTest;',
  9058. 'varying vec2 vUV;',
  9059. 'varying float fogDepth;',
  9060. 'void main() {',
  9061. ' vec4 texture = texture2D( map, vUV );',
  9062. ' gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  9063. ' if ( gl_FragColor.a < alphaTest ) discard;',
  9064. ' if ( fogType > 0 ) {',
  9065. ' float fogFactor = 0.0;',
  9066. ' if ( fogType == 1 ) {',
  9067. ' fogFactor = smoothstep( fogNear, fogFar, fogDepth );',
  9068. ' } else {',
  9069. ' const float LOG2 = 1.442695;',
  9070. ' fogFactor = exp2( - fogDensity * fogDensity * fogDepth * fogDepth * LOG2 );',
  9071. ' fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  9072. ' }',
  9073. ' gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );',
  9074. ' }',
  9075. '}'
  9076. ].join( '\n' ) );
  9077. gl.compileShader( vertexShader );
  9078. gl.compileShader( fragmentShader );
  9079. gl.attachShader( program, vertexShader );
  9080. gl.attachShader( program, fragmentShader );
  9081. gl.linkProgram( program );
  9082. return program;
  9083. }
  9084. function painterSortStable( a, b ) {
  9085. if ( a.renderOrder !== b.renderOrder ) {
  9086. return a.renderOrder - b.renderOrder;
  9087. } else if ( a.z !== b.z ) {
  9088. return b.z - a.z;
  9089. } else {
  9090. return b.id - a.id;
  9091. }
  9092. }
  9093. }
  9094. /**
  9095. * @author mrdoob / http://mrdoob.com/
  9096. * @author alteredq / http://alteredqualia.com/
  9097. */
  9098. var materialId = 0;
  9099. function Material() {
  9100. Object.defineProperty( this, 'id', { value: materialId ++ } );
  9101. this.uuid = _Math.generateUUID();
  9102. this.name = '';
  9103. this.type = 'Material';
  9104. this.fog = true;
  9105. this.lights = true;
  9106. this.blending = NormalBlending;
  9107. this.side = FrontSide;
  9108. this.flatShading = false;
  9109. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  9110. this.opacity = 1;
  9111. this.transparent = false;
  9112. this.blendSrc = SrcAlphaFactor;
  9113. this.blendDst = OneMinusSrcAlphaFactor;
  9114. this.blendEquation = AddEquation;
  9115. this.blendSrcAlpha = null;
  9116. this.blendDstAlpha = null;
  9117. this.blendEquationAlpha = null;
  9118. this.depthFunc = LessEqualDepth;
  9119. this.depthTest = true;
  9120. this.depthWrite = true;
  9121. this.clippingPlanes = null;
  9122. this.clipIntersection = false;
  9123. this.clipShadows = false;
  9124. this.colorWrite = true;
  9125. this.precision = null; // override the renderer's default precision for this material
  9126. this.polygonOffset = false;
  9127. this.polygonOffsetFactor = 0;
  9128. this.polygonOffsetUnits = 0;
  9129. this.dithering = false;
  9130. this.alphaTest = 0;
  9131. this.premultipliedAlpha = false;
  9132. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  9133. this.visible = true;
  9134. this.userData = {};
  9135. this.needsUpdate = true;
  9136. }
  9137. Material.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  9138. constructor: Material,
  9139. isMaterial: true,
  9140. onBeforeCompile: function () {},
  9141. setValues: function ( values ) {
  9142. if ( values === undefined ) return;
  9143. for ( var key in values ) {
  9144. var newValue = values[ key ];
  9145. if ( newValue === undefined ) {
  9146. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  9147. continue;
  9148. }
  9149. // for backward compatability if shading is set in the constructor
  9150. if ( key === 'shading' ) {
  9151. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  9152. this.flatShading = ( newValue === FlatShading ) ? true : false;
  9153. continue;
  9154. }
  9155. var currentValue = this[ key ];
  9156. if ( currentValue === undefined ) {
  9157. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  9158. continue;
  9159. }
  9160. if ( currentValue && currentValue.isColor ) {
  9161. currentValue.set( newValue );
  9162. } else if ( ( currentValue && currentValue.isVector3 ) && ( newValue && newValue.isVector3 ) ) {
  9163. currentValue.copy( newValue );
  9164. } else if ( key === 'overdraw' ) {
  9165. // ensure overdraw is backwards-compatible with legacy boolean type
  9166. this[ key ] = Number( newValue );
  9167. } else {
  9168. this[ key ] = newValue;
  9169. }
  9170. }
  9171. },
  9172. toJSON: function ( meta ) {
  9173. var isRoot = ( meta === undefined || typeof meta === 'string' );
  9174. if ( isRoot ) {
  9175. meta = {
  9176. textures: {},
  9177. images: {}
  9178. };
  9179. }
  9180. var data = {
  9181. metadata: {
  9182. version: 4.5,
  9183. type: 'Material',
  9184. generator: 'Material.toJSON'
  9185. }
  9186. };
  9187. // standard Material serialization
  9188. data.uuid = this.uuid;
  9189. data.type = this.type;
  9190. if ( this.name !== '' ) data.name = this.name;
  9191. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  9192. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  9193. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  9194. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  9195. if ( this.emissiveIntensity !== 1 ) data.emissiveIntensity = this.emissiveIntensity;
  9196. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  9197. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  9198. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  9199. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  9200. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  9201. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  9202. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  9203. if ( this.bumpMap && this.bumpMap.isTexture ) {
  9204. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  9205. data.bumpScale = this.bumpScale;
  9206. }
  9207. if ( this.normalMap && this.normalMap.isTexture ) {
  9208. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  9209. data.normalScale = this.normalScale.toArray();
  9210. }
  9211. if ( this.displacementMap && this.displacementMap.isTexture ) {
  9212. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  9213. data.displacementScale = this.displacementScale;
  9214. data.displacementBias = this.displacementBias;
  9215. }
  9216. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  9217. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  9218. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  9219. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  9220. if ( this.envMap && this.envMap.isTexture ) {
  9221. data.envMap = this.envMap.toJSON( meta ).uuid;
  9222. data.reflectivity = this.reflectivity; // Scale behind envMap
  9223. }
  9224. if ( this.gradientMap && this.gradientMap.isTexture ) {
  9225. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  9226. }
  9227. if ( this.size !== undefined ) data.size = this.size;
  9228. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  9229. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  9230. if ( this.flatShading === true ) data.flatShading = this.flatShading;
  9231. if ( this.side !== FrontSide ) data.side = this.side;
  9232. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  9233. if ( this.opacity < 1 ) data.opacity = this.opacity;
  9234. if ( this.transparent === true ) data.transparent = this.transparent;
  9235. data.depthFunc = this.depthFunc;
  9236. data.depthTest = this.depthTest;
  9237. data.depthWrite = this.depthWrite;
  9238. // rotation (SpriteMaterial)
  9239. if ( this.rotation !== 0 ) data.rotation = this.rotation;
  9240. if ( this.linewidth !== 1 ) data.linewidth = this.linewidth;
  9241. if ( this.dashSize !== undefined ) data.dashSize = this.dashSize;
  9242. if ( this.gapSize !== undefined ) data.gapSize = this.gapSize;
  9243. if ( this.scale !== undefined ) data.scale = this.scale;
  9244. if ( this.dithering === true ) data.dithering = true;
  9245. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  9246. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  9247. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  9248. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  9249. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  9250. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  9251. if ( this.morphTargets === true ) data.morphTargets = true;
  9252. if ( this.skinning === true ) data.skinning = true;
  9253. if ( this.visible === false ) data.visible = false;
  9254. if ( JSON.stringify( this.userData ) !== '{}' ) data.userData = this.userData;
  9255. // TODO: Copied from Object3D.toJSON
  9256. function extractFromCache( cache ) {
  9257. var values = [];
  9258. for ( var key in cache ) {
  9259. var data = cache[ key ];
  9260. delete data.metadata;
  9261. values.push( data );
  9262. }
  9263. return values;
  9264. }
  9265. if ( isRoot ) {
  9266. var textures = extractFromCache( meta.textures );
  9267. var images = extractFromCache( meta.images );
  9268. if ( textures.length > 0 ) data.textures = textures;
  9269. if ( images.length > 0 ) data.images = images;
  9270. }
  9271. return data;
  9272. },
  9273. clone: function () {
  9274. return new this.constructor().copy( this );
  9275. },
  9276. copy: function ( source ) {
  9277. this.name = source.name;
  9278. this.fog = source.fog;
  9279. this.lights = source.lights;
  9280. this.blending = source.blending;
  9281. this.side = source.side;
  9282. this.flatShading = source.flatShading;
  9283. this.vertexColors = source.vertexColors;
  9284. this.opacity = source.opacity;
  9285. this.transparent = source.transparent;
  9286. this.blendSrc = source.blendSrc;
  9287. this.blendDst = source.blendDst;
  9288. this.blendEquation = source.blendEquation;
  9289. this.blendSrcAlpha = source.blendSrcAlpha;
  9290. this.blendDstAlpha = source.blendDstAlpha;
  9291. this.blendEquationAlpha = source.blendEquationAlpha;
  9292. this.depthFunc = source.depthFunc;
  9293. this.depthTest = source.depthTest;
  9294. this.depthWrite = source.depthWrite;
  9295. this.colorWrite = source.colorWrite;
  9296. this.precision = source.precision;
  9297. this.polygonOffset = source.polygonOffset;
  9298. this.polygonOffsetFactor = source.polygonOffsetFactor;
  9299. this.polygonOffsetUnits = source.polygonOffsetUnits;
  9300. this.dithering = source.dithering;
  9301. this.alphaTest = source.alphaTest;
  9302. this.premultipliedAlpha = source.premultipliedAlpha;
  9303. this.overdraw = source.overdraw;
  9304. this.visible = source.visible;
  9305. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  9306. this.clipShadows = source.clipShadows;
  9307. this.clipIntersection = source.clipIntersection;
  9308. var srcPlanes = source.clippingPlanes,
  9309. dstPlanes = null;
  9310. if ( srcPlanes !== null ) {
  9311. var n = srcPlanes.length;
  9312. dstPlanes = new Array( n );
  9313. for ( var i = 0; i !== n; ++ i )
  9314. dstPlanes[ i ] = srcPlanes[ i ].clone();
  9315. }
  9316. this.clippingPlanes = dstPlanes;
  9317. return this;
  9318. },
  9319. dispose: function () {
  9320. this.dispatchEvent( { type: 'dispose' } );
  9321. }
  9322. } );
  9323. /**
  9324. * @author mrdoob / http://mrdoob.com/
  9325. * @author alteredq / http://alteredqualia.com/
  9326. * @author bhouston / https://clara.io
  9327. * @author WestLangley / http://github.com/WestLangley
  9328. *
  9329. * parameters = {
  9330. *
  9331. * opacity: <float>,
  9332. *
  9333. * map: new THREE.Texture( <Image> ),
  9334. *
  9335. * alphaMap: new THREE.Texture( <Image> ),
  9336. *
  9337. * displacementMap: new THREE.Texture( <Image> ),
  9338. * displacementScale: <float>,
  9339. * displacementBias: <float>,
  9340. *
  9341. * wireframe: <boolean>,
  9342. * wireframeLinewidth: <float>
  9343. * }
  9344. */
  9345. function MeshDepthMaterial( parameters ) {
  9346. Material.call( this );
  9347. this.type = 'MeshDepthMaterial';
  9348. this.depthPacking = BasicDepthPacking;
  9349. this.skinning = false;
  9350. this.morphTargets = false;
  9351. this.map = null;
  9352. this.alphaMap = null;
  9353. this.displacementMap = null;
  9354. this.displacementScale = 1;
  9355. this.displacementBias = 0;
  9356. this.wireframe = false;
  9357. this.wireframeLinewidth = 1;
  9358. this.fog = false;
  9359. this.lights = false;
  9360. this.setValues( parameters );
  9361. }
  9362. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  9363. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  9364. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  9365. MeshDepthMaterial.prototype.copy = function ( source ) {
  9366. Material.prototype.copy.call( this, source );
  9367. this.depthPacking = source.depthPacking;
  9368. this.skinning = source.skinning;
  9369. this.morphTargets = source.morphTargets;
  9370. this.map = source.map;
  9371. this.alphaMap = source.alphaMap;
  9372. this.displacementMap = source.displacementMap;
  9373. this.displacementScale = source.displacementScale;
  9374. this.displacementBias = source.displacementBias;
  9375. this.wireframe = source.wireframe;
  9376. this.wireframeLinewidth = source.wireframeLinewidth;
  9377. return this;
  9378. };
  9379. /**
  9380. * @author WestLangley / http://github.com/WestLangley
  9381. *
  9382. * parameters = {
  9383. *
  9384. * referencePosition: <float>,
  9385. * nearDistance: <float>,
  9386. * farDistance: <float>,
  9387. *
  9388. * skinning: <bool>,
  9389. * morphTargets: <bool>,
  9390. *
  9391. * map: new THREE.Texture( <Image> ),
  9392. *
  9393. * alphaMap: new THREE.Texture( <Image> ),
  9394. *
  9395. * displacementMap: new THREE.Texture( <Image> ),
  9396. * displacementScale: <float>,
  9397. * displacementBias: <float>
  9398. *
  9399. * }
  9400. */
  9401. function MeshDistanceMaterial( parameters ) {
  9402. Material.call( this );
  9403. this.type = 'MeshDistanceMaterial';
  9404. this.referencePosition = new Vector3();
  9405. this.nearDistance = 1;
  9406. this.farDistance = 1000;
  9407. this.skinning = false;
  9408. this.morphTargets = false;
  9409. this.map = null;
  9410. this.alphaMap = null;
  9411. this.displacementMap = null;
  9412. this.displacementScale = 1;
  9413. this.displacementBias = 0;
  9414. this.fog = false;
  9415. this.lights = false;
  9416. this.setValues( parameters );
  9417. }
  9418. MeshDistanceMaterial.prototype = Object.create( Material.prototype );
  9419. MeshDistanceMaterial.prototype.constructor = MeshDistanceMaterial;
  9420. MeshDistanceMaterial.prototype.isMeshDistanceMaterial = true;
  9421. MeshDistanceMaterial.prototype.copy = function ( source ) {
  9422. Material.prototype.copy.call( this, source );
  9423. this.referencePosition.copy( source.referencePosition );
  9424. this.nearDistance = source.nearDistance;
  9425. this.farDistance = source.farDistance;
  9426. this.skinning = source.skinning;
  9427. this.morphTargets = source.morphTargets;
  9428. this.map = source.map;
  9429. this.alphaMap = source.alphaMap;
  9430. this.displacementMap = source.displacementMap;
  9431. this.displacementScale = source.displacementScale;
  9432. this.displacementBias = source.displacementBias;
  9433. return this;
  9434. };
  9435. /**
  9436. * @author bhouston / http://clara.io
  9437. * @author WestLangley / http://github.com/WestLangley
  9438. */
  9439. function Box3( min, max ) {
  9440. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9441. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9442. }
  9443. Object.assign( Box3.prototype, {
  9444. isBox3: true,
  9445. set: function ( min, max ) {
  9446. this.min.copy( min );
  9447. this.max.copy( max );
  9448. return this;
  9449. },
  9450. setFromArray: function ( array ) {
  9451. var minX = + Infinity;
  9452. var minY = + Infinity;
  9453. var minZ = + Infinity;
  9454. var maxX = - Infinity;
  9455. var maxY = - Infinity;
  9456. var maxZ = - Infinity;
  9457. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9458. var x = array[ i ];
  9459. var y = array[ i + 1 ];
  9460. var z = array[ i + 2 ];
  9461. if ( x < minX ) minX = x;
  9462. if ( y < minY ) minY = y;
  9463. if ( z < minZ ) minZ = z;
  9464. if ( x > maxX ) maxX = x;
  9465. if ( y > maxY ) maxY = y;
  9466. if ( z > maxZ ) maxZ = z;
  9467. }
  9468. this.min.set( minX, minY, minZ );
  9469. this.max.set( maxX, maxY, maxZ );
  9470. return this;
  9471. },
  9472. setFromBufferAttribute: function ( attribute ) {
  9473. var minX = + Infinity;
  9474. var minY = + Infinity;
  9475. var minZ = + Infinity;
  9476. var maxX = - Infinity;
  9477. var maxY = - Infinity;
  9478. var maxZ = - Infinity;
  9479. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9480. var x = attribute.getX( i );
  9481. var y = attribute.getY( i );
  9482. var z = attribute.getZ( i );
  9483. if ( x < minX ) minX = x;
  9484. if ( y < minY ) minY = y;
  9485. if ( z < minZ ) minZ = z;
  9486. if ( x > maxX ) maxX = x;
  9487. if ( y > maxY ) maxY = y;
  9488. if ( z > maxZ ) maxZ = z;
  9489. }
  9490. this.min.set( minX, minY, minZ );
  9491. this.max.set( maxX, maxY, maxZ );
  9492. return this;
  9493. },
  9494. setFromPoints: function ( points ) {
  9495. this.makeEmpty();
  9496. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9497. this.expandByPoint( points[ i ] );
  9498. }
  9499. return this;
  9500. },
  9501. setFromCenterAndSize: function () {
  9502. var v1 = new Vector3();
  9503. return function setFromCenterAndSize( center, size ) {
  9504. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  9505. this.min.copy( center ).sub( halfSize );
  9506. this.max.copy( center ).add( halfSize );
  9507. return this;
  9508. };
  9509. }(),
  9510. setFromObject: function ( object ) {
  9511. this.makeEmpty();
  9512. return this.expandByObject( object );
  9513. },
  9514. clone: function () {
  9515. return new this.constructor().copy( this );
  9516. },
  9517. copy: function ( box ) {
  9518. this.min.copy( box.min );
  9519. this.max.copy( box.max );
  9520. return this;
  9521. },
  9522. makeEmpty: function () {
  9523. this.min.x = this.min.y = this.min.z = + Infinity;
  9524. this.max.x = this.max.y = this.max.z = - Infinity;
  9525. return this;
  9526. },
  9527. isEmpty: function () {
  9528. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9529. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9530. },
  9531. getCenter: function ( optionalTarget ) {
  9532. var result = optionalTarget || new Vector3();
  9533. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9534. },
  9535. getSize: function ( optionalTarget ) {
  9536. var result = optionalTarget || new Vector3();
  9537. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  9538. },
  9539. expandByPoint: function ( point ) {
  9540. this.min.min( point );
  9541. this.max.max( point );
  9542. return this;
  9543. },
  9544. expandByVector: function ( vector ) {
  9545. this.min.sub( vector );
  9546. this.max.add( vector );
  9547. return this;
  9548. },
  9549. expandByScalar: function ( scalar ) {
  9550. this.min.addScalar( - scalar );
  9551. this.max.addScalar( scalar );
  9552. return this;
  9553. },
  9554. expandByObject: function () {
  9555. // Computes the world-axis-aligned bounding box of an object (including its children),
  9556. // accounting for both the object's, and children's, world transforms
  9557. var scope, i, l;
  9558. var v1 = new Vector3();
  9559. function traverse( node ) {
  9560. var geometry = node.geometry;
  9561. if ( geometry !== undefined ) {
  9562. if ( geometry.isGeometry ) {
  9563. var vertices = geometry.vertices;
  9564. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  9565. v1.copy( vertices[ i ] );
  9566. v1.applyMatrix4( node.matrixWorld );
  9567. scope.expandByPoint( v1 );
  9568. }
  9569. } else if ( geometry.isBufferGeometry ) {
  9570. var attribute = geometry.attributes.position;
  9571. if ( attribute !== undefined ) {
  9572. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  9573. v1.fromBufferAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  9574. scope.expandByPoint( v1 );
  9575. }
  9576. }
  9577. }
  9578. }
  9579. }
  9580. return function expandByObject( object ) {
  9581. scope = this;
  9582. object.updateMatrixWorld( true );
  9583. object.traverse( traverse );
  9584. return this;
  9585. };
  9586. }(),
  9587. containsPoint: function ( point ) {
  9588. return point.x < this.min.x || point.x > this.max.x ||
  9589. point.y < this.min.y || point.y > this.max.y ||
  9590. point.z < this.min.z || point.z > this.max.z ? false : true;
  9591. },
  9592. containsBox: function ( box ) {
  9593. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9594. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9595. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9596. },
  9597. getParameter: function ( point, optionalTarget ) {
  9598. // This can potentially have a divide by zero if the box
  9599. // has a size dimension of 0.
  9600. var result = optionalTarget || new Vector3();
  9601. return result.set(
  9602. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9603. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9604. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9605. );
  9606. },
  9607. intersectsBox: function ( box ) {
  9608. // using 6 splitting planes to rule out intersections.
  9609. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9610. box.max.y < this.min.y || box.min.y > this.max.y ||
  9611. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9612. },
  9613. intersectsSphere: ( function () {
  9614. var closestPoint = new Vector3();
  9615. return function intersectsSphere( sphere ) {
  9616. // Find the point on the AABB closest to the sphere center.
  9617. this.clampPoint( sphere.center, closestPoint );
  9618. // If that point is inside the sphere, the AABB and sphere intersect.
  9619. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9620. };
  9621. } )(),
  9622. intersectsPlane: function ( plane ) {
  9623. // We compute the minimum and maximum dot product values. If those values
  9624. // are on the same side (back or front) of the plane, then there is no intersection.
  9625. var min, max;
  9626. if ( plane.normal.x > 0 ) {
  9627. min = plane.normal.x * this.min.x;
  9628. max = plane.normal.x * this.max.x;
  9629. } else {
  9630. min = plane.normal.x * this.max.x;
  9631. max = plane.normal.x * this.min.x;
  9632. }
  9633. if ( plane.normal.y > 0 ) {
  9634. min += plane.normal.y * this.min.y;
  9635. max += plane.normal.y * this.max.y;
  9636. } else {
  9637. min += plane.normal.y * this.max.y;
  9638. max += plane.normal.y * this.min.y;
  9639. }
  9640. if ( plane.normal.z > 0 ) {
  9641. min += plane.normal.z * this.min.z;
  9642. max += plane.normal.z * this.max.z;
  9643. } else {
  9644. min += plane.normal.z * this.max.z;
  9645. max += plane.normal.z * this.min.z;
  9646. }
  9647. return ( min <= plane.constant && max >= plane.constant );
  9648. },
  9649. clampPoint: function ( point, optionalTarget ) {
  9650. var result = optionalTarget || new Vector3();
  9651. return result.copy( point ).clamp( this.min, this.max );
  9652. },
  9653. distanceToPoint: function () {
  9654. var v1 = new Vector3();
  9655. return function distanceToPoint( point ) {
  9656. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9657. return clampedPoint.sub( point ).length();
  9658. };
  9659. }(),
  9660. getBoundingSphere: function () {
  9661. var v1 = new Vector3();
  9662. return function getBoundingSphere( optionalTarget ) {
  9663. var result = optionalTarget || new Sphere();
  9664. this.getCenter( result.center );
  9665. result.radius = this.getSize( v1 ).length() * 0.5;
  9666. return result;
  9667. };
  9668. }(),
  9669. intersect: function ( box ) {
  9670. this.min.max( box.min );
  9671. this.max.min( box.max );
  9672. // 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.
  9673. if ( this.isEmpty() ) this.makeEmpty();
  9674. return this;
  9675. },
  9676. union: function ( box ) {
  9677. this.min.min( box.min );
  9678. this.max.max( box.max );
  9679. return this;
  9680. },
  9681. applyMatrix4: function () {
  9682. var points = [
  9683. new Vector3(),
  9684. new Vector3(),
  9685. new Vector3(),
  9686. new Vector3(),
  9687. new Vector3(),
  9688. new Vector3(),
  9689. new Vector3(),
  9690. new Vector3()
  9691. ];
  9692. return function applyMatrix4( matrix ) {
  9693. // transform of empty box is an empty box.
  9694. if ( this.isEmpty() ) return this;
  9695. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9696. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9697. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9698. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9699. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9700. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9701. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9702. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9703. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9704. this.setFromPoints( points );
  9705. return this;
  9706. };
  9707. }(),
  9708. translate: function ( offset ) {
  9709. this.min.add( offset );
  9710. this.max.add( offset );
  9711. return this;
  9712. },
  9713. equals: function ( box ) {
  9714. return box.min.equals( this.min ) && box.max.equals( this.max );
  9715. }
  9716. } );
  9717. /**
  9718. * @author bhouston / http://clara.io
  9719. * @author mrdoob / http://mrdoob.com/
  9720. */
  9721. function Sphere( center, radius ) {
  9722. this.center = ( center !== undefined ) ? center : new Vector3();
  9723. this.radius = ( radius !== undefined ) ? radius : 0;
  9724. }
  9725. Object.assign( Sphere.prototype, {
  9726. set: function ( center, radius ) {
  9727. this.center.copy( center );
  9728. this.radius = radius;
  9729. return this;
  9730. },
  9731. setFromPoints: function () {
  9732. var box = new Box3();
  9733. return function setFromPoints( points, optionalCenter ) {
  9734. var center = this.center;
  9735. if ( optionalCenter !== undefined ) {
  9736. center.copy( optionalCenter );
  9737. } else {
  9738. box.setFromPoints( points ).getCenter( center );
  9739. }
  9740. var maxRadiusSq = 0;
  9741. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9742. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9743. }
  9744. this.radius = Math.sqrt( maxRadiusSq );
  9745. return this;
  9746. };
  9747. }(),
  9748. clone: function () {
  9749. return new this.constructor().copy( this );
  9750. },
  9751. copy: function ( sphere ) {
  9752. this.center.copy( sphere.center );
  9753. this.radius = sphere.radius;
  9754. return this;
  9755. },
  9756. empty: function () {
  9757. return ( this.radius <= 0 );
  9758. },
  9759. containsPoint: function ( point ) {
  9760. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9761. },
  9762. distanceToPoint: function ( point ) {
  9763. return ( point.distanceTo( this.center ) - this.radius );
  9764. },
  9765. intersectsSphere: function ( sphere ) {
  9766. var radiusSum = this.radius + sphere.radius;
  9767. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9768. },
  9769. intersectsBox: function ( box ) {
  9770. return box.intersectsSphere( this );
  9771. },
  9772. intersectsPlane: function ( plane ) {
  9773. return Math.abs( plane.distanceToPoint( this.center ) ) <= this.radius;
  9774. },
  9775. clampPoint: function ( point, optionalTarget ) {
  9776. var deltaLengthSq = this.center.distanceToSquared( point );
  9777. var result = optionalTarget || new Vector3();
  9778. result.copy( point );
  9779. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9780. result.sub( this.center ).normalize();
  9781. result.multiplyScalar( this.radius ).add( this.center );
  9782. }
  9783. return result;
  9784. },
  9785. getBoundingBox: function ( optionalTarget ) {
  9786. var box = optionalTarget || new Box3();
  9787. box.set( this.center, this.center );
  9788. box.expandByScalar( this.radius );
  9789. return box;
  9790. },
  9791. applyMatrix4: function ( matrix ) {
  9792. this.center.applyMatrix4( matrix );
  9793. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9794. return this;
  9795. },
  9796. translate: function ( offset ) {
  9797. this.center.add( offset );
  9798. return this;
  9799. },
  9800. equals: function ( sphere ) {
  9801. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9802. }
  9803. } );
  9804. /**
  9805. * @author bhouston / http://clara.io
  9806. */
  9807. function Plane( normal, constant ) {
  9808. // normal is assumed to be normalized
  9809. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9810. this.constant = ( constant !== undefined ) ? constant : 0;
  9811. }
  9812. Object.assign( Plane.prototype, {
  9813. set: function ( normal, constant ) {
  9814. this.normal.copy( normal );
  9815. this.constant = constant;
  9816. return this;
  9817. },
  9818. setComponents: function ( x, y, z, w ) {
  9819. this.normal.set( x, y, z );
  9820. this.constant = w;
  9821. return this;
  9822. },
  9823. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9824. this.normal.copy( normal );
  9825. this.constant = - point.dot( this.normal );
  9826. return this;
  9827. },
  9828. setFromCoplanarPoints: function () {
  9829. var v1 = new Vector3();
  9830. var v2 = new Vector3();
  9831. return function setFromCoplanarPoints( a, b, c ) {
  9832. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9833. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9834. this.setFromNormalAndCoplanarPoint( normal, a );
  9835. return this;
  9836. };
  9837. }(),
  9838. clone: function () {
  9839. return new this.constructor().copy( this );
  9840. },
  9841. copy: function ( plane ) {
  9842. this.normal.copy( plane.normal );
  9843. this.constant = plane.constant;
  9844. return this;
  9845. },
  9846. normalize: function () {
  9847. // Note: will lead to a divide by zero if the plane is invalid.
  9848. var inverseNormalLength = 1.0 / this.normal.length();
  9849. this.normal.multiplyScalar( inverseNormalLength );
  9850. this.constant *= inverseNormalLength;
  9851. return this;
  9852. },
  9853. negate: function () {
  9854. this.constant *= - 1;
  9855. this.normal.negate();
  9856. return this;
  9857. },
  9858. distanceToPoint: function ( point ) {
  9859. return this.normal.dot( point ) + this.constant;
  9860. },
  9861. distanceToSphere: function ( sphere ) {
  9862. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9863. },
  9864. projectPoint: function ( point, optionalTarget ) {
  9865. var result = optionalTarget || new Vector3();
  9866. return result.copy( this.normal ).multiplyScalar( - this.distanceToPoint( point ) ).add( point );
  9867. },
  9868. intersectLine: function () {
  9869. var v1 = new Vector3();
  9870. return function intersectLine( line, optionalTarget ) {
  9871. var result = optionalTarget || new Vector3();
  9872. var direction = line.delta( v1 );
  9873. var denominator = this.normal.dot( direction );
  9874. if ( denominator === 0 ) {
  9875. // line is coplanar, return origin
  9876. if ( this.distanceToPoint( line.start ) === 0 ) {
  9877. return result.copy( line.start );
  9878. }
  9879. // Unsure if this is the correct method to handle this case.
  9880. return undefined;
  9881. }
  9882. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9883. if ( t < 0 || t > 1 ) {
  9884. return undefined;
  9885. }
  9886. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9887. };
  9888. }(),
  9889. intersectsLine: function ( line ) {
  9890. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9891. var startSign = this.distanceToPoint( line.start );
  9892. var endSign = this.distanceToPoint( line.end );
  9893. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9894. },
  9895. intersectsBox: function ( box ) {
  9896. return box.intersectsPlane( this );
  9897. },
  9898. intersectsSphere: function ( sphere ) {
  9899. return sphere.intersectsPlane( this );
  9900. },
  9901. coplanarPoint: function ( optionalTarget ) {
  9902. var result = optionalTarget || new Vector3();
  9903. return result.copy( this.normal ).multiplyScalar( - this.constant );
  9904. },
  9905. applyMatrix4: function () {
  9906. var v1 = new Vector3();
  9907. var m1 = new Matrix3();
  9908. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  9909. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  9910. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  9911. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9912. this.constant = - referencePoint.dot( normal );
  9913. return this;
  9914. };
  9915. }(),
  9916. translate: function ( offset ) {
  9917. this.constant -= offset.dot( this.normal );
  9918. return this;
  9919. },
  9920. equals: function ( plane ) {
  9921. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9922. }
  9923. } );
  9924. /**
  9925. * @author mrdoob / http://mrdoob.com/
  9926. * @author alteredq / http://alteredqualia.com/
  9927. * @author bhouston / http://clara.io
  9928. */
  9929. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  9930. this.planes = [
  9931. ( p0 !== undefined ) ? p0 : new Plane(),
  9932. ( p1 !== undefined ) ? p1 : new Plane(),
  9933. ( p2 !== undefined ) ? p2 : new Plane(),
  9934. ( p3 !== undefined ) ? p3 : new Plane(),
  9935. ( p4 !== undefined ) ? p4 : new Plane(),
  9936. ( p5 !== undefined ) ? p5 : new Plane()
  9937. ];
  9938. }
  9939. Object.assign( Frustum.prototype, {
  9940. set: function ( p0, p1, p2, p3, p4, p5 ) {
  9941. var planes = this.planes;
  9942. planes[ 0 ].copy( p0 );
  9943. planes[ 1 ].copy( p1 );
  9944. planes[ 2 ].copy( p2 );
  9945. planes[ 3 ].copy( p3 );
  9946. planes[ 4 ].copy( p4 );
  9947. planes[ 5 ].copy( p5 );
  9948. return this;
  9949. },
  9950. clone: function () {
  9951. return new this.constructor().copy( this );
  9952. },
  9953. copy: function ( frustum ) {
  9954. var planes = this.planes;
  9955. for ( var i = 0; i < 6; i ++ ) {
  9956. planes[ i ].copy( frustum.planes[ i ] );
  9957. }
  9958. return this;
  9959. },
  9960. setFromMatrix: function ( m ) {
  9961. var planes = this.planes;
  9962. var me = m.elements;
  9963. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9964. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9965. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9966. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9967. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9968. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9969. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9970. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9971. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9972. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9973. return this;
  9974. },
  9975. intersectsObject: function () {
  9976. var sphere = new Sphere();
  9977. return function intersectsObject( object ) {
  9978. var geometry = object.geometry;
  9979. if ( geometry.boundingSphere === null )
  9980. geometry.computeBoundingSphere();
  9981. sphere.copy( geometry.boundingSphere )
  9982. .applyMatrix4( object.matrixWorld );
  9983. return this.intersectsSphere( sphere );
  9984. };
  9985. }(),
  9986. intersectsSprite: function () {
  9987. var sphere = new Sphere();
  9988. return function intersectsSprite( sprite ) {
  9989. sphere.center.set( 0, 0, 0 );
  9990. sphere.radius = 0.7071067811865476;
  9991. sphere.applyMatrix4( sprite.matrixWorld );
  9992. return this.intersectsSphere( sphere );
  9993. };
  9994. }(),
  9995. intersectsSphere: function ( sphere ) {
  9996. var planes = this.planes;
  9997. var center = sphere.center;
  9998. var negRadius = - sphere.radius;
  9999. for ( var i = 0; i < 6; i ++ ) {
  10000. var distance = planes[ i ].distanceToPoint( center );
  10001. if ( distance < negRadius ) {
  10002. return false;
  10003. }
  10004. }
  10005. return true;
  10006. },
  10007. intersectsBox: function () {
  10008. var p1 = new Vector3(),
  10009. p2 = new Vector3();
  10010. return function intersectsBox( box ) {
  10011. var planes = this.planes;
  10012. for ( var i = 0; i < 6; i ++ ) {
  10013. var plane = planes[ i ];
  10014. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  10015. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  10016. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  10017. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  10018. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  10019. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  10020. var d1 = plane.distanceToPoint( p1 );
  10021. var d2 = plane.distanceToPoint( p2 );
  10022. // if both outside plane, no intersection
  10023. if ( d1 < 0 && d2 < 0 ) {
  10024. return false;
  10025. }
  10026. }
  10027. return true;
  10028. };
  10029. }(),
  10030. containsPoint: function ( point ) {
  10031. var planes = this.planes;
  10032. for ( var i = 0; i < 6; i ++ ) {
  10033. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  10034. return false;
  10035. }
  10036. }
  10037. return true;
  10038. }
  10039. } );
  10040. /**
  10041. * @author alteredq / http://alteredqualia.com/
  10042. * @author mrdoob / http://mrdoob.com/
  10043. */
  10044. function WebGLShadowMap( _renderer, _objects, maxTextureSize ) {
  10045. var _frustum = new Frustum(),
  10046. _projScreenMatrix = new Matrix4(),
  10047. _shadowMapSize = new Vector2(),
  10048. _maxShadowMapSize = new Vector2( maxTextureSize, maxTextureSize ),
  10049. _lookTarget = new Vector3(),
  10050. _lightPositionWorld = new Vector3(),
  10051. _MorphingFlag = 1,
  10052. _SkinningFlag = 2,
  10053. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  10054. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  10055. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  10056. _materialCache = {};
  10057. var cubeDirections = [
  10058. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  10059. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  10060. ];
  10061. var cubeUps = [
  10062. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  10063. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  10064. ];
  10065. var cube2DViewPorts = [
  10066. new Vector4(), new Vector4(), new Vector4(),
  10067. new Vector4(), new Vector4(), new Vector4()
  10068. ];
  10069. // init
  10070. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  10071. var useMorphing = ( i & _MorphingFlag ) !== 0;
  10072. var useSkinning = ( i & _SkinningFlag ) !== 0;
  10073. var depthMaterial = new MeshDepthMaterial( {
  10074. depthPacking: RGBADepthPacking,
  10075. morphTargets: useMorphing,
  10076. skinning: useSkinning
  10077. } );
  10078. _depthMaterials[ i ] = depthMaterial;
  10079. //
  10080. var distanceMaterial = new MeshDistanceMaterial( {
  10081. morphTargets: useMorphing,
  10082. skinning: useSkinning
  10083. } );
  10084. _distanceMaterials[ i ] = distanceMaterial;
  10085. }
  10086. //
  10087. var scope = this;
  10088. this.enabled = false;
  10089. this.autoUpdate = true;
  10090. this.needsUpdate = false;
  10091. this.type = PCFShadowMap;
  10092. this.renderReverseSided = true;
  10093. this.renderSingleSided = true;
  10094. this.render = function ( lights, scene, camera ) {
  10095. if ( scope.enabled === false ) return;
  10096. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  10097. if ( lights.length === 0 ) return;
  10098. // TODO Clean up (needed in case of contextlost)
  10099. var _gl = _renderer.context;
  10100. var _state = _renderer.state;
  10101. // Set GL state for depth map.
  10102. _state.disable( _gl.BLEND );
  10103. _state.buffers.color.setClear( 1, 1, 1, 1 );
  10104. _state.buffers.depth.setTest( true );
  10105. _state.setScissorTest( false );
  10106. // render depth map
  10107. var faceCount;
  10108. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  10109. var light = lights[ i ];
  10110. var shadow = light.shadow;
  10111. var isPointLight = light && light.isPointLight;
  10112. if ( shadow === undefined ) {
  10113. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  10114. continue;
  10115. }
  10116. var shadowCamera = shadow.camera;
  10117. _shadowMapSize.copy( shadow.mapSize );
  10118. _shadowMapSize.min( _maxShadowMapSize );
  10119. if ( isPointLight ) {
  10120. var vpWidth = _shadowMapSize.x;
  10121. var vpHeight = _shadowMapSize.y;
  10122. // These viewports map a cube-map onto a 2D texture with the
  10123. // following orientation:
  10124. //
  10125. // xzXZ
  10126. // y Y
  10127. //
  10128. // X - Positive x direction
  10129. // x - Negative x direction
  10130. // Y - Positive y direction
  10131. // y - Negative y direction
  10132. // Z - Positive z direction
  10133. // z - Negative z direction
  10134. // positive X
  10135. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  10136. // negative X
  10137. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  10138. // positive Z
  10139. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  10140. // negative Z
  10141. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  10142. // positive Y
  10143. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  10144. // negative Y
  10145. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  10146. _shadowMapSize.x *= 4.0;
  10147. _shadowMapSize.y *= 2.0;
  10148. }
  10149. if ( shadow.map === null ) {
  10150. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  10151. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  10152. shadow.map.texture.name = light.name + ".shadowMap";
  10153. shadowCamera.updateProjectionMatrix();
  10154. }
  10155. if ( shadow.isSpotLightShadow ) {
  10156. shadow.update( light );
  10157. }
  10158. var shadowMap = shadow.map;
  10159. var shadowMatrix = shadow.matrix;
  10160. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  10161. shadowCamera.position.copy( _lightPositionWorld );
  10162. if ( isPointLight ) {
  10163. faceCount = 6;
  10164. // for point lights we set the shadow matrix to be a translation-only matrix
  10165. // equal to inverse of the light's position
  10166. shadowMatrix.makeTranslation( - _lightPositionWorld.x, - _lightPositionWorld.y, - _lightPositionWorld.z );
  10167. } else {
  10168. faceCount = 1;
  10169. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  10170. shadowCamera.lookAt( _lookTarget );
  10171. shadowCamera.updateMatrixWorld();
  10172. // compute shadow matrix
  10173. shadowMatrix.set(
  10174. 0.5, 0.0, 0.0, 0.5,
  10175. 0.0, 0.5, 0.0, 0.5,
  10176. 0.0, 0.0, 0.5, 0.5,
  10177. 0.0, 0.0, 0.0, 1.0
  10178. );
  10179. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  10180. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  10181. }
  10182. _renderer.setRenderTarget( shadowMap );
  10183. _renderer.clear();
  10184. // render shadow map for each cube face (if omni-directional) or
  10185. // run a single pass if not
  10186. for ( var face = 0; face < faceCount; face ++ ) {
  10187. if ( isPointLight ) {
  10188. _lookTarget.copy( shadowCamera.position );
  10189. _lookTarget.add( cubeDirections[ face ] );
  10190. shadowCamera.up.copy( cubeUps[ face ] );
  10191. shadowCamera.lookAt( _lookTarget );
  10192. shadowCamera.updateMatrixWorld();
  10193. var vpDimensions = cube2DViewPorts[ face ];
  10194. _state.viewport( vpDimensions );
  10195. }
  10196. // update camera matrices and frustum
  10197. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  10198. _frustum.setFromMatrix( _projScreenMatrix );
  10199. // set object matrices & frustum culling
  10200. renderObject( scene, camera, shadowCamera, isPointLight );
  10201. }
  10202. }
  10203. scope.needsUpdate = false;
  10204. };
  10205. function getDepthMaterial( object, material, isPointLight, lightPositionWorld, shadowCameraNear, shadowCameraFar ) {
  10206. var geometry = object.geometry;
  10207. var result = null;
  10208. var materialVariants = _depthMaterials;
  10209. var customMaterial = object.customDepthMaterial;
  10210. if ( isPointLight ) {
  10211. materialVariants = _distanceMaterials;
  10212. customMaterial = object.customDistanceMaterial;
  10213. }
  10214. if ( ! customMaterial ) {
  10215. var useMorphing = false;
  10216. if ( material.morphTargets ) {
  10217. if ( geometry && geometry.isBufferGeometry ) {
  10218. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  10219. } else if ( geometry && geometry.isGeometry ) {
  10220. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  10221. }
  10222. }
  10223. if ( object.isSkinnedMesh && material.skinning === false ) {
  10224. console.warn( 'THREE.WebGLShadowMap: THREE.SkinnedMesh with material.skinning set to false:', object );
  10225. }
  10226. var useSkinning = object.isSkinnedMesh && material.skinning;
  10227. var variantIndex = 0;
  10228. if ( useMorphing ) variantIndex |= _MorphingFlag;
  10229. if ( useSkinning ) variantIndex |= _SkinningFlag;
  10230. result = materialVariants[ variantIndex ];
  10231. } else {
  10232. result = customMaterial;
  10233. }
  10234. if ( _renderer.localClippingEnabled &&
  10235. material.clipShadows === true &&
  10236. material.clippingPlanes.length !== 0 ) {
  10237. // in this case we need a unique material instance reflecting the
  10238. // appropriate state
  10239. var keyA = result.uuid, keyB = material.uuid;
  10240. var materialsForVariant = _materialCache[ keyA ];
  10241. if ( materialsForVariant === undefined ) {
  10242. materialsForVariant = {};
  10243. _materialCache[ keyA ] = materialsForVariant;
  10244. }
  10245. var cachedMaterial = materialsForVariant[ keyB ];
  10246. if ( cachedMaterial === undefined ) {
  10247. cachedMaterial = result.clone();
  10248. materialsForVariant[ keyB ] = cachedMaterial;
  10249. }
  10250. result = cachedMaterial;
  10251. }
  10252. result.visible = material.visible;
  10253. result.wireframe = material.wireframe;
  10254. var side = material.side;
  10255. if ( scope.renderSingleSided && side == DoubleSide ) {
  10256. side = FrontSide;
  10257. }
  10258. if ( scope.renderReverseSided ) {
  10259. if ( side === FrontSide ) side = BackSide;
  10260. else if ( side === BackSide ) side = FrontSide;
  10261. }
  10262. result.side = side;
  10263. result.clipShadows = material.clipShadows;
  10264. result.clippingPlanes = material.clippingPlanes;
  10265. result.clipIntersection = material.clipIntersection;
  10266. result.wireframeLinewidth = material.wireframeLinewidth;
  10267. result.linewidth = material.linewidth;
  10268. if ( isPointLight && result.isMeshDistanceMaterial ) {
  10269. result.referencePosition.copy( lightPositionWorld );
  10270. result.nearDistance = shadowCameraNear;
  10271. result.farDistance = shadowCameraFar;
  10272. }
  10273. return result;
  10274. }
  10275. function renderObject( object, camera, shadowCamera, isPointLight ) {
  10276. if ( object.visible === false ) return;
  10277. var visible = object.layers.test( camera.layers );
  10278. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  10279. if ( object.castShadow && ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) ) {
  10280. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  10281. var geometry = _objects.update( object );
  10282. var material = object.material;
  10283. if ( Array.isArray( material ) ) {
  10284. var groups = geometry.groups;
  10285. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  10286. var group = groups[ k ];
  10287. var groupMaterial = material[ group.materialIndex ];
  10288. if ( groupMaterial && groupMaterial.visible ) {
  10289. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  10290. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  10291. }
  10292. }
  10293. } else if ( material.visible ) {
  10294. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld, shadowCamera.near, shadowCamera.far );
  10295. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  10296. }
  10297. }
  10298. }
  10299. var children = object.children;
  10300. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10301. renderObject( children[ i ], camera, shadowCamera, isPointLight );
  10302. }
  10303. }
  10304. }
  10305. /**
  10306. * @author mrdoob / http://mrdoob.com/
  10307. */
  10308. function WebGLAttributes( gl ) {
  10309. var buffers = {};
  10310. function createBuffer( attribute, bufferType ) {
  10311. var array = attribute.array;
  10312. var usage = attribute.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  10313. var buffer = gl.createBuffer();
  10314. gl.bindBuffer( bufferType, buffer );
  10315. gl.bufferData( bufferType, array, usage );
  10316. attribute.onUploadCallback();
  10317. var type = gl.FLOAT;
  10318. if ( array instanceof Float32Array ) {
  10319. type = gl.FLOAT;
  10320. } else if ( array instanceof Float64Array ) {
  10321. console.warn( 'THREE.WebGLAttributes: Unsupported data buffer format: Float64Array.' );
  10322. } else if ( array instanceof Uint16Array ) {
  10323. type = gl.UNSIGNED_SHORT;
  10324. } else if ( array instanceof Int16Array ) {
  10325. type = gl.SHORT;
  10326. } else if ( array instanceof Uint32Array ) {
  10327. type = gl.UNSIGNED_INT;
  10328. } else if ( array instanceof Int32Array ) {
  10329. type = gl.INT;
  10330. } else if ( array instanceof Int8Array ) {
  10331. type = gl.BYTE;
  10332. } else if ( array instanceof Uint8Array ) {
  10333. type = gl.UNSIGNED_BYTE;
  10334. }
  10335. return {
  10336. buffer: buffer,
  10337. type: type,
  10338. bytesPerElement: array.BYTES_PER_ELEMENT,
  10339. version: attribute.version
  10340. };
  10341. }
  10342. function updateBuffer( buffer, attribute, bufferType ) {
  10343. var array = attribute.array;
  10344. var updateRange = attribute.updateRange;
  10345. gl.bindBuffer( bufferType, buffer );
  10346. if ( attribute.dynamic === false ) {
  10347. gl.bufferData( bufferType, array, gl.STATIC_DRAW );
  10348. } else if ( updateRange.count === - 1 ) {
  10349. // Not using update ranges
  10350. gl.bufferSubData( bufferType, 0, array );
  10351. } else if ( updateRange.count === 0 ) {
  10352. 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.' );
  10353. } else {
  10354. gl.bufferSubData( bufferType, updateRange.offset * array.BYTES_PER_ELEMENT,
  10355. array.subarray( updateRange.offset, updateRange.offset + updateRange.count ) );
  10356. updateRange.count = - 1; // reset range
  10357. }
  10358. }
  10359. //
  10360. function get( attribute ) {
  10361. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10362. return buffers[ attribute.uuid ];
  10363. }
  10364. function remove( attribute ) {
  10365. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10366. var data = buffers[ attribute.uuid ];
  10367. if ( data ) {
  10368. gl.deleteBuffer( data.buffer );
  10369. delete buffers[ attribute.uuid ];
  10370. }
  10371. }
  10372. function update( attribute, bufferType ) {
  10373. if ( attribute.isInterleavedBufferAttribute ) attribute = attribute.data;
  10374. var data = buffers[ attribute.uuid ];
  10375. if ( data === undefined ) {
  10376. buffers[ attribute.uuid ] = createBuffer( attribute, bufferType );
  10377. } else if ( data.version < attribute.version ) {
  10378. updateBuffer( data.buffer, attribute, bufferType );
  10379. data.version = attribute.version;
  10380. }
  10381. }
  10382. return {
  10383. get: get,
  10384. remove: remove,
  10385. update: update
  10386. };
  10387. }
  10388. /**
  10389. * @author mrdoob / http://mrdoob.com/
  10390. * @author WestLangley / http://github.com/WestLangley
  10391. * @author bhouston / http://clara.io
  10392. */
  10393. function Euler( x, y, z, order ) {
  10394. this._x = x || 0;
  10395. this._y = y || 0;
  10396. this._z = z || 0;
  10397. this._order = order || Euler.DefaultOrder;
  10398. }
  10399. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  10400. Euler.DefaultOrder = 'XYZ';
  10401. Object.defineProperties( Euler.prototype, {
  10402. x: {
  10403. get: function () {
  10404. return this._x;
  10405. },
  10406. set: function ( value ) {
  10407. this._x = value;
  10408. this.onChangeCallback();
  10409. }
  10410. },
  10411. y: {
  10412. get: function () {
  10413. return this._y;
  10414. },
  10415. set: function ( value ) {
  10416. this._y = value;
  10417. this.onChangeCallback();
  10418. }
  10419. },
  10420. z: {
  10421. get: function () {
  10422. return this._z;
  10423. },
  10424. set: function ( value ) {
  10425. this._z = value;
  10426. this.onChangeCallback();
  10427. }
  10428. },
  10429. order: {
  10430. get: function () {
  10431. return this._order;
  10432. },
  10433. set: function ( value ) {
  10434. this._order = value;
  10435. this.onChangeCallback();
  10436. }
  10437. }
  10438. } );
  10439. Object.assign( Euler.prototype, {
  10440. isEuler: true,
  10441. set: function ( x, y, z, order ) {
  10442. this._x = x;
  10443. this._y = y;
  10444. this._z = z;
  10445. this._order = order || this._order;
  10446. this.onChangeCallback();
  10447. return this;
  10448. },
  10449. clone: function () {
  10450. return new this.constructor( this._x, this._y, this._z, this._order );
  10451. },
  10452. copy: function ( euler ) {
  10453. this._x = euler._x;
  10454. this._y = euler._y;
  10455. this._z = euler._z;
  10456. this._order = euler._order;
  10457. this.onChangeCallback();
  10458. return this;
  10459. },
  10460. setFromRotationMatrix: function ( m, order, update ) {
  10461. var clamp = _Math.clamp;
  10462. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10463. var te = m.elements;
  10464. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  10465. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  10466. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  10467. order = order || this._order;
  10468. if ( order === 'XYZ' ) {
  10469. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  10470. if ( Math.abs( m13 ) < 0.99999 ) {
  10471. this._x = Math.atan2( - m23, m33 );
  10472. this._z = Math.atan2( - m12, m11 );
  10473. } else {
  10474. this._x = Math.atan2( m32, m22 );
  10475. this._z = 0;
  10476. }
  10477. } else if ( order === 'YXZ' ) {
  10478. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  10479. if ( Math.abs( m23 ) < 0.99999 ) {
  10480. this._y = Math.atan2( m13, m33 );
  10481. this._z = Math.atan2( m21, m22 );
  10482. } else {
  10483. this._y = Math.atan2( - m31, m11 );
  10484. this._z = 0;
  10485. }
  10486. } else if ( order === 'ZXY' ) {
  10487. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  10488. if ( Math.abs( m32 ) < 0.99999 ) {
  10489. this._y = Math.atan2( - m31, m33 );
  10490. this._z = Math.atan2( - m12, m22 );
  10491. } else {
  10492. this._y = 0;
  10493. this._z = Math.atan2( m21, m11 );
  10494. }
  10495. } else if ( order === 'ZYX' ) {
  10496. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  10497. if ( Math.abs( m31 ) < 0.99999 ) {
  10498. this._x = Math.atan2( m32, m33 );
  10499. this._z = Math.atan2( m21, m11 );
  10500. } else {
  10501. this._x = 0;
  10502. this._z = Math.atan2( - m12, m22 );
  10503. }
  10504. } else if ( order === 'YZX' ) {
  10505. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  10506. if ( Math.abs( m21 ) < 0.99999 ) {
  10507. this._x = Math.atan2( - m23, m22 );
  10508. this._y = Math.atan2( - m31, m11 );
  10509. } else {
  10510. this._x = 0;
  10511. this._y = Math.atan2( m13, m33 );
  10512. }
  10513. } else if ( order === 'XZY' ) {
  10514. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  10515. if ( Math.abs( m12 ) < 0.99999 ) {
  10516. this._x = Math.atan2( m32, m22 );
  10517. this._y = Math.atan2( m13, m11 );
  10518. } else {
  10519. this._x = Math.atan2( - m23, m33 );
  10520. this._y = 0;
  10521. }
  10522. } else {
  10523. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  10524. }
  10525. this._order = order;
  10526. if ( update !== false ) this.onChangeCallback();
  10527. return this;
  10528. },
  10529. setFromQuaternion: function () {
  10530. var matrix = new Matrix4();
  10531. return function setFromQuaternion( q, order, update ) {
  10532. matrix.makeRotationFromQuaternion( q );
  10533. return this.setFromRotationMatrix( matrix, order, update );
  10534. };
  10535. }(),
  10536. setFromVector3: function ( v, order ) {
  10537. return this.set( v.x, v.y, v.z, order || this._order );
  10538. },
  10539. reorder: function () {
  10540. // WARNING: this discards revolution information -bhouston
  10541. var q = new Quaternion();
  10542. return function reorder( newOrder ) {
  10543. q.setFromEuler( this );
  10544. return this.setFromQuaternion( q, newOrder );
  10545. };
  10546. }(),
  10547. equals: function ( euler ) {
  10548. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10549. },
  10550. fromArray: function ( array ) {
  10551. this._x = array[ 0 ];
  10552. this._y = array[ 1 ];
  10553. this._z = array[ 2 ];
  10554. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10555. this.onChangeCallback();
  10556. return this;
  10557. },
  10558. toArray: function ( array, offset ) {
  10559. if ( array === undefined ) array = [];
  10560. if ( offset === undefined ) offset = 0;
  10561. array[ offset ] = this._x;
  10562. array[ offset + 1 ] = this._y;
  10563. array[ offset + 2 ] = this._z;
  10564. array[ offset + 3 ] = this._order;
  10565. return array;
  10566. },
  10567. toVector3: function ( optionalResult ) {
  10568. if ( optionalResult ) {
  10569. return optionalResult.set( this._x, this._y, this._z );
  10570. } else {
  10571. return new Vector3( this._x, this._y, this._z );
  10572. }
  10573. },
  10574. onChange: function ( callback ) {
  10575. this.onChangeCallback = callback;
  10576. return this;
  10577. },
  10578. onChangeCallback: function () {}
  10579. } );
  10580. /**
  10581. * @author mrdoob / http://mrdoob.com/
  10582. */
  10583. function Layers() {
  10584. this.mask = 1 | 0;
  10585. }
  10586. Object.assign( Layers.prototype, {
  10587. set: function ( channel ) {
  10588. this.mask = 1 << channel | 0;
  10589. },
  10590. enable: function ( channel ) {
  10591. this.mask |= 1 << channel | 0;
  10592. },
  10593. toggle: function ( channel ) {
  10594. this.mask ^= 1 << channel | 0;
  10595. },
  10596. disable: function ( channel ) {
  10597. this.mask &= ~ ( 1 << channel | 0 );
  10598. },
  10599. test: function ( layers ) {
  10600. return ( this.mask & layers.mask ) !== 0;
  10601. }
  10602. } );
  10603. /**
  10604. * @author mrdoob / http://mrdoob.com/
  10605. * @author mikael emtinger / http://gomo.se/
  10606. * @author alteredq / http://alteredqualia.com/
  10607. * @author WestLangley / http://github.com/WestLangley
  10608. * @author elephantatwork / www.elephantatwork.ch
  10609. */
  10610. var object3DId = 0;
  10611. function Object3D() {
  10612. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  10613. this.uuid = _Math.generateUUID();
  10614. this.name = '';
  10615. this.type = 'Object3D';
  10616. this.parent = null;
  10617. this.children = [];
  10618. this.up = Object3D.DefaultUp.clone();
  10619. var position = new Vector3();
  10620. var rotation = new Euler();
  10621. var quaternion = new Quaternion();
  10622. var scale = new Vector3( 1, 1, 1 );
  10623. function onRotationChange() {
  10624. quaternion.setFromEuler( rotation, false );
  10625. }
  10626. function onQuaternionChange() {
  10627. rotation.setFromQuaternion( quaternion, undefined, false );
  10628. }
  10629. rotation.onChange( onRotationChange );
  10630. quaternion.onChange( onQuaternionChange );
  10631. Object.defineProperties( this, {
  10632. position: {
  10633. enumerable: true,
  10634. value: position
  10635. },
  10636. rotation: {
  10637. enumerable: true,
  10638. value: rotation
  10639. },
  10640. quaternion: {
  10641. enumerable: true,
  10642. value: quaternion
  10643. },
  10644. scale: {
  10645. enumerable: true,
  10646. value: scale
  10647. },
  10648. modelViewMatrix: {
  10649. value: new Matrix4()
  10650. },
  10651. normalMatrix: {
  10652. value: new Matrix3()
  10653. }
  10654. } );
  10655. this.matrix = new Matrix4();
  10656. this.matrixWorld = new Matrix4();
  10657. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10658. this.matrixWorldNeedsUpdate = false;
  10659. this.layers = new Layers();
  10660. this.visible = true;
  10661. this.castShadow = false;
  10662. this.receiveShadow = false;
  10663. this.frustumCulled = true;
  10664. this.renderOrder = 0;
  10665. this.userData = {};
  10666. }
  10667. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  10668. Object3D.DefaultMatrixAutoUpdate = true;
  10669. Object3D.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  10670. constructor: Object3D,
  10671. isObject3D: true,
  10672. onBeforeRender: function () {},
  10673. onAfterRender: function () {},
  10674. applyMatrix: function ( matrix ) {
  10675. this.matrix.multiplyMatrices( matrix, this.matrix );
  10676. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10677. },
  10678. applyQuaternion: function ( q ) {
  10679. this.quaternion.premultiply( q );
  10680. return this;
  10681. },
  10682. setRotationFromAxisAngle: function ( axis, angle ) {
  10683. // assumes axis is normalized
  10684. this.quaternion.setFromAxisAngle( axis, angle );
  10685. },
  10686. setRotationFromEuler: function ( euler ) {
  10687. this.quaternion.setFromEuler( euler, true );
  10688. },
  10689. setRotationFromMatrix: function ( m ) {
  10690. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10691. this.quaternion.setFromRotationMatrix( m );
  10692. },
  10693. setRotationFromQuaternion: function ( q ) {
  10694. // assumes q is normalized
  10695. this.quaternion.copy( q );
  10696. },
  10697. rotateOnAxis: function () {
  10698. // rotate object on axis in object space
  10699. // axis is assumed to be normalized
  10700. var q1 = new Quaternion();
  10701. return function rotateOnAxis( axis, angle ) {
  10702. q1.setFromAxisAngle( axis, angle );
  10703. this.quaternion.multiply( q1 );
  10704. return this;
  10705. };
  10706. }(),
  10707. rotateOnWorldAxis: function () {
  10708. // rotate object on axis in world space
  10709. // axis is assumed to be normalized
  10710. // method assumes no rotated parent
  10711. var q1 = new Quaternion();
  10712. return function rotateOnWorldAxis( axis, angle ) {
  10713. q1.setFromAxisAngle( axis, angle );
  10714. this.quaternion.premultiply( q1 );
  10715. return this;
  10716. };
  10717. }(),
  10718. rotateX: function () {
  10719. var v1 = new Vector3( 1, 0, 0 );
  10720. return function rotateX( angle ) {
  10721. return this.rotateOnAxis( v1, angle );
  10722. };
  10723. }(),
  10724. rotateY: function () {
  10725. var v1 = new Vector3( 0, 1, 0 );
  10726. return function rotateY( angle ) {
  10727. return this.rotateOnAxis( v1, angle );
  10728. };
  10729. }(),
  10730. rotateZ: function () {
  10731. var v1 = new Vector3( 0, 0, 1 );
  10732. return function rotateZ( angle ) {
  10733. return this.rotateOnAxis( v1, angle );
  10734. };
  10735. }(),
  10736. translateOnAxis: function () {
  10737. // translate object by distance along axis in object space
  10738. // axis is assumed to be normalized
  10739. var v1 = new Vector3();
  10740. return function translateOnAxis( axis, distance ) {
  10741. v1.copy( axis ).applyQuaternion( this.quaternion );
  10742. this.position.add( v1.multiplyScalar( distance ) );
  10743. return this;
  10744. };
  10745. }(),
  10746. translateX: function () {
  10747. var v1 = new Vector3( 1, 0, 0 );
  10748. return function translateX( distance ) {
  10749. return this.translateOnAxis( v1, distance );
  10750. };
  10751. }(),
  10752. translateY: function () {
  10753. var v1 = new Vector3( 0, 1, 0 );
  10754. return function translateY( distance ) {
  10755. return this.translateOnAxis( v1, distance );
  10756. };
  10757. }(),
  10758. translateZ: function () {
  10759. var v1 = new Vector3( 0, 0, 1 );
  10760. return function translateZ( distance ) {
  10761. return this.translateOnAxis( v1, distance );
  10762. };
  10763. }(),
  10764. localToWorld: function ( vector ) {
  10765. return vector.applyMatrix4( this.matrixWorld );
  10766. },
  10767. worldToLocal: function () {
  10768. var m1 = new Matrix4();
  10769. return function worldToLocal( vector ) {
  10770. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  10771. };
  10772. }(),
  10773. lookAt: function () {
  10774. // This method does not support objects with rotated and/or translated parent(s)
  10775. var m1 = new Matrix4();
  10776. var vector = new Vector3();
  10777. return function lookAt( x, y, z ) {
  10778. if ( x.isVector3 ) {
  10779. vector.copy( x );
  10780. } else {
  10781. vector.set( x, y, z );
  10782. }
  10783. if ( this.isCamera ) {
  10784. m1.lookAt( this.position, vector, this.up );
  10785. } else {
  10786. m1.lookAt( vector, this.position, this.up );
  10787. }
  10788. this.quaternion.setFromRotationMatrix( m1 );
  10789. };
  10790. }(),
  10791. add: function ( object ) {
  10792. if ( arguments.length > 1 ) {
  10793. for ( var i = 0; i < arguments.length; i ++ ) {
  10794. this.add( arguments[ i ] );
  10795. }
  10796. return this;
  10797. }
  10798. if ( object === this ) {
  10799. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  10800. return this;
  10801. }
  10802. if ( ( object && object.isObject3D ) ) {
  10803. if ( object.parent !== null ) {
  10804. object.parent.remove( object );
  10805. }
  10806. object.parent = this;
  10807. object.dispatchEvent( { type: 'added' } );
  10808. this.children.push( object );
  10809. } else {
  10810. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  10811. }
  10812. return this;
  10813. },
  10814. remove: function ( object ) {
  10815. if ( arguments.length > 1 ) {
  10816. for ( var i = 0; i < arguments.length; i ++ ) {
  10817. this.remove( arguments[ i ] );
  10818. }
  10819. return this;
  10820. }
  10821. var index = this.children.indexOf( object );
  10822. if ( index !== - 1 ) {
  10823. object.parent = null;
  10824. object.dispatchEvent( { type: 'removed' } );
  10825. this.children.splice( index, 1 );
  10826. }
  10827. return this;
  10828. },
  10829. getObjectById: function ( id ) {
  10830. return this.getObjectByProperty( 'id', id );
  10831. },
  10832. getObjectByName: function ( name ) {
  10833. return this.getObjectByProperty( 'name', name );
  10834. },
  10835. getObjectByProperty: function ( name, value ) {
  10836. if ( this[ name ] === value ) return this;
  10837. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10838. var child = this.children[ i ];
  10839. var object = child.getObjectByProperty( name, value );
  10840. if ( object !== undefined ) {
  10841. return object;
  10842. }
  10843. }
  10844. return undefined;
  10845. },
  10846. getWorldPosition: function ( optionalTarget ) {
  10847. var result = optionalTarget || new Vector3();
  10848. this.updateMatrixWorld( true );
  10849. return result.setFromMatrixPosition( this.matrixWorld );
  10850. },
  10851. getWorldQuaternion: function () {
  10852. var position = new Vector3();
  10853. var scale = new Vector3();
  10854. return function getWorldQuaternion( optionalTarget ) {
  10855. var result = optionalTarget || new Quaternion();
  10856. this.updateMatrixWorld( true );
  10857. this.matrixWorld.decompose( position, result, scale );
  10858. return result;
  10859. };
  10860. }(),
  10861. getWorldRotation: function () {
  10862. var quaternion = new Quaternion();
  10863. return function getWorldRotation( optionalTarget ) {
  10864. var result = optionalTarget || new Euler();
  10865. this.getWorldQuaternion( quaternion );
  10866. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  10867. };
  10868. }(),
  10869. getWorldScale: function () {
  10870. var position = new Vector3();
  10871. var quaternion = new Quaternion();
  10872. return function getWorldScale( optionalTarget ) {
  10873. var result = optionalTarget || new Vector3();
  10874. this.updateMatrixWorld( true );
  10875. this.matrixWorld.decompose( position, quaternion, result );
  10876. return result;
  10877. };
  10878. }(),
  10879. getWorldDirection: function () {
  10880. var quaternion = new Quaternion();
  10881. return function getWorldDirection( optionalTarget ) {
  10882. var result = optionalTarget || new Vector3();
  10883. this.getWorldQuaternion( quaternion );
  10884. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  10885. };
  10886. }(),
  10887. raycast: function () {},
  10888. traverse: function ( callback ) {
  10889. callback( this );
  10890. var children = this.children;
  10891. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10892. children[ i ].traverse( callback );
  10893. }
  10894. },
  10895. traverseVisible: function ( callback ) {
  10896. if ( this.visible === false ) return;
  10897. callback( this );
  10898. var children = this.children;
  10899. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10900. children[ i ].traverseVisible( callback );
  10901. }
  10902. },
  10903. traverseAncestors: function ( callback ) {
  10904. var parent = this.parent;
  10905. if ( parent !== null ) {
  10906. callback( parent );
  10907. parent.traverseAncestors( callback );
  10908. }
  10909. },
  10910. updateMatrix: function () {
  10911. this.matrix.compose( this.position, this.quaternion, this.scale );
  10912. this.matrixWorldNeedsUpdate = true;
  10913. },
  10914. updateMatrixWorld: function ( force ) {
  10915. if ( this.matrixAutoUpdate ) this.updateMatrix();
  10916. if ( this.matrixWorldNeedsUpdate || force ) {
  10917. if ( this.parent === null ) {
  10918. this.matrixWorld.copy( this.matrix );
  10919. } else {
  10920. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10921. }
  10922. this.matrixWorldNeedsUpdate = false;
  10923. force = true;
  10924. }
  10925. // update children
  10926. var children = this.children;
  10927. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10928. children[ i ].updateMatrixWorld( force );
  10929. }
  10930. },
  10931. toJSON: function ( meta ) {
  10932. // meta is a string when called from JSON.stringify
  10933. var isRootObject = ( meta === undefined || typeof meta === 'string' );
  10934. var output = {};
  10935. // meta is a hash used to collect geometries, materials.
  10936. // not providing it implies that this is the root object
  10937. // being serialized.
  10938. if ( isRootObject ) {
  10939. // initialize meta obj
  10940. meta = {
  10941. geometries: {},
  10942. materials: {},
  10943. textures: {},
  10944. images: {},
  10945. shapes: {}
  10946. };
  10947. output.metadata = {
  10948. version: 4.5,
  10949. type: 'Object',
  10950. generator: 'Object3D.toJSON'
  10951. };
  10952. }
  10953. // standard Object3D serialization
  10954. var object = {};
  10955. object.uuid = this.uuid;
  10956. object.type = this.type;
  10957. if ( this.name !== '' ) object.name = this.name;
  10958. if ( this.castShadow === true ) object.castShadow = true;
  10959. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10960. if ( this.visible === false ) object.visible = false;
  10961. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10962. object.matrix = this.matrix.toArray();
  10963. //
  10964. function serialize( library, element ) {
  10965. if ( library[ element.uuid ] === undefined ) {
  10966. library[ element.uuid ] = element.toJSON( meta );
  10967. }
  10968. return element.uuid;
  10969. }
  10970. if ( this.geometry !== undefined ) {
  10971. object.geometry = serialize( meta.geometries, this.geometry );
  10972. var parameters = this.geometry.parameters;
  10973. if ( parameters !== undefined && parameters.shapes !== undefined ) {
  10974. var shapes = parameters.shapes;
  10975. if ( Array.isArray( shapes ) ) {
  10976. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  10977. var shape = shapes[ i ];
  10978. serialize( meta.shapes, shape );
  10979. }
  10980. } else {
  10981. serialize( meta.shapes, shapes );
  10982. }
  10983. }
  10984. }
  10985. if ( this.material !== undefined ) {
  10986. if ( Array.isArray( this.material ) ) {
  10987. var uuids = [];
  10988. for ( var i = 0, l = this.material.length; i < l; i ++ ) {
  10989. uuids.push( serialize( meta.materials, this.material[ i ] ) );
  10990. }
  10991. object.material = uuids;
  10992. } else {
  10993. object.material = serialize( meta.materials, this.material );
  10994. }
  10995. }
  10996. //
  10997. if ( this.children.length > 0 ) {
  10998. object.children = [];
  10999. for ( var i = 0; i < this.children.length; i ++ ) {
  11000. object.children.push( this.children[ i ].toJSON( meta ).object );
  11001. }
  11002. }
  11003. if ( isRootObject ) {
  11004. var geometries = extractFromCache( meta.geometries );
  11005. var materials = extractFromCache( meta.materials );
  11006. var textures = extractFromCache( meta.textures );
  11007. var images = extractFromCache( meta.images );
  11008. var shapes = extractFromCache( meta.shapes );
  11009. if ( geometries.length > 0 ) output.geometries = geometries;
  11010. if ( materials.length > 0 ) output.materials = materials;
  11011. if ( textures.length > 0 ) output.textures = textures;
  11012. if ( images.length > 0 ) output.images = images;
  11013. if ( shapes.length > 0 ) output.shapes = shapes;
  11014. }
  11015. output.object = object;
  11016. return output;
  11017. // extract data from the cache hash
  11018. // remove metadata on each item
  11019. // and return as array
  11020. function extractFromCache( cache ) {
  11021. var values = [];
  11022. for ( var key in cache ) {
  11023. var data = cache[ key ];
  11024. delete data.metadata;
  11025. values.push( data );
  11026. }
  11027. return values;
  11028. }
  11029. },
  11030. clone: function ( recursive ) {
  11031. return new this.constructor().copy( this, recursive );
  11032. },
  11033. copy: function ( source, recursive ) {
  11034. if ( recursive === undefined ) recursive = true;
  11035. this.name = source.name;
  11036. this.up.copy( source.up );
  11037. this.position.copy( source.position );
  11038. this.quaternion.copy( source.quaternion );
  11039. this.scale.copy( source.scale );
  11040. this.matrix.copy( source.matrix );
  11041. this.matrixWorld.copy( source.matrixWorld );
  11042. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11043. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11044. this.layers.mask = source.layers.mask;
  11045. this.visible = source.visible;
  11046. this.castShadow = source.castShadow;
  11047. this.receiveShadow = source.receiveShadow;
  11048. this.frustumCulled = source.frustumCulled;
  11049. this.renderOrder = source.renderOrder;
  11050. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11051. if ( recursive === true ) {
  11052. for ( var i = 0; i < source.children.length; i ++ ) {
  11053. var child = source.children[ i ];
  11054. this.add( child.clone() );
  11055. }
  11056. }
  11057. return this;
  11058. }
  11059. } );
  11060. /**
  11061. * @author mrdoob / http://mrdoob.com/
  11062. * @author mikael emtinger / http://gomo.se/
  11063. * @author WestLangley / http://github.com/WestLangley
  11064. */
  11065. function Camera() {
  11066. Object3D.call( this );
  11067. this.type = 'Camera';
  11068. this.matrixWorldInverse = new Matrix4();
  11069. this.projectionMatrix = new Matrix4();
  11070. }
  11071. Camera.prototype = Object.assign( Object.create( Object3D.prototype ), {
  11072. constructor: Camera,
  11073. isCamera: true,
  11074. copy: function ( source, recursive ) {
  11075. Object3D.prototype.copy.call( this, source, recursive );
  11076. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  11077. this.projectionMatrix.copy( source.projectionMatrix );
  11078. return this;
  11079. },
  11080. getWorldDirection: function () {
  11081. var quaternion = new Quaternion();
  11082. return function getWorldDirection( optionalTarget ) {
  11083. var result = optionalTarget || new Vector3();
  11084. this.getWorldQuaternion( quaternion );
  11085. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  11086. };
  11087. }(),
  11088. updateMatrixWorld: function ( force ) {
  11089. Object3D.prototype.updateMatrixWorld.call( this, force );
  11090. this.matrixWorldInverse.getInverse( this.matrixWorld );
  11091. },
  11092. clone: function () {
  11093. return new this.constructor().copy( this );
  11094. }
  11095. } );
  11096. /**
  11097. * @author alteredq / http://alteredqualia.com/
  11098. * @author arose / http://github.com/arose
  11099. */
  11100. function OrthographicCamera( left, right, top, bottom, near, far ) {
  11101. Camera.call( this );
  11102. this.type = 'OrthographicCamera';
  11103. this.zoom = 1;
  11104. this.view = null;
  11105. this.left = left;
  11106. this.right = right;
  11107. this.top = top;
  11108. this.bottom = bottom;
  11109. this.near = ( near !== undefined ) ? near : 0.1;
  11110. this.far = ( far !== undefined ) ? far : 2000;
  11111. this.updateProjectionMatrix();
  11112. }
  11113. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  11114. constructor: OrthographicCamera,
  11115. isOrthographicCamera: true,
  11116. copy: function ( source, recursive ) {
  11117. Camera.prototype.copy.call( this, source, recursive );
  11118. this.left = source.left;
  11119. this.right = source.right;
  11120. this.top = source.top;
  11121. this.bottom = source.bottom;
  11122. this.near = source.near;
  11123. this.far = source.far;
  11124. this.zoom = source.zoom;
  11125. this.view = source.view === null ? null : Object.assign( {}, source.view );
  11126. return this;
  11127. },
  11128. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  11129. if ( this.view === null ) {
  11130. this.view = {
  11131. enabled: true,
  11132. fullWidth: 1,
  11133. fullHeight: 1,
  11134. offsetX: 0,
  11135. offsetY: 0,
  11136. width: 1,
  11137. height: 1
  11138. };
  11139. }
  11140. this.view.enabled = true;
  11141. this.view.fullWidth = fullWidth;
  11142. this.view.fullHeight = fullHeight;
  11143. this.view.offsetX = x;
  11144. this.view.offsetY = y;
  11145. this.view.width = width;
  11146. this.view.height = height;
  11147. this.updateProjectionMatrix();
  11148. },
  11149. clearViewOffset: function () {
  11150. if ( this.view !== null ) {
  11151. this.view.enabled = false;
  11152. }
  11153. this.updateProjectionMatrix();
  11154. },
  11155. updateProjectionMatrix: function () {
  11156. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  11157. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  11158. var cx = ( this.right + this.left ) / 2;
  11159. var cy = ( this.top + this.bottom ) / 2;
  11160. var left = cx - dx;
  11161. var right = cx + dx;
  11162. var top = cy + dy;
  11163. var bottom = cy - dy;
  11164. if ( this.view !== null && this.view.enabled ) {
  11165. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  11166. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  11167. var scaleW = ( this.right - this.left ) / this.view.width;
  11168. var scaleH = ( this.top - this.bottom ) / this.view.height;
  11169. left += scaleW * ( this.view.offsetX / zoomW );
  11170. right = left + scaleW * ( this.view.width / zoomW );
  11171. top -= scaleH * ( this.view.offsetY / zoomH );
  11172. bottom = top - scaleH * ( this.view.height / zoomH );
  11173. }
  11174. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  11175. },
  11176. toJSON: function ( meta ) {
  11177. var data = Object3D.prototype.toJSON.call( this, meta );
  11178. data.object.zoom = this.zoom;
  11179. data.object.left = this.left;
  11180. data.object.right = this.right;
  11181. data.object.top = this.top;
  11182. data.object.bottom = this.bottom;
  11183. data.object.near = this.near;
  11184. data.object.far = this.far;
  11185. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  11186. return data;
  11187. }
  11188. } );
  11189. /**
  11190. * @author mrdoob / http://mrdoob.com/
  11191. * @author alteredq / http://alteredqualia.com/
  11192. */
  11193. function Face3( a, b, c, normal, color, materialIndex ) {
  11194. this.a = a;
  11195. this.b = b;
  11196. this.c = c;
  11197. this.normal = ( normal && normal.isVector3 ) ? normal : new Vector3();
  11198. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  11199. this.color = ( color && color.isColor ) ? color : new Color();
  11200. this.vertexColors = Array.isArray( color ) ? color : [];
  11201. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  11202. }
  11203. Object.assign( Face3.prototype, {
  11204. clone: function () {
  11205. return new this.constructor().copy( this );
  11206. },
  11207. copy: function ( source ) {
  11208. this.a = source.a;
  11209. this.b = source.b;
  11210. this.c = source.c;
  11211. this.normal.copy( source.normal );
  11212. this.color.copy( source.color );
  11213. this.materialIndex = source.materialIndex;
  11214. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  11215. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  11216. }
  11217. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  11218. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  11219. }
  11220. return this;
  11221. }
  11222. } );
  11223. /**
  11224. * @author mrdoob / http://mrdoob.com/
  11225. * @author kile / http://kile.stravaganza.org/
  11226. * @author alteredq / http://alteredqualia.com/
  11227. * @author mikael emtinger / http://gomo.se/
  11228. * @author zz85 / http://www.lab4games.net/zz85/blog
  11229. * @author bhouston / http://clara.io
  11230. */
  11231. var geometryId = 0; // Geometry uses even numbers as Id
  11232. function Geometry() {
  11233. Object.defineProperty( this, 'id', { value: geometryId += 2 } );
  11234. this.uuid = _Math.generateUUID();
  11235. this.name = '';
  11236. this.type = 'Geometry';
  11237. this.vertices = [];
  11238. this.colors = [];
  11239. this.faces = [];
  11240. this.faceVertexUvs = [[]];
  11241. this.morphTargets = [];
  11242. this.morphNormals = [];
  11243. this.skinWeights = [];
  11244. this.skinIndices = [];
  11245. this.lineDistances = [];
  11246. this.boundingBox = null;
  11247. this.boundingSphere = null;
  11248. // update flags
  11249. this.elementsNeedUpdate = false;
  11250. this.verticesNeedUpdate = false;
  11251. this.uvsNeedUpdate = false;
  11252. this.normalsNeedUpdate = false;
  11253. this.colorsNeedUpdate = false;
  11254. this.lineDistancesNeedUpdate = false;
  11255. this.groupsNeedUpdate = false;
  11256. }
  11257. Geometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  11258. constructor: Geometry,
  11259. isGeometry: true,
  11260. applyMatrix: function ( matrix ) {
  11261. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11262. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  11263. var vertex = this.vertices[ i ];
  11264. vertex.applyMatrix4( matrix );
  11265. }
  11266. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  11267. var face = this.faces[ i ];
  11268. face.normal.applyMatrix3( normalMatrix ).normalize();
  11269. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  11270. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  11271. }
  11272. }
  11273. if ( this.boundingBox !== null ) {
  11274. this.computeBoundingBox();
  11275. }
  11276. if ( this.boundingSphere !== null ) {
  11277. this.computeBoundingSphere();
  11278. }
  11279. this.verticesNeedUpdate = true;
  11280. this.normalsNeedUpdate = true;
  11281. return this;
  11282. },
  11283. rotateX: function () {
  11284. // rotate geometry around world x-axis
  11285. var m1 = new Matrix4();
  11286. return function rotateX( angle ) {
  11287. m1.makeRotationX( angle );
  11288. this.applyMatrix( m1 );
  11289. return this;
  11290. };
  11291. }(),
  11292. rotateY: function () {
  11293. // rotate geometry around world y-axis
  11294. var m1 = new Matrix4();
  11295. return function rotateY( angle ) {
  11296. m1.makeRotationY( angle );
  11297. this.applyMatrix( m1 );
  11298. return this;
  11299. };
  11300. }(),
  11301. rotateZ: function () {
  11302. // rotate geometry around world z-axis
  11303. var m1 = new Matrix4();
  11304. return function rotateZ( angle ) {
  11305. m1.makeRotationZ( angle );
  11306. this.applyMatrix( m1 );
  11307. return this;
  11308. };
  11309. }(),
  11310. translate: function () {
  11311. // translate geometry
  11312. var m1 = new Matrix4();
  11313. return function translate( x, y, z ) {
  11314. m1.makeTranslation( x, y, z );
  11315. this.applyMatrix( m1 );
  11316. return this;
  11317. };
  11318. }(),
  11319. scale: function () {
  11320. // scale geometry
  11321. var m1 = new Matrix4();
  11322. return function scale( x, y, z ) {
  11323. m1.makeScale( x, y, z );
  11324. this.applyMatrix( m1 );
  11325. return this;
  11326. };
  11327. }(),
  11328. lookAt: function () {
  11329. var obj = new Object3D();
  11330. return function lookAt( vector ) {
  11331. obj.lookAt( vector );
  11332. obj.updateMatrix();
  11333. this.applyMatrix( obj.matrix );
  11334. };
  11335. }(),
  11336. fromBufferGeometry: function ( geometry ) {
  11337. var scope = this;
  11338. var indices = geometry.index !== null ? geometry.index.array : undefined;
  11339. var attributes = geometry.attributes;
  11340. var positions = attributes.position.array;
  11341. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  11342. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  11343. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  11344. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  11345. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  11346. var tempNormals = [];
  11347. var tempUVs = [];
  11348. var tempUVs2 = [];
  11349. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  11350. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  11351. if ( normals !== undefined ) {
  11352. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  11353. }
  11354. if ( colors !== undefined ) {
  11355. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  11356. }
  11357. if ( uvs !== undefined ) {
  11358. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  11359. }
  11360. if ( uvs2 !== undefined ) {
  11361. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  11362. }
  11363. }
  11364. function addFace( a, b, c, materialIndex ) {
  11365. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  11366. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  11367. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  11368. scope.faces.push( face );
  11369. if ( uvs !== undefined ) {
  11370. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  11371. }
  11372. if ( uvs2 !== undefined ) {
  11373. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  11374. }
  11375. }
  11376. var groups = geometry.groups;
  11377. if ( groups.length > 0 ) {
  11378. for ( var i = 0; i < groups.length; i ++ ) {
  11379. var group = groups[ i ];
  11380. var start = group.start;
  11381. var count = group.count;
  11382. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  11383. if ( indices !== undefined ) {
  11384. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  11385. } else {
  11386. addFace( j, j + 1, j + 2, group.materialIndex );
  11387. }
  11388. }
  11389. }
  11390. } else {
  11391. if ( indices !== undefined ) {
  11392. for ( var i = 0; i < indices.length; i += 3 ) {
  11393. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  11394. }
  11395. } else {
  11396. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  11397. addFace( i, i + 1, i + 2 );
  11398. }
  11399. }
  11400. }
  11401. this.computeFaceNormals();
  11402. if ( geometry.boundingBox !== null ) {
  11403. this.boundingBox = geometry.boundingBox.clone();
  11404. }
  11405. if ( geometry.boundingSphere !== null ) {
  11406. this.boundingSphere = geometry.boundingSphere.clone();
  11407. }
  11408. return this;
  11409. },
  11410. center: function () {
  11411. this.computeBoundingBox();
  11412. var offset = this.boundingBox.getCenter().negate();
  11413. this.translate( offset.x, offset.y, offset.z );
  11414. return offset;
  11415. },
  11416. normalize: function () {
  11417. this.computeBoundingSphere();
  11418. var center = this.boundingSphere.center;
  11419. var radius = this.boundingSphere.radius;
  11420. var s = radius === 0 ? 1 : 1.0 / radius;
  11421. var matrix = new Matrix4();
  11422. matrix.set(
  11423. s, 0, 0, - s * center.x,
  11424. 0, s, 0, - s * center.y,
  11425. 0, 0, s, - s * center.z,
  11426. 0, 0, 0, 1
  11427. );
  11428. this.applyMatrix( matrix );
  11429. return this;
  11430. },
  11431. computeFaceNormals: function () {
  11432. var cb = new Vector3(), ab = new Vector3();
  11433. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11434. var face = this.faces[ f ];
  11435. var vA = this.vertices[ face.a ];
  11436. var vB = this.vertices[ face.b ];
  11437. var vC = this.vertices[ face.c ];
  11438. cb.subVectors( vC, vB );
  11439. ab.subVectors( vA, vB );
  11440. cb.cross( ab );
  11441. cb.normalize();
  11442. face.normal.copy( cb );
  11443. }
  11444. },
  11445. computeVertexNormals: function ( areaWeighted ) {
  11446. if ( areaWeighted === undefined ) areaWeighted = true;
  11447. var v, vl, f, fl, face, vertices;
  11448. vertices = new Array( this.vertices.length );
  11449. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11450. vertices[ v ] = new Vector3();
  11451. }
  11452. if ( areaWeighted ) {
  11453. // vertex normals weighted by triangle areas
  11454. // http://www.iquilezles.org/www/articles/normals/normals.htm
  11455. var vA, vB, vC;
  11456. var cb = new Vector3(), ab = new Vector3();
  11457. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11458. face = this.faces[ f ];
  11459. vA = this.vertices[ face.a ];
  11460. vB = this.vertices[ face.b ];
  11461. vC = this.vertices[ face.c ];
  11462. cb.subVectors( vC, vB );
  11463. ab.subVectors( vA, vB );
  11464. cb.cross( ab );
  11465. vertices[ face.a ].add( cb );
  11466. vertices[ face.b ].add( cb );
  11467. vertices[ face.c ].add( cb );
  11468. }
  11469. } else {
  11470. this.computeFaceNormals();
  11471. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11472. face = this.faces[ f ];
  11473. vertices[ face.a ].add( face.normal );
  11474. vertices[ face.b ].add( face.normal );
  11475. vertices[ face.c ].add( face.normal );
  11476. }
  11477. }
  11478. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11479. vertices[ v ].normalize();
  11480. }
  11481. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11482. face = this.faces[ f ];
  11483. var vertexNormals = face.vertexNormals;
  11484. if ( vertexNormals.length === 3 ) {
  11485. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  11486. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  11487. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  11488. } else {
  11489. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  11490. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  11491. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  11492. }
  11493. }
  11494. if ( this.faces.length > 0 ) {
  11495. this.normalsNeedUpdate = true;
  11496. }
  11497. },
  11498. computeFlatVertexNormals: function () {
  11499. var f, fl, face;
  11500. this.computeFaceNormals();
  11501. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11502. face = this.faces[ f ];
  11503. var vertexNormals = face.vertexNormals;
  11504. if ( vertexNormals.length === 3 ) {
  11505. vertexNormals[ 0 ].copy( face.normal );
  11506. vertexNormals[ 1 ].copy( face.normal );
  11507. vertexNormals[ 2 ].copy( face.normal );
  11508. } else {
  11509. vertexNormals[ 0 ] = face.normal.clone();
  11510. vertexNormals[ 1 ] = face.normal.clone();
  11511. vertexNormals[ 2 ] = face.normal.clone();
  11512. }
  11513. }
  11514. if ( this.faces.length > 0 ) {
  11515. this.normalsNeedUpdate = true;
  11516. }
  11517. },
  11518. computeMorphNormals: function () {
  11519. var i, il, f, fl, face;
  11520. // save original normals
  11521. // - create temp variables on first access
  11522. // otherwise just copy (for faster repeated calls)
  11523. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11524. face = this.faces[ f ];
  11525. if ( ! face.__originalFaceNormal ) {
  11526. face.__originalFaceNormal = face.normal.clone();
  11527. } else {
  11528. face.__originalFaceNormal.copy( face.normal );
  11529. }
  11530. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  11531. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  11532. if ( ! face.__originalVertexNormals[ i ] ) {
  11533. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  11534. } else {
  11535. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  11536. }
  11537. }
  11538. }
  11539. // use temp geometry to compute face and vertex normals for each morph
  11540. var tmpGeo = new Geometry();
  11541. tmpGeo.faces = this.faces;
  11542. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  11543. // create on first access
  11544. if ( ! this.morphNormals[ i ] ) {
  11545. this.morphNormals[ i ] = {};
  11546. this.morphNormals[ i ].faceNormals = [];
  11547. this.morphNormals[ i ].vertexNormals = [];
  11548. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  11549. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  11550. var faceNormal, vertexNormals;
  11551. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11552. faceNormal = new Vector3();
  11553. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  11554. dstNormalsFace.push( faceNormal );
  11555. dstNormalsVertex.push( vertexNormals );
  11556. }
  11557. }
  11558. var morphNormals = this.morphNormals[ i ];
  11559. // set vertices to morph target
  11560. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  11561. // compute morph normals
  11562. tmpGeo.computeFaceNormals();
  11563. tmpGeo.computeVertexNormals();
  11564. // store morph normals
  11565. var faceNormal, vertexNormals;
  11566. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11567. face = this.faces[ f ];
  11568. faceNormal = morphNormals.faceNormals[ f ];
  11569. vertexNormals = morphNormals.vertexNormals[ f ];
  11570. faceNormal.copy( face.normal );
  11571. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  11572. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  11573. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  11574. }
  11575. }
  11576. // restore original normals
  11577. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11578. face = this.faces[ f ];
  11579. face.normal = face.__originalFaceNormal;
  11580. face.vertexNormals = face.__originalVertexNormals;
  11581. }
  11582. },
  11583. computeLineDistances: function () {
  11584. var d = 0;
  11585. var vertices = this.vertices;
  11586. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  11587. if ( i > 0 ) {
  11588. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  11589. }
  11590. this.lineDistances[ i ] = d;
  11591. }
  11592. },
  11593. computeBoundingBox: function () {
  11594. if ( this.boundingBox === null ) {
  11595. this.boundingBox = new Box3();
  11596. }
  11597. this.boundingBox.setFromPoints( this.vertices );
  11598. },
  11599. computeBoundingSphere: function () {
  11600. if ( this.boundingSphere === null ) {
  11601. this.boundingSphere = new Sphere();
  11602. }
  11603. this.boundingSphere.setFromPoints( this.vertices );
  11604. },
  11605. merge: function ( geometry, matrix, materialIndexOffset ) {
  11606. if ( ! ( geometry && geometry.isGeometry ) ) {
  11607. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  11608. return;
  11609. }
  11610. var normalMatrix,
  11611. vertexOffset = this.vertices.length,
  11612. vertices1 = this.vertices,
  11613. vertices2 = geometry.vertices,
  11614. faces1 = this.faces,
  11615. faces2 = geometry.faces,
  11616. uvs1 = this.faceVertexUvs[ 0 ],
  11617. uvs2 = geometry.faceVertexUvs[ 0 ],
  11618. colors1 = this.colors,
  11619. colors2 = geometry.colors;
  11620. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  11621. if ( matrix !== undefined ) {
  11622. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11623. }
  11624. // vertices
  11625. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  11626. var vertex = vertices2[ i ];
  11627. var vertexCopy = vertex.clone();
  11628. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  11629. vertices1.push( vertexCopy );
  11630. }
  11631. // colors
  11632. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  11633. colors1.push( colors2[ i ].clone() );
  11634. }
  11635. // faces
  11636. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  11637. var face = faces2[ i ], faceCopy, normal, color,
  11638. faceVertexNormals = face.vertexNormals,
  11639. faceVertexColors = face.vertexColors;
  11640. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  11641. faceCopy.normal.copy( face.normal );
  11642. if ( normalMatrix !== undefined ) {
  11643. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  11644. }
  11645. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  11646. normal = faceVertexNormals[ j ].clone();
  11647. if ( normalMatrix !== undefined ) {
  11648. normal.applyMatrix3( normalMatrix ).normalize();
  11649. }
  11650. faceCopy.vertexNormals.push( normal );
  11651. }
  11652. faceCopy.color.copy( face.color );
  11653. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  11654. color = faceVertexColors[ j ];
  11655. faceCopy.vertexColors.push( color.clone() );
  11656. }
  11657. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  11658. faces1.push( faceCopy );
  11659. }
  11660. // uvs
  11661. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  11662. var uv = uvs2[ i ], uvCopy = [];
  11663. if ( uv === undefined ) {
  11664. continue;
  11665. }
  11666. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  11667. uvCopy.push( uv[ j ].clone() );
  11668. }
  11669. uvs1.push( uvCopy );
  11670. }
  11671. },
  11672. mergeMesh: function ( mesh ) {
  11673. if ( ! ( mesh && mesh.isMesh ) ) {
  11674. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  11675. return;
  11676. }
  11677. mesh.matrixAutoUpdate && mesh.updateMatrix();
  11678. this.merge( mesh.geometry, mesh.matrix );
  11679. },
  11680. /*
  11681. * Checks for duplicate vertices with hashmap.
  11682. * Duplicated vertices are removed
  11683. * and faces' vertices are updated.
  11684. */
  11685. mergeVertices: function () {
  11686. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  11687. var unique = [], changes = [];
  11688. var v, key;
  11689. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  11690. var precision = Math.pow( 10, precisionPoints );
  11691. var i, il, face;
  11692. var indices, j, jl;
  11693. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  11694. v = this.vertices[ i ];
  11695. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  11696. if ( verticesMap[ key ] === undefined ) {
  11697. verticesMap[ key ] = i;
  11698. unique.push( this.vertices[ i ] );
  11699. changes[ i ] = unique.length - 1;
  11700. } else {
  11701. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  11702. changes[ i ] = changes[ verticesMap[ key ] ];
  11703. }
  11704. }
  11705. // if faces are completely degenerate after merging vertices, we
  11706. // have to remove them from the geometry.
  11707. var faceIndicesToRemove = [];
  11708. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  11709. face = this.faces[ i ];
  11710. face.a = changes[ face.a ];
  11711. face.b = changes[ face.b ];
  11712. face.c = changes[ face.c ];
  11713. indices = [ face.a, face.b, face.c ];
  11714. // if any duplicate vertices are found in a Face3
  11715. // we have to remove the face as nothing can be saved
  11716. for ( var n = 0; n < 3; n ++ ) {
  11717. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  11718. faceIndicesToRemove.push( i );
  11719. break;
  11720. }
  11721. }
  11722. }
  11723. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  11724. var idx = faceIndicesToRemove[ i ];
  11725. this.faces.splice( idx, 1 );
  11726. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  11727. this.faceVertexUvs[ j ].splice( idx, 1 );
  11728. }
  11729. }
  11730. // Use unique set of vertices
  11731. var diff = this.vertices.length - unique.length;
  11732. this.vertices = unique;
  11733. return diff;
  11734. },
  11735. setFromPoints: function ( points ) {
  11736. this.vertices = [];
  11737. for ( var i = 0, l = points.length; i < l; i ++ ) {
  11738. var point = points[ i ];
  11739. this.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  11740. }
  11741. return this;
  11742. },
  11743. sortFacesByMaterialIndex: function () {
  11744. var faces = this.faces;
  11745. var length = faces.length;
  11746. // tag faces
  11747. for ( var i = 0; i < length; i ++ ) {
  11748. faces[ i ]._id = i;
  11749. }
  11750. // sort faces
  11751. function materialIndexSort( a, b ) {
  11752. return a.materialIndex - b.materialIndex;
  11753. }
  11754. faces.sort( materialIndexSort );
  11755. // sort uvs
  11756. var uvs1 = this.faceVertexUvs[ 0 ];
  11757. var uvs2 = this.faceVertexUvs[ 1 ];
  11758. var newUvs1, newUvs2;
  11759. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  11760. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  11761. for ( var i = 0; i < length; i ++ ) {
  11762. var id = faces[ i ]._id;
  11763. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  11764. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  11765. }
  11766. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  11767. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  11768. },
  11769. toJSON: function () {
  11770. var data = {
  11771. metadata: {
  11772. version: 4.5,
  11773. type: 'Geometry',
  11774. generator: 'Geometry.toJSON'
  11775. }
  11776. };
  11777. // standard Geometry serialization
  11778. data.uuid = this.uuid;
  11779. data.type = this.type;
  11780. if ( this.name !== '' ) data.name = this.name;
  11781. if ( this.parameters !== undefined ) {
  11782. var parameters = this.parameters;
  11783. for ( var key in parameters ) {
  11784. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  11785. }
  11786. return data;
  11787. }
  11788. var vertices = [];
  11789. for ( var i = 0; i < this.vertices.length; i ++ ) {
  11790. var vertex = this.vertices[ i ];
  11791. vertices.push( vertex.x, vertex.y, vertex.z );
  11792. }
  11793. var faces = [];
  11794. var normals = [];
  11795. var normalsHash = {};
  11796. var colors = [];
  11797. var colorsHash = {};
  11798. var uvs = [];
  11799. var uvsHash = {};
  11800. for ( var i = 0; i < this.faces.length; i ++ ) {
  11801. var face = this.faces[ i ];
  11802. var hasMaterial = true;
  11803. var hasFaceUv = false; // deprecated
  11804. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  11805. var hasFaceNormal = face.normal.length() > 0;
  11806. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  11807. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  11808. var hasFaceVertexColor = face.vertexColors.length > 0;
  11809. var faceType = 0;
  11810. faceType = setBit( faceType, 0, 0 ); // isQuad
  11811. faceType = setBit( faceType, 1, hasMaterial );
  11812. faceType = setBit( faceType, 2, hasFaceUv );
  11813. faceType = setBit( faceType, 3, hasFaceVertexUv );
  11814. faceType = setBit( faceType, 4, hasFaceNormal );
  11815. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  11816. faceType = setBit( faceType, 6, hasFaceColor );
  11817. faceType = setBit( faceType, 7, hasFaceVertexColor );
  11818. faces.push( faceType );
  11819. faces.push( face.a, face.b, face.c );
  11820. faces.push( face.materialIndex );
  11821. if ( hasFaceVertexUv ) {
  11822. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  11823. faces.push(
  11824. getUvIndex( faceVertexUvs[ 0 ] ),
  11825. getUvIndex( faceVertexUvs[ 1 ] ),
  11826. getUvIndex( faceVertexUvs[ 2 ] )
  11827. );
  11828. }
  11829. if ( hasFaceNormal ) {
  11830. faces.push( getNormalIndex( face.normal ) );
  11831. }
  11832. if ( hasFaceVertexNormal ) {
  11833. var vertexNormals = face.vertexNormals;
  11834. faces.push(
  11835. getNormalIndex( vertexNormals[ 0 ] ),
  11836. getNormalIndex( vertexNormals[ 1 ] ),
  11837. getNormalIndex( vertexNormals[ 2 ] )
  11838. );
  11839. }
  11840. if ( hasFaceColor ) {
  11841. faces.push( getColorIndex( face.color ) );
  11842. }
  11843. if ( hasFaceVertexColor ) {
  11844. var vertexColors = face.vertexColors;
  11845. faces.push(
  11846. getColorIndex( vertexColors[ 0 ] ),
  11847. getColorIndex( vertexColors[ 1 ] ),
  11848. getColorIndex( vertexColors[ 2 ] )
  11849. );
  11850. }
  11851. }
  11852. function setBit( value, position, enabled ) {
  11853. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  11854. }
  11855. function getNormalIndex( normal ) {
  11856. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  11857. if ( normalsHash[ hash ] !== undefined ) {
  11858. return normalsHash[ hash ];
  11859. }
  11860. normalsHash[ hash ] = normals.length / 3;
  11861. normals.push( normal.x, normal.y, normal.z );
  11862. return normalsHash[ hash ];
  11863. }
  11864. function getColorIndex( color ) {
  11865. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  11866. if ( colorsHash[ hash ] !== undefined ) {
  11867. return colorsHash[ hash ];
  11868. }
  11869. colorsHash[ hash ] = colors.length;
  11870. colors.push( color.getHex() );
  11871. return colorsHash[ hash ];
  11872. }
  11873. function getUvIndex( uv ) {
  11874. var hash = uv.x.toString() + uv.y.toString();
  11875. if ( uvsHash[ hash ] !== undefined ) {
  11876. return uvsHash[ hash ];
  11877. }
  11878. uvsHash[ hash ] = uvs.length / 2;
  11879. uvs.push( uv.x, uv.y );
  11880. return uvsHash[ hash ];
  11881. }
  11882. data.data = {};
  11883. data.data.vertices = vertices;
  11884. data.data.normals = normals;
  11885. if ( colors.length > 0 ) data.data.colors = colors;
  11886. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  11887. data.data.faces = faces;
  11888. return data;
  11889. },
  11890. clone: function () {
  11891. /*
  11892. // Handle primitives
  11893. var parameters = this.parameters;
  11894. if ( parameters !== undefined ) {
  11895. var values = [];
  11896. for ( var key in parameters ) {
  11897. values.push( parameters[ key ] );
  11898. }
  11899. var geometry = Object.create( this.constructor.prototype );
  11900. this.constructor.apply( geometry, values );
  11901. return geometry;
  11902. }
  11903. return new this.constructor().copy( this );
  11904. */
  11905. return new Geometry().copy( this );
  11906. },
  11907. copy: function ( source ) {
  11908. var i, il, j, jl, k, kl;
  11909. // reset
  11910. this.vertices = [];
  11911. this.colors = [];
  11912. this.faces = [];
  11913. this.faceVertexUvs = [[]];
  11914. this.morphTargets = [];
  11915. this.morphNormals = [];
  11916. this.skinWeights = [];
  11917. this.skinIndices = [];
  11918. this.lineDistances = [];
  11919. this.boundingBox = null;
  11920. this.boundingSphere = null;
  11921. // name
  11922. this.name = source.name;
  11923. // vertices
  11924. var vertices = source.vertices;
  11925. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  11926. this.vertices.push( vertices[ i ].clone() );
  11927. }
  11928. // colors
  11929. var colors = source.colors;
  11930. for ( i = 0, il = colors.length; i < il; i ++ ) {
  11931. this.colors.push( colors[ i ].clone() );
  11932. }
  11933. // faces
  11934. var faces = source.faces;
  11935. for ( i = 0, il = faces.length; i < il; i ++ ) {
  11936. this.faces.push( faces[ i ].clone() );
  11937. }
  11938. // face vertex uvs
  11939. for ( i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  11940. var faceVertexUvs = source.faceVertexUvs[ i ];
  11941. if ( this.faceVertexUvs[ i ] === undefined ) {
  11942. this.faceVertexUvs[ i ] = [];
  11943. }
  11944. for ( j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  11945. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  11946. for ( k = 0, kl = uvs.length; k < kl; k ++ ) {
  11947. var uv = uvs[ k ];
  11948. uvsCopy.push( uv.clone() );
  11949. }
  11950. this.faceVertexUvs[ i ].push( uvsCopy );
  11951. }
  11952. }
  11953. // morph targets
  11954. var morphTargets = source.morphTargets;
  11955. for ( i = 0, il = morphTargets.length; i < il; i ++ ) {
  11956. var morphTarget = {};
  11957. morphTarget.name = morphTargets[ i ].name;
  11958. // vertices
  11959. if ( morphTargets[ i ].vertices !== undefined ) {
  11960. morphTarget.vertices = [];
  11961. for ( j = 0, jl = morphTargets[ i ].vertices.length; j < jl; j ++ ) {
  11962. morphTarget.vertices.push( morphTargets[ i ].vertices[ j ].clone() );
  11963. }
  11964. }
  11965. // normals
  11966. if ( morphTargets[ i ].normals !== undefined ) {
  11967. morphTarget.normals = [];
  11968. for ( j = 0, jl = morphTargets[ i ].normals.length; j < jl; j ++ ) {
  11969. morphTarget.normals.push( morphTargets[ i ].normals[ j ].clone() );
  11970. }
  11971. }
  11972. this.morphTargets.push( morphTarget );
  11973. }
  11974. // morph normals
  11975. var morphNormals = source.morphNormals;
  11976. for ( i = 0, il = morphNormals.length; i < il; i ++ ) {
  11977. var morphNormal = {};
  11978. // vertex normals
  11979. if ( morphNormals[ i ].vertexNormals !== undefined ) {
  11980. morphNormal.vertexNormals = [];
  11981. for ( j = 0, jl = morphNormals[ i ].vertexNormals.length; j < jl; j ++ ) {
  11982. var srcVertexNormal = morphNormals[ i ].vertexNormals[ j ];
  11983. var destVertexNormal = {};
  11984. destVertexNormal.a = srcVertexNormal.a.clone();
  11985. destVertexNormal.b = srcVertexNormal.b.clone();
  11986. destVertexNormal.c = srcVertexNormal.c.clone();
  11987. morphNormal.vertexNormals.push( destVertexNormal );
  11988. }
  11989. }
  11990. // face normals
  11991. if ( morphNormals[ i ].faceNormals !== undefined ) {
  11992. morphNormal.faceNormals = [];
  11993. for ( j = 0, jl = morphNormals[ i ].faceNormals.length; j < jl; j ++ ) {
  11994. morphNormal.faceNormals.push( morphNormals[ i ].faceNormals[ j ].clone() );
  11995. }
  11996. }
  11997. this.morphNormals.push( morphNormal );
  11998. }
  11999. // skin weights
  12000. var skinWeights = source.skinWeights;
  12001. for ( i = 0, il = skinWeights.length; i < il; i ++ ) {
  12002. this.skinWeights.push( skinWeights[ i ].clone() );
  12003. }
  12004. // skin indices
  12005. var skinIndices = source.skinIndices;
  12006. for ( i = 0, il = skinIndices.length; i < il; i ++ ) {
  12007. this.skinIndices.push( skinIndices[ i ].clone() );
  12008. }
  12009. // line distances
  12010. var lineDistances = source.lineDistances;
  12011. for ( i = 0, il = lineDistances.length; i < il; i ++ ) {
  12012. this.lineDistances.push( lineDistances[ i ] );
  12013. }
  12014. // bounding box
  12015. var boundingBox = source.boundingBox;
  12016. if ( boundingBox !== null ) {
  12017. this.boundingBox = boundingBox.clone();
  12018. }
  12019. // bounding sphere
  12020. var boundingSphere = source.boundingSphere;
  12021. if ( boundingSphere !== null ) {
  12022. this.boundingSphere = boundingSphere.clone();
  12023. }
  12024. // update flags
  12025. this.elementsNeedUpdate = source.elementsNeedUpdate;
  12026. this.verticesNeedUpdate = source.verticesNeedUpdate;
  12027. this.uvsNeedUpdate = source.uvsNeedUpdate;
  12028. this.normalsNeedUpdate = source.normalsNeedUpdate;
  12029. this.colorsNeedUpdate = source.colorsNeedUpdate;
  12030. this.lineDistancesNeedUpdate = source.lineDistancesNeedUpdate;
  12031. this.groupsNeedUpdate = source.groupsNeedUpdate;
  12032. return this;
  12033. },
  12034. dispose: function () {
  12035. this.dispatchEvent( { type: 'dispose' } );
  12036. }
  12037. } );
  12038. /**
  12039. * @author mrdoob / http://mrdoob.com/
  12040. */
  12041. function BufferAttribute( array, itemSize, normalized ) {
  12042. if ( Array.isArray( array ) ) {
  12043. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12044. }
  12045. this.uuid = _Math.generateUUID();
  12046. this.name = '';
  12047. this.array = array;
  12048. this.itemSize = itemSize;
  12049. this.count = array !== undefined ? array.length / itemSize : 0;
  12050. this.normalized = normalized === true;
  12051. this.dynamic = false;
  12052. this.updateRange = { offset: 0, count: - 1 };
  12053. this.onUploadCallback = function () {};
  12054. this.version = 0;
  12055. }
  12056. Object.defineProperty( BufferAttribute.prototype, 'needsUpdate', {
  12057. set: function ( value ) {
  12058. if ( value === true ) this.version ++;
  12059. }
  12060. } );
  12061. Object.assign( BufferAttribute.prototype, {
  12062. isBufferAttribute: true,
  12063. setArray: function ( array ) {
  12064. if ( Array.isArray( array ) ) {
  12065. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  12066. }
  12067. this.count = array !== undefined ? array.length / this.itemSize : 0;
  12068. this.array = array;
  12069. },
  12070. setDynamic: function ( value ) {
  12071. this.dynamic = value;
  12072. return this;
  12073. },
  12074. copy: function ( source ) {
  12075. this.array = new source.array.constructor( source.array );
  12076. this.itemSize = source.itemSize;
  12077. this.count = source.count;
  12078. this.normalized = source.normalized;
  12079. this.dynamic = source.dynamic;
  12080. return this;
  12081. },
  12082. copyAt: function ( index1, attribute, index2 ) {
  12083. index1 *= this.itemSize;
  12084. index2 *= attribute.itemSize;
  12085. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  12086. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  12087. }
  12088. return this;
  12089. },
  12090. copyArray: function ( array ) {
  12091. this.array.set( array );
  12092. return this;
  12093. },
  12094. copyColorsArray: function ( colors ) {
  12095. var array = this.array, offset = 0;
  12096. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  12097. var color = colors[ i ];
  12098. if ( color === undefined ) {
  12099. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  12100. color = new Color();
  12101. }
  12102. array[ offset ++ ] = color.r;
  12103. array[ offset ++ ] = color.g;
  12104. array[ offset ++ ] = color.b;
  12105. }
  12106. return this;
  12107. },
  12108. copyIndicesArray: function ( indices ) {
  12109. var array = this.array, offset = 0;
  12110. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12111. var index = indices[ i ];
  12112. array[ offset ++ ] = index.a;
  12113. array[ offset ++ ] = index.b;
  12114. array[ offset ++ ] = index.c;
  12115. }
  12116. return this;
  12117. },
  12118. copyVector2sArray: function ( vectors ) {
  12119. var array = this.array, offset = 0;
  12120. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12121. var vector = vectors[ i ];
  12122. if ( vector === undefined ) {
  12123. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  12124. vector = new Vector2();
  12125. }
  12126. array[ offset ++ ] = vector.x;
  12127. array[ offset ++ ] = vector.y;
  12128. }
  12129. return this;
  12130. },
  12131. copyVector3sArray: function ( vectors ) {
  12132. var array = this.array, offset = 0;
  12133. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12134. var vector = vectors[ i ];
  12135. if ( vector === undefined ) {
  12136. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  12137. vector = new Vector3();
  12138. }
  12139. array[ offset ++ ] = vector.x;
  12140. array[ offset ++ ] = vector.y;
  12141. array[ offset ++ ] = vector.z;
  12142. }
  12143. return this;
  12144. },
  12145. copyVector4sArray: function ( vectors ) {
  12146. var array = this.array, offset = 0;
  12147. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  12148. var vector = vectors[ i ];
  12149. if ( vector === undefined ) {
  12150. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  12151. vector = new Vector4();
  12152. }
  12153. array[ offset ++ ] = vector.x;
  12154. array[ offset ++ ] = vector.y;
  12155. array[ offset ++ ] = vector.z;
  12156. array[ offset ++ ] = vector.w;
  12157. }
  12158. return this;
  12159. },
  12160. set: function ( value, offset ) {
  12161. if ( offset === undefined ) offset = 0;
  12162. this.array.set( value, offset );
  12163. return this;
  12164. },
  12165. getX: function ( index ) {
  12166. return this.array[ index * this.itemSize ];
  12167. },
  12168. setX: function ( index, x ) {
  12169. this.array[ index * this.itemSize ] = x;
  12170. return this;
  12171. },
  12172. getY: function ( index ) {
  12173. return this.array[ index * this.itemSize + 1 ];
  12174. },
  12175. setY: function ( index, y ) {
  12176. this.array[ index * this.itemSize + 1 ] = y;
  12177. return this;
  12178. },
  12179. getZ: function ( index ) {
  12180. return this.array[ index * this.itemSize + 2 ];
  12181. },
  12182. setZ: function ( index, z ) {
  12183. this.array[ index * this.itemSize + 2 ] = z;
  12184. return this;
  12185. },
  12186. getW: function ( index ) {
  12187. return this.array[ index * this.itemSize + 3 ];
  12188. },
  12189. setW: function ( index, w ) {
  12190. this.array[ index * this.itemSize + 3 ] = w;
  12191. return this;
  12192. },
  12193. setXY: function ( index, x, y ) {
  12194. index *= this.itemSize;
  12195. this.array[ index + 0 ] = x;
  12196. this.array[ index + 1 ] = y;
  12197. return this;
  12198. },
  12199. setXYZ: function ( index, x, y, z ) {
  12200. index *= this.itemSize;
  12201. this.array[ index + 0 ] = x;
  12202. this.array[ index + 1 ] = y;
  12203. this.array[ index + 2 ] = z;
  12204. return this;
  12205. },
  12206. setXYZW: function ( index, x, y, z, w ) {
  12207. index *= this.itemSize;
  12208. this.array[ index + 0 ] = x;
  12209. this.array[ index + 1 ] = y;
  12210. this.array[ index + 2 ] = z;
  12211. this.array[ index + 3 ] = w;
  12212. return this;
  12213. },
  12214. onUpload: function ( callback ) {
  12215. this.onUploadCallback = callback;
  12216. return this;
  12217. },
  12218. clone: function () {
  12219. return new this.constructor( this.array, this.itemSize ).copy( this );
  12220. }
  12221. } );
  12222. //
  12223. function Int8BufferAttribute( array, itemSize, normalized ) {
  12224. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  12225. }
  12226. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12227. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  12228. function Uint8BufferAttribute( array, itemSize, normalized ) {
  12229. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  12230. }
  12231. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12232. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  12233. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  12234. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  12235. }
  12236. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12237. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  12238. function Int16BufferAttribute( array, itemSize, normalized ) {
  12239. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  12240. }
  12241. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12242. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  12243. function Uint16BufferAttribute( array, itemSize, normalized ) {
  12244. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  12245. }
  12246. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12247. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  12248. function Int32BufferAttribute( array, itemSize, normalized ) {
  12249. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  12250. }
  12251. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12252. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  12253. function Uint32BufferAttribute( array, itemSize, normalized ) {
  12254. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  12255. }
  12256. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12257. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  12258. function Float32BufferAttribute( array, itemSize, normalized ) {
  12259. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  12260. }
  12261. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12262. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  12263. function Float64BufferAttribute( array, itemSize, normalized ) {
  12264. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  12265. }
  12266. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  12267. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  12268. /**
  12269. * @author mrdoob / http://mrdoob.com/
  12270. */
  12271. function DirectGeometry() {
  12272. this.indices = [];
  12273. this.vertices = [];
  12274. this.normals = [];
  12275. this.colors = [];
  12276. this.uvs = [];
  12277. this.uvs2 = [];
  12278. this.groups = [];
  12279. this.morphTargets = {};
  12280. this.skinWeights = [];
  12281. this.skinIndices = [];
  12282. // this.lineDistances = [];
  12283. this.boundingBox = null;
  12284. this.boundingSphere = null;
  12285. // update flags
  12286. this.verticesNeedUpdate = false;
  12287. this.normalsNeedUpdate = false;
  12288. this.colorsNeedUpdate = false;
  12289. this.uvsNeedUpdate = false;
  12290. this.groupsNeedUpdate = false;
  12291. }
  12292. Object.assign( DirectGeometry.prototype, {
  12293. computeGroups: function ( geometry ) {
  12294. var group;
  12295. var groups = [];
  12296. var materialIndex = undefined;
  12297. var faces = geometry.faces;
  12298. for ( var i = 0; i < faces.length; i ++ ) {
  12299. var face = faces[ i ];
  12300. // materials
  12301. if ( face.materialIndex !== materialIndex ) {
  12302. materialIndex = face.materialIndex;
  12303. if ( group !== undefined ) {
  12304. group.count = ( i * 3 ) - group.start;
  12305. groups.push( group );
  12306. }
  12307. group = {
  12308. start: i * 3,
  12309. materialIndex: materialIndex
  12310. };
  12311. }
  12312. }
  12313. if ( group !== undefined ) {
  12314. group.count = ( i * 3 ) - group.start;
  12315. groups.push( group );
  12316. }
  12317. this.groups = groups;
  12318. },
  12319. fromGeometry: function ( geometry ) {
  12320. var faces = geometry.faces;
  12321. var vertices = geometry.vertices;
  12322. var faceVertexUvs = geometry.faceVertexUvs;
  12323. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  12324. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  12325. // morphs
  12326. var morphTargets = geometry.morphTargets;
  12327. var morphTargetsLength = morphTargets.length;
  12328. var morphTargetsPosition;
  12329. if ( morphTargetsLength > 0 ) {
  12330. morphTargetsPosition = [];
  12331. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  12332. morphTargetsPosition[ i ] = [];
  12333. }
  12334. this.morphTargets.position = morphTargetsPosition;
  12335. }
  12336. var morphNormals = geometry.morphNormals;
  12337. var morphNormalsLength = morphNormals.length;
  12338. var morphTargetsNormal;
  12339. if ( morphNormalsLength > 0 ) {
  12340. morphTargetsNormal = [];
  12341. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  12342. morphTargetsNormal[ i ] = [];
  12343. }
  12344. this.morphTargets.normal = morphTargetsNormal;
  12345. }
  12346. // skins
  12347. var skinIndices = geometry.skinIndices;
  12348. var skinWeights = geometry.skinWeights;
  12349. var hasSkinIndices = skinIndices.length === vertices.length;
  12350. var hasSkinWeights = skinWeights.length === vertices.length;
  12351. //
  12352. for ( var i = 0; i < faces.length; i ++ ) {
  12353. var face = faces[ i ];
  12354. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  12355. var vertexNormals = face.vertexNormals;
  12356. if ( vertexNormals.length === 3 ) {
  12357. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  12358. } else {
  12359. var normal = face.normal;
  12360. this.normals.push( normal, normal, normal );
  12361. }
  12362. var vertexColors = face.vertexColors;
  12363. if ( vertexColors.length === 3 ) {
  12364. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  12365. } else {
  12366. var color = face.color;
  12367. this.colors.push( color, color, color );
  12368. }
  12369. if ( hasFaceVertexUv === true ) {
  12370. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  12371. if ( vertexUvs !== undefined ) {
  12372. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12373. } else {
  12374. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  12375. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  12376. }
  12377. }
  12378. if ( hasFaceVertexUv2 === true ) {
  12379. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  12380. if ( vertexUvs !== undefined ) {
  12381. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  12382. } else {
  12383. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  12384. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  12385. }
  12386. }
  12387. // morphs
  12388. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  12389. var morphTarget = morphTargets[ j ].vertices;
  12390. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  12391. }
  12392. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  12393. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  12394. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  12395. }
  12396. // skins
  12397. if ( hasSkinIndices ) {
  12398. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  12399. }
  12400. if ( hasSkinWeights ) {
  12401. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  12402. }
  12403. }
  12404. this.computeGroups( geometry );
  12405. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12406. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12407. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12408. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12409. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12410. return this;
  12411. }
  12412. } );
  12413. /**
  12414. * @author mrdoob / http://mrdoob.com/
  12415. */
  12416. function arrayMax( array ) {
  12417. if ( array.length === 0 ) return - Infinity;
  12418. var max = array[ 0 ];
  12419. for ( var i = 1, l = array.length; i < l; ++ i ) {
  12420. if ( array[ i ] > max ) max = array[ i ];
  12421. }
  12422. return max;
  12423. }
  12424. /**
  12425. * @author alteredq / http://alteredqualia.com/
  12426. * @author mrdoob / http://mrdoob.com/
  12427. */
  12428. var bufferGeometryId = 1; // BufferGeometry uses odd numbers as Id
  12429. function BufferGeometry() {
  12430. Object.defineProperty( this, 'id', { value: bufferGeometryId += 2 } );
  12431. this.uuid = _Math.generateUUID();
  12432. this.name = '';
  12433. this.type = 'BufferGeometry';
  12434. this.index = null;
  12435. this.attributes = {};
  12436. this.morphAttributes = {};
  12437. this.groups = [];
  12438. this.boundingBox = null;
  12439. this.boundingSphere = null;
  12440. this.drawRange = { start: 0, count: Infinity };
  12441. }
  12442. BufferGeometry.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  12443. constructor: BufferGeometry,
  12444. isBufferGeometry: true,
  12445. getIndex: function () {
  12446. return this.index;
  12447. },
  12448. setIndex: function ( index ) {
  12449. if ( Array.isArray( index ) ) {
  12450. this.index = new ( arrayMax( index ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( index, 1 );
  12451. } else {
  12452. this.index = index;
  12453. }
  12454. },
  12455. addAttribute: function ( name, attribute ) {
  12456. if ( ! ( attribute && attribute.isBufferAttribute ) && ! ( attribute && attribute.isInterleavedBufferAttribute ) ) {
  12457. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  12458. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  12459. return;
  12460. }
  12461. if ( name === 'index' ) {
  12462. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  12463. this.setIndex( attribute );
  12464. return;
  12465. }
  12466. this.attributes[ name ] = attribute;
  12467. return this;
  12468. },
  12469. getAttribute: function ( name ) {
  12470. return this.attributes[ name ];
  12471. },
  12472. removeAttribute: function ( name ) {
  12473. delete this.attributes[ name ];
  12474. return this;
  12475. },
  12476. addGroup: function ( start, count, materialIndex ) {
  12477. this.groups.push( {
  12478. start: start,
  12479. count: count,
  12480. materialIndex: materialIndex !== undefined ? materialIndex : 0
  12481. } );
  12482. },
  12483. clearGroups: function () {
  12484. this.groups = [];
  12485. },
  12486. setDrawRange: function ( start, count ) {
  12487. this.drawRange.start = start;
  12488. this.drawRange.count = count;
  12489. },
  12490. applyMatrix: function ( matrix ) {
  12491. var position = this.attributes.position;
  12492. if ( position !== undefined ) {
  12493. matrix.applyToBufferAttribute( position );
  12494. position.needsUpdate = true;
  12495. }
  12496. var normal = this.attributes.normal;
  12497. if ( normal !== undefined ) {
  12498. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12499. normalMatrix.applyToBufferAttribute( normal );
  12500. normal.needsUpdate = true;
  12501. }
  12502. if ( this.boundingBox !== null ) {
  12503. this.computeBoundingBox();
  12504. }
  12505. if ( this.boundingSphere !== null ) {
  12506. this.computeBoundingSphere();
  12507. }
  12508. return this;
  12509. },
  12510. rotateX: function () {
  12511. // rotate geometry around world x-axis
  12512. var m1 = new Matrix4();
  12513. return function rotateX( angle ) {
  12514. m1.makeRotationX( angle );
  12515. this.applyMatrix( m1 );
  12516. return this;
  12517. };
  12518. }(),
  12519. rotateY: function () {
  12520. // rotate geometry around world y-axis
  12521. var m1 = new Matrix4();
  12522. return function rotateY( angle ) {
  12523. m1.makeRotationY( angle );
  12524. this.applyMatrix( m1 );
  12525. return this;
  12526. };
  12527. }(),
  12528. rotateZ: function () {
  12529. // rotate geometry around world z-axis
  12530. var m1 = new Matrix4();
  12531. return function rotateZ( angle ) {
  12532. m1.makeRotationZ( angle );
  12533. this.applyMatrix( m1 );
  12534. return this;
  12535. };
  12536. }(),
  12537. translate: function () {
  12538. // translate geometry
  12539. var m1 = new Matrix4();
  12540. return function translate( x, y, z ) {
  12541. m1.makeTranslation( x, y, z );
  12542. this.applyMatrix( m1 );
  12543. return this;
  12544. };
  12545. }(),
  12546. scale: function () {
  12547. // scale geometry
  12548. var m1 = new Matrix4();
  12549. return function scale( x, y, z ) {
  12550. m1.makeScale( x, y, z );
  12551. this.applyMatrix( m1 );
  12552. return this;
  12553. };
  12554. }(),
  12555. lookAt: function () {
  12556. var obj = new Object3D();
  12557. return function lookAt( vector ) {
  12558. obj.lookAt( vector );
  12559. obj.updateMatrix();
  12560. this.applyMatrix( obj.matrix );
  12561. };
  12562. }(),
  12563. center: function () {
  12564. this.computeBoundingBox();
  12565. var offset = this.boundingBox.getCenter().negate();
  12566. this.translate( offset.x, offset.y, offset.z );
  12567. return offset;
  12568. },
  12569. setFromObject: function ( object ) {
  12570. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  12571. var geometry = object.geometry;
  12572. if ( object.isPoints || object.isLine ) {
  12573. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  12574. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  12575. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  12576. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  12577. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  12578. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  12579. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  12580. }
  12581. if ( geometry.boundingSphere !== null ) {
  12582. this.boundingSphere = geometry.boundingSphere.clone();
  12583. }
  12584. if ( geometry.boundingBox !== null ) {
  12585. this.boundingBox = geometry.boundingBox.clone();
  12586. }
  12587. } else if ( object.isMesh ) {
  12588. if ( geometry && geometry.isGeometry ) {
  12589. this.fromGeometry( geometry );
  12590. }
  12591. }
  12592. return this;
  12593. },
  12594. setFromPoints: function ( points ) {
  12595. var position = [];
  12596. for ( var i = 0, l = points.length; i < l; i ++ ) {
  12597. var point = points[ i ];
  12598. position.push( point.x, point.y, point.z || 0 );
  12599. }
  12600. this.addAttribute( 'position', new Float32BufferAttribute( position, 3 ) );
  12601. return this;
  12602. },
  12603. updateFromObject: function ( object ) {
  12604. var geometry = object.geometry;
  12605. if ( object.isMesh ) {
  12606. var direct = geometry.__directGeometry;
  12607. if ( geometry.elementsNeedUpdate === true ) {
  12608. direct = undefined;
  12609. geometry.elementsNeedUpdate = false;
  12610. }
  12611. if ( direct === undefined ) {
  12612. return this.fromGeometry( geometry );
  12613. }
  12614. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12615. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12616. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12617. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12618. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12619. geometry.verticesNeedUpdate = false;
  12620. geometry.normalsNeedUpdate = false;
  12621. geometry.colorsNeedUpdate = false;
  12622. geometry.uvsNeedUpdate = false;
  12623. geometry.groupsNeedUpdate = false;
  12624. geometry = direct;
  12625. }
  12626. var attribute;
  12627. if ( geometry.verticesNeedUpdate === true ) {
  12628. attribute = this.attributes.position;
  12629. if ( attribute !== undefined ) {
  12630. attribute.copyVector3sArray( geometry.vertices );
  12631. attribute.needsUpdate = true;
  12632. }
  12633. geometry.verticesNeedUpdate = false;
  12634. }
  12635. if ( geometry.normalsNeedUpdate === true ) {
  12636. attribute = this.attributes.normal;
  12637. if ( attribute !== undefined ) {
  12638. attribute.copyVector3sArray( geometry.normals );
  12639. attribute.needsUpdate = true;
  12640. }
  12641. geometry.normalsNeedUpdate = false;
  12642. }
  12643. if ( geometry.colorsNeedUpdate === true ) {
  12644. attribute = this.attributes.color;
  12645. if ( attribute !== undefined ) {
  12646. attribute.copyColorsArray( geometry.colors );
  12647. attribute.needsUpdate = true;
  12648. }
  12649. geometry.colorsNeedUpdate = false;
  12650. }
  12651. if ( geometry.uvsNeedUpdate ) {
  12652. attribute = this.attributes.uv;
  12653. if ( attribute !== undefined ) {
  12654. attribute.copyVector2sArray( geometry.uvs );
  12655. attribute.needsUpdate = true;
  12656. }
  12657. geometry.uvsNeedUpdate = false;
  12658. }
  12659. if ( geometry.lineDistancesNeedUpdate ) {
  12660. attribute = this.attributes.lineDistance;
  12661. if ( attribute !== undefined ) {
  12662. attribute.copyArray( geometry.lineDistances );
  12663. attribute.needsUpdate = true;
  12664. }
  12665. geometry.lineDistancesNeedUpdate = false;
  12666. }
  12667. if ( geometry.groupsNeedUpdate ) {
  12668. geometry.computeGroups( object.geometry );
  12669. this.groups = geometry.groups;
  12670. geometry.groupsNeedUpdate = false;
  12671. }
  12672. return this;
  12673. },
  12674. fromGeometry: function ( geometry ) {
  12675. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  12676. return this.fromDirectGeometry( geometry.__directGeometry );
  12677. },
  12678. fromDirectGeometry: function ( geometry ) {
  12679. var positions = new Float32Array( geometry.vertices.length * 3 );
  12680. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  12681. if ( geometry.normals.length > 0 ) {
  12682. var normals = new Float32Array( geometry.normals.length * 3 );
  12683. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  12684. }
  12685. if ( geometry.colors.length > 0 ) {
  12686. var colors = new Float32Array( geometry.colors.length * 3 );
  12687. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  12688. }
  12689. if ( geometry.uvs.length > 0 ) {
  12690. var uvs = new Float32Array( geometry.uvs.length * 2 );
  12691. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  12692. }
  12693. if ( geometry.uvs2.length > 0 ) {
  12694. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  12695. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  12696. }
  12697. if ( geometry.indices.length > 0 ) {
  12698. var TypeArray = arrayMax( geometry.indices ) > 65535 ? Uint32Array : Uint16Array;
  12699. var indices = new TypeArray( geometry.indices.length * 3 );
  12700. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  12701. }
  12702. // groups
  12703. this.groups = geometry.groups;
  12704. // morphs
  12705. for ( var name in geometry.morphTargets ) {
  12706. var array = [];
  12707. var morphTargets = geometry.morphTargets[ name ];
  12708. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  12709. var morphTarget = morphTargets[ i ];
  12710. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  12711. array.push( attribute.copyVector3sArray( morphTarget ) );
  12712. }
  12713. this.morphAttributes[ name ] = array;
  12714. }
  12715. // skinning
  12716. if ( geometry.skinIndices.length > 0 ) {
  12717. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  12718. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  12719. }
  12720. if ( geometry.skinWeights.length > 0 ) {
  12721. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  12722. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  12723. }
  12724. //
  12725. if ( geometry.boundingSphere !== null ) {
  12726. this.boundingSphere = geometry.boundingSphere.clone();
  12727. }
  12728. if ( geometry.boundingBox !== null ) {
  12729. this.boundingBox = geometry.boundingBox.clone();
  12730. }
  12731. return this;
  12732. },
  12733. computeBoundingBox: function () {
  12734. if ( this.boundingBox === null ) {
  12735. this.boundingBox = new Box3();
  12736. }
  12737. var position = this.attributes.position;
  12738. if ( position !== undefined ) {
  12739. this.boundingBox.setFromBufferAttribute( position );
  12740. } else {
  12741. this.boundingBox.makeEmpty();
  12742. }
  12743. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  12744. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  12745. }
  12746. },
  12747. computeBoundingSphere: function () {
  12748. var box = new Box3();
  12749. var vector = new Vector3();
  12750. return function computeBoundingSphere() {
  12751. if ( this.boundingSphere === null ) {
  12752. this.boundingSphere = new Sphere();
  12753. }
  12754. var position = this.attributes.position;
  12755. if ( position ) {
  12756. var center = this.boundingSphere.center;
  12757. box.setFromBufferAttribute( position );
  12758. box.getCenter( center );
  12759. // hoping to find a boundingSphere with a radius smaller than the
  12760. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12761. var maxRadiusSq = 0;
  12762. for ( var i = 0, il = position.count; i < il; i ++ ) {
  12763. vector.x = position.getX( i );
  12764. vector.y = position.getY( i );
  12765. vector.z = position.getZ( i );
  12766. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  12767. }
  12768. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  12769. if ( isNaN( this.boundingSphere.radius ) ) {
  12770. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  12771. }
  12772. }
  12773. };
  12774. }(),
  12775. computeFaceNormals: function () {
  12776. // backwards compatibility
  12777. },
  12778. computeVertexNormals: function () {
  12779. var index = this.index;
  12780. var attributes = this.attributes;
  12781. var groups = this.groups;
  12782. if ( attributes.position ) {
  12783. var positions = attributes.position.array;
  12784. if ( attributes.normal === undefined ) {
  12785. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  12786. } else {
  12787. // reset existing normals to zero
  12788. var array = attributes.normal.array;
  12789. for ( var i = 0, il = array.length; i < il; i ++ ) {
  12790. array[ i ] = 0;
  12791. }
  12792. }
  12793. var normals = attributes.normal.array;
  12794. var vA, vB, vC;
  12795. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  12796. var cb = new Vector3(), ab = new Vector3();
  12797. // indexed elements
  12798. if ( index ) {
  12799. var indices = index.array;
  12800. if ( groups.length === 0 ) {
  12801. this.addGroup( 0, indices.length );
  12802. }
  12803. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  12804. var group = groups[ j ];
  12805. var start = group.start;
  12806. var count = group.count;
  12807. for ( var i = start, il = start + count; i < il; i += 3 ) {
  12808. vA = indices[ i + 0 ] * 3;
  12809. vB = indices[ i + 1 ] * 3;
  12810. vC = indices[ i + 2 ] * 3;
  12811. pA.fromArray( positions, vA );
  12812. pB.fromArray( positions, vB );
  12813. pC.fromArray( positions, vC );
  12814. cb.subVectors( pC, pB );
  12815. ab.subVectors( pA, pB );
  12816. cb.cross( ab );
  12817. normals[ vA ] += cb.x;
  12818. normals[ vA + 1 ] += cb.y;
  12819. normals[ vA + 2 ] += cb.z;
  12820. normals[ vB ] += cb.x;
  12821. normals[ vB + 1 ] += cb.y;
  12822. normals[ vB + 2 ] += cb.z;
  12823. normals[ vC ] += cb.x;
  12824. normals[ vC + 1 ] += cb.y;
  12825. normals[ vC + 2 ] += cb.z;
  12826. }
  12827. }
  12828. } else {
  12829. // non-indexed elements (unconnected triangle soup)
  12830. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  12831. pA.fromArray( positions, i );
  12832. pB.fromArray( positions, i + 3 );
  12833. pC.fromArray( positions, i + 6 );
  12834. cb.subVectors( pC, pB );
  12835. ab.subVectors( pA, pB );
  12836. cb.cross( ab );
  12837. normals[ i ] = cb.x;
  12838. normals[ i + 1 ] = cb.y;
  12839. normals[ i + 2 ] = cb.z;
  12840. normals[ i + 3 ] = cb.x;
  12841. normals[ i + 4 ] = cb.y;
  12842. normals[ i + 5 ] = cb.z;
  12843. normals[ i + 6 ] = cb.x;
  12844. normals[ i + 7 ] = cb.y;
  12845. normals[ i + 8 ] = cb.z;
  12846. }
  12847. }
  12848. this.normalizeNormals();
  12849. attributes.normal.needsUpdate = true;
  12850. }
  12851. },
  12852. merge: function ( geometry, offset ) {
  12853. if ( ! ( geometry && geometry.isBufferGeometry ) ) {
  12854. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  12855. return;
  12856. }
  12857. if ( offset === undefined ) offset = 0;
  12858. var attributes = this.attributes;
  12859. for ( var key in attributes ) {
  12860. if ( geometry.attributes[ key ] === undefined ) continue;
  12861. var attribute1 = attributes[ key ];
  12862. var attributeArray1 = attribute1.array;
  12863. var attribute2 = geometry.attributes[ key ];
  12864. var attributeArray2 = attribute2.array;
  12865. var attributeSize = attribute2.itemSize;
  12866. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  12867. attributeArray1[ j ] = attributeArray2[ i ];
  12868. }
  12869. }
  12870. return this;
  12871. },
  12872. normalizeNormals: function () {
  12873. var vector = new Vector3();
  12874. return function normalizeNormals() {
  12875. var normals = this.attributes.normal;
  12876. for ( var i = 0, il = normals.count; i < il; i ++ ) {
  12877. vector.x = normals.getX( i );
  12878. vector.y = normals.getY( i );
  12879. vector.z = normals.getZ( i );
  12880. vector.normalize();
  12881. normals.setXYZ( i, vector.x, vector.y, vector.z );
  12882. }
  12883. };
  12884. }(),
  12885. toNonIndexed: function () {
  12886. if ( this.index === null ) {
  12887. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12888. return this;
  12889. }
  12890. var geometry2 = new BufferGeometry();
  12891. var indices = this.index.array;
  12892. var attributes = this.attributes;
  12893. for ( var name in attributes ) {
  12894. var attribute = attributes[ name ];
  12895. var array = attribute.array;
  12896. var itemSize = attribute.itemSize;
  12897. var array2 = new array.constructor( indices.length * itemSize );
  12898. var index = 0, index2 = 0;
  12899. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12900. index = indices[ i ] * itemSize;
  12901. for ( var j = 0; j < itemSize; j ++ ) {
  12902. array2[ index2 ++ ] = array[ index ++ ];
  12903. }
  12904. }
  12905. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  12906. }
  12907. return geometry2;
  12908. },
  12909. toJSON: function () {
  12910. var data = {
  12911. metadata: {
  12912. version: 4.5,
  12913. type: 'BufferGeometry',
  12914. generator: 'BufferGeometry.toJSON'
  12915. }
  12916. };
  12917. // standard BufferGeometry serialization
  12918. data.uuid = this.uuid;
  12919. data.type = this.type;
  12920. if ( this.name !== '' ) data.name = this.name;
  12921. if ( this.parameters !== undefined ) {
  12922. var parameters = this.parameters;
  12923. for ( var key in parameters ) {
  12924. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12925. }
  12926. return data;
  12927. }
  12928. data.data = { attributes: {} };
  12929. var index = this.index;
  12930. if ( index !== null ) {
  12931. var array = Array.prototype.slice.call( index.array );
  12932. data.data.index = {
  12933. type: index.array.constructor.name,
  12934. array: array
  12935. };
  12936. }
  12937. var attributes = this.attributes;
  12938. for ( var key in attributes ) {
  12939. var attribute = attributes[ key ];
  12940. var array = Array.prototype.slice.call( attribute.array );
  12941. data.data.attributes[ key ] = {
  12942. itemSize: attribute.itemSize,
  12943. type: attribute.array.constructor.name,
  12944. array: array,
  12945. normalized: attribute.normalized
  12946. };
  12947. }
  12948. var groups = this.groups;
  12949. if ( groups.length > 0 ) {
  12950. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  12951. }
  12952. var boundingSphere = this.boundingSphere;
  12953. if ( boundingSphere !== null ) {
  12954. data.data.boundingSphere = {
  12955. center: boundingSphere.center.toArray(),
  12956. radius: boundingSphere.radius
  12957. };
  12958. }
  12959. return data;
  12960. },
  12961. clone: function () {
  12962. /*
  12963. // Handle primitives
  12964. var parameters = this.parameters;
  12965. if ( parameters !== undefined ) {
  12966. var values = [];
  12967. for ( var key in parameters ) {
  12968. values.push( parameters[ key ] );
  12969. }
  12970. var geometry = Object.create( this.constructor.prototype );
  12971. this.constructor.apply( geometry, values );
  12972. return geometry;
  12973. }
  12974. return new this.constructor().copy( this );
  12975. */
  12976. return new BufferGeometry().copy( this );
  12977. },
  12978. copy: function ( source ) {
  12979. var name, i, l;
  12980. // reset
  12981. this.index = null;
  12982. this.attributes = {};
  12983. this.morphAttributes = {};
  12984. this.groups = [];
  12985. this.boundingBox = null;
  12986. this.boundingSphere = null;
  12987. // name
  12988. this.name = source.name;
  12989. // index
  12990. var index = source.index;
  12991. if ( index !== null ) {
  12992. this.setIndex( index.clone() );
  12993. }
  12994. // attributes
  12995. var attributes = source.attributes;
  12996. for ( name in attributes ) {
  12997. var attribute = attributes[ name ];
  12998. this.addAttribute( name, attribute.clone() );
  12999. }
  13000. // morph attributes
  13001. var morphAttributes = source.morphAttributes;
  13002. for ( name in morphAttributes ) {
  13003. var array = [];
  13004. var morphAttribute = morphAttributes[ name ]; // morphAttribute: array of Float32BufferAttributes
  13005. for ( i = 0, l = morphAttribute.length; i < l; i ++ ) {
  13006. array.push( morphAttribute[ i ].clone() );
  13007. }
  13008. this.morphAttributes[ name ] = array;
  13009. }
  13010. // groups
  13011. var groups = source.groups;
  13012. for ( i = 0, l = groups.length; i < l; i ++ ) {
  13013. var group = groups[ i ];
  13014. this.addGroup( group.start, group.count, group.materialIndex );
  13015. }
  13016. // bounding box
  13017. var boundingBox = source.boundingBox;
  13018. if ( boundingBox !== null ) {
  13019. this.boundingBox = boundingBox.clone();
  13020. }
  13021. // bounding sphere
  13022. var boundingSphere = source.boundingSphere;
  13023. if ( boundingSphere !== null ) {
  13024. this.boundingSphere = boundingSphere.clone();
  13025. }
  13026. // draw range
  13027. this.drawRange.start = source.drawRange.start;
  13028. this.drawRange.count = source.drawRange.count;
  13029. return this;
  13030. },
  13031. dispose: function () {
  13032. this.dispatchEvent( { type: 'dispose' } );
  13033. }
  13034. } );
  13035. /**
  13036. * @author mrdoob / http://mrdoob.com/
  13037. * @author Mugen87 / https://github.com/Mugen87
  13038. */
  13039. // BoxGeometry
  13040. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13041. Geometry.call( this );
  13042. this.type = 'BoxGeometry';
  13043. this.parameters = {
  13044. width: width,
  13045. height: height,
  13046. depth: depth,
  13047. widthSegments: widthSegments,
  13048. heightSegments: heightSegments,
  13049. depthSegments: depthSegments
  13050. };
  13051. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  13052. this.mergeVertices();
  13053. }
  13054. BoxGeometry.prototype = Object.create( Geometry.prototype );
  13055. BoxGeometry.prototype.constructor = BoxGeometry;
  13056. // BoxBufferGeometry
  13057. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13058. BufferGeometry.call( this );
  13059. this.type = 'BoxBufferGeometry';
  13060. this.parameters = {
  13061. width: width,
  13062. height: height,
  13063. depth: depth,
  13064. widthSegments: widthSegments,
  13065. heightSegments: heightSegments,
  13066. depthSegments: depthSegments
  13067. };
  13068. var scope = this;
  13069. width = width || 1;
  13070. height = height || 1;
  13071. depth = depth || 1;
  13072. // segments
  13073. widthSegments = Math.floor( widthSegments ) || 1;
  13074. heightSegments = Math.floor( heightSegments ) || 1;
  13075. depthSegments = Math.floor( depthSegments ) || 1;
  13076. // buffers
  13077. var indices = [];
  13078. var vertices = [];
  13079. var normals = [];
  13080. var uvs = [];
  13081. // helper variables
  13082. var numberOfVertices = 0;
  13083. var groupStart = 0;
  13084. // build each side of the box geometry
  13085. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13086. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13087. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13088. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13089. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13090. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13091. // build geometry
  13092. this.setIndex( indices );
  13093. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13094. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13095. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13096. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13097. var segmentWidth = width / gridX;
  13098. var segmentHeight = height / gridY;
  13099. var widthHalf = width / 2;
  13100. var heightHalf = height / 2;
  13101. var depthHalf = depth / 2;
  13102. var gridX1 = gridX + 1;
  13103. var gridY1 = gridY + 1;
  13104. var vertexCounter = 0;
  13105. var groupCount = 0;
  13106. var ix, iy;
  13107. var vector = new Vector3();
  13108. // generate vertices, normals and uvs
  13109. for ( iy = 0; iy < gridY1; iy ++ ) {
  13110. var y = iy * segmentHeight - heightHalf;
  13111. for ( ix = 0; ix < gridX1; ix ++ ) {
  13112. var x = ix * segmentWidth - widthHalf;
  13113. // set values to correct vector component
  13114. vector[ u ] = x * udir;
  13115. vector[ v ] = y * vdir;
  13116. vector[ w ] = depthHalf;
  13117. // now apply vector to vertex buffer
  13118. vertices.push( vector.x, vector.y, vector.z );
  13119. // set values to correct vector component
  13120. vector[ u ] = 0;
  13121. vector[ v ] = 0;
  13122. vector[ w ] = depth > 0 ? 1 : - 1;
  13123. // now apply vector to normal buffer
  13124. normals.push( vector.x, vector.y, vector.z );
  13125. // uvs
  13126. uvs.push( ix / gridX );
  13127. uvs.push( 1 - ( iy / gridY ) );
  13128. // counters
  13129. vertexCounter += 1;
  13130. }
  13131. }
  13132. // indices
  13133. // 1. you need three indices to draw a single face
  13134. // 2. a single segment consists of two faces
  13135. // 3. so we need to generate six (2*3) indices per segment
  13136. for ( iy = 0; iy < gridY; iy ++ ) {
  13137. for ( ix = 0; ix < gridX; ix ++ ) {
  13138. var a = numberOfVertices + ix + gridX1 * iy;
  13139. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13140. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13141. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13142. // faces
  13143. indices.push( a, b, d );
  13144. indices.push( b, c, d );
  13145. // increase counter
  13146. groupCount += 6;
  13147. }
  13148. }
  13149. // add a group to the geometry. this will ensure multi material support
  13150. scope.addGroup( groupStart, groupCount, materialIndex );
  13151. // calculate new start value for groups
  13152. groupStart += groupCount;
  13153. // update total number of vertices
  13154. numberOfVertices += vertexCounter;
  13155. }
  13156. }
  13157. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13158. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13159. /**
  13160. * @author mrdoob / http://mrdoob.com/
  13161. * @author Mugen87 / https://github.com/Mugen87
  13162. */
  13163. // PlaneGeometry
  13164. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  13165. Geometry.call( this );
  13166. this.type = 'PlaneGeometry';
  13167. this.parameters = {
  13168. width: width,
  13169. height: height,
  13170. widthSegments: widthSegments,
  13171. heightSegments: heightSegments
  13172. };
  13173. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  13174. this.mergeVertices();
  13175. }
  13176. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  13177. PlaneGeometry.prototype.constructor = PlaneGeometry;
  13178. // PlaneBufferGeometry
  13179. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  13180. BufferGeometry.call( this );
  13181. this.type = 'PlaneBufferGeometry';
  13182. this.parameters = {
  13183. width: width,
  13184. height: height,
  13185. widthSegments: widthSegments,
  13186. heightSegments: heightSegments
  13187. };
  13188. width = width || 1;
  13189. height = height || 1;
  13190. var width_half = width / 2;
  13191. var height_half = height / 2;
  13192. var gridX = Math.floor( widthSegments ) || 1;
  13193. var gridY = Math.floor( heightSegments ) || 1;
  13194. var gridX1 = gridX + 1;
  13195. var gridY1 = gridY + 1;
  13196. var segment_width = width / gridX;
  13197. var segment_height = height / gridY;
  13198. var ix, iy;
  13199. // buffers
  13200. var indices = [];
  13201. var vertices = [];
  13202. var normals = [];
  13203. var uvs = [];
  13204. // generate vertices, normals and uvs
  13205. for ( iy = 0; iy < gridY1; iy ++ ) {
  13206. var y = iy * segment_height - height_half;
  13207. for ( ix = 0; ix < gridX1; ix ++ ) {
  13208. var x = ix * segment_width - width_half;
  13209. vertices.push( x, - y, 0 );
  13210. normals.push( 0, 0, 1 );
  13211. uvs.push( ix / gridX );
  13212. uvs.push( 1 - ( iy / gridY ) );
  13213. }
  13214. }
  13215. // indices
  13216. for ( iy = 0; iy < gridY; iy ++ ) {
  13217. for ( ix = 0; ix < gridX; ix ++ ) {
  13218. var a = ix + gridX1 * iy;
  13219. var b = ix + gridX1 * ( iy + 1 );
  13220. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13221. var d = ( ix + 1 ) + gridX1 * iy;
  13222. // faces
  13223. indices.push( a, b, d );
  13224. indices.push( b, c, d );
  13225. }
  13226. }
  13227. // build geometry
  13228. this.setIndex( indices );
  13229. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  13230. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  13231. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  13232. }
  13233. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13234. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  13235. /**
  13236. * @author mrdoob / http://mrdoob.com/
  13237. * @author alteredq / http://alteredqualia.com/
  13238. *
  13239. * parameters = {
  13240. * color: <hex>,
  13241. * opacity: <float>,
  13242. * map: new THREE.Texture( <Image> ),
  13243. *
  13244. * lightMap: new THREE.Texture( <Image> ),
  13245. * lightMapIntensity: <float>
  13246. *
  13247. * aoMap: new THREE.Texture( <Image> ),
  13248. * aoMapIntensity: <float>
  13249. *
  13250. * specularMap: new THREE.Texture( <Image> ),
  13251. *
  13252. * alphaMap: new THREE.Texture( <Image> ),
  13253. *
  13254. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  13255. * combine: THREE.Multiply,
  13256. * reflectivity: <float>,
  13257. * refractionRatio: <float>,
  13258. *
  13259. * depthTest: <bool>,
  13260. * depthWrite: <bool>,
  13261. *
  13262. * wireframe: <boolean>,
  13263. * wireframeLinewidth: <float>,
  13264. *
  13265. * skinning: <bool>,
  13266. * morphTargets: <bool>
  13267. * }
  13268. */
  13269. function MeshBasicMaterial( parameters ) {
  13270. Material.call( this );
  13271. this.type = 'MeshBasicMaterial';
  13272. this.color = new Color( 0xffffff ); // emissive
  13273. this.map = null;
  13274. this.lightMap = null;
  13275. this.lightMapIntensity = 1.0;
  13276. this.aoMap = null;
  13277. this.aoMapIntensity = 1.0;
  13278. this.specularMap = null;
  13279. this.alphaMap = null;
  13280. this.envMap = null;
  13281. this.combine = MultiplyOperation;
  13282. this.reflectivity = 1;
  13283. this.refractionRatio = 0.98;
  13284. this.wireframe = false;
  13285. this.wireframeLinewidth = 1;
  13286. this.wireframeLinecap = 'round';
  13287. this.wireframeLinejoin = 'round';
  13288. this.skinning = false;
  13289. this.morphTargets = false;
  13290. this.lights = false;
  13291. this.setValues( parameters );
  13292. }
  13293. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  13294. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  13295. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  13296. MeshBasicMaterial.prototype.copy = function ( source ) {
  13297. Material.prototype.copy.call( this, source );
  13298. this.color.copy( source.color );
  13299. this.map = source.map;
  13300. this.lightMap = source.lightMap;
  13301. this.lightMapIntensity = source.lightMapIntensity;
  13302. this.aoMap = source.aoMap;
  13303. this.aoMapIntensity = source.aoMapIntensity;
  13304. this.specularMap = source.specularMap;
  13305. this.alphaMap = source.alphaMap;
  13306. this.envMap = source.envMap;
  13307. this.combine = source.combine;
  13308. this.reflectivity = source.reflectivity;
  13309. this.refractionRatio = source.refractionRatio;
  13310. this.wireframe = source.wireframe;
  13311. this.wireframeLinewidth = source.wireframeLinewidth;
  13312. this.wireframeLinecap = source.wireframeLinecap;
  13313. this.wireframeLinejoin = source.wireframeLinejoin;
  13314. this.skinning = source.skinning;
  13315. this.morphTargets = source.morphTargets;
  13316. return this;
  13317. };
  13318. /**
  13319. * @author alteredq / http://alteredqualia.com/
  13320. *
  13321. * parameters = {
  13322. * defines: { "label" : "value" },
  13323. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  13324. *
  13325. * fragmentShader: <string>,
  13326. * vertexShader: <string>,
  13327. *
  13328. * wireframe: <boolean>,
  13329. * wireframeLinewidth: <float>,
  13330. *
  13331. * lights: <bool>,
  13332. *
  13333. * skinning: <bool>,
  13334. * morphTargets: <bool>,
  13335. * morphNormals: <bool>
  13336. * }
  13337. */
  13338. function ShaderMaterial( parameters ) {
  13339. Material.call( this );
  13340. this.type = 'ShaderMaterial';
  13341. this.defines = {};
  13342. this.uniforms = {};
  13343. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  13344. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  13345. this.linewidth = 1;
  13346. this.wireframe = false;
  13347. this.wireframeLinewidth = 1;
  13348. this.fog = false; // set to use scene fog
  13349. this.lights = false; // set to use scene lights
  13350. this.clipping = false; // set to use user-defined clipping planes
  13351. this.skinning = false; // set to use skinning attribute streams
  13352. this.morphTargets = false; // set to use morph targets
  13353. this.morphNormals = false; // set to use morph normals
  13354. this.extensions = {
  13355. derivatives: false, // set to use derivatives
  13356. fragDepth: false, // set to use fragment depth values
  13357. drawBuffers: false, // set to use draw buffers
  13358. shaderTextureLOD: false // set to use shader texture LOD
  13359. };
  13360. // When rendered geometry doesn't include these attributes but the material does,
  13361. // use these default values in WebGL. This avoids errors when buffer data is missing.
  13362. this.defaultAttributeValues = {
  13363. 'color': [ 1, 1, 1 ],
  13364. 'uv': [ 0, 0 ],
  13365. 'uv2': [ 0, 0 ]
  13366. };
  13367. this.index0AttributeName = undefined;
  13368. if ( parameters !== undefined ) {
  13369. if ( parameters.attributes !== undefined ) {
  13370. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  13371. }
  13372. this.setValues( parameters );
  13373. }
  13374. }
  13375. ShaderMaterial.prototype = Object.create( Material.prototype );
  13376. ShaderMaterial.prototype.constructor = ShaderMaterial;
  13377. ShaderMaterial.prototype.isShaderMaterial = true;
  13378. ShaderMaterial.prototype.copy = function ( source ) {
  13379. Material.prototype.copy.call( this, source );
  13380. this.fragmentShader = source.fragmentShader;
  13381. this.vertexShader = source.vertexShader;
  13382. this.uniforms = UniformsUtils.clone( source.uniforms );
  13383. this.defines = source.defines;
  13384. this.wireframe = source.wireframe;
  13385. this.wireframeLinewidth = source.wireframeLinewidth;
  13386. this.lights = source.lights;
  13387. this.clipping = source.clipping;
  13388. this.skinning = source.skinning;
  13389. this.morphTargets = source.morphTargets;
  13390. this.morphNormals = source.morphNormals;
  13391. this.extensions = source.extensions;
  13392. return this;
  13393. };
  13394. ShaderMaterial.prototype.toJSON = function ( meta ) {
  13395. var data = Material.prototype.toJSON.call( this, meta );
  13396. data.uniforms = this.uniforms;
  13397. data.vertexShader = this.vertexShader;
  13398. data.fragmentShader = this.fragmentShader;
  13399. return data;
  13400. };
  13401. /**
  13402. * @author bhouston / http://clara.io
  13403. */
  13404. function Ray( origin, direction ) {
  13405. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  13406. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  13407. }
  13408. Object.assign( Ray.prototype, {
  13409. set: function ( origin, direction ) {
  13410. this.origin.copy( origin );
  13411. this.direction.copy( direction );
  13412. return this;
  13413. },
  13414. clone: function () {
  13415. return new this.constructor().copy( this );
  13416. },
  13417. copy: function ( ray ) {
  13418. this.origin.copy( ray.origin );
  13419. this.direction.copy( ray.direction );
  13420. return this;
  13421. },
  13422. at: function ( t, optionalTarget ) {
  13423. var result = optionalTarget || new Vector3();
  13424. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  13425. },
  13426. lookAt: function ( v ) {
  13427. this.direction.copy( v ).sub( this.origin ).normalize();
  13428. return this;
  13429. },
  13430. recast: function () {
  13431. var v1 = new Vector3();
  13432. return function recast( t ) {
  13433. this.origin.copy( this.at( t, v1 ) );
  13434. return this;
  13435. };
  13436. }(),
  13437. closestPointToPoint: function ( point, optionalTarget ) {
  13438. var result = optionalTarget || new Vector3();
  13439. result.subVectors( point, this.origin );
  13440. var directionDistance = result.dot( this.direction );
  13441. if ( directionDistance < 0 ) {
  13442. return result.copy( this.origin );
  13443. }
  13444. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  13445. },
  13446. distanceToPoint: function ( point ) {
  13447. return Math.sqrt( this.distanceSqToPoint( point ) );
  13448. },
  13449. distanceSqToPoint: function () {
  13450. var v1 = new Vector3();
  13451. return function distanceSqToPoint( point ) {
  13452. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  13453. // point behind the ray
  13454. if ( directionDistance < 0 ) {
  13455. return this.origin.distanceToSquared( point );
  13456. }
  13457. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  13458. return v1.distanceToSquared( point );
  13459. };
  13460. }(),
  13461. distanceSqToSegment: function () {
  13462. var segCenter = new Vector3();
  13463. var segDir = new Vector3();
  13464. var diff = new Vector3();
  13465. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  13466. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  13467. // It returns the min distance between the ray and the segment
  13468. // defined by v0 and v1
  13469. // It can also set two optional targets :
  13470. // - The closest point on the ray
  13471. // - The closest point on the segment
  13472. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  13473. segDir.copy( v1 ).sub( v0 ).normalize();
  13474. diff.copy( this.origin ).sub( segCenter );
  13475. var segExtent = v0.distanceTo( v1 ) * 0.5;
  13476. var a01 = - this.direction.dot( segDir );
  13477. var b0 = diff.dot( this.direction );
  13478. var b1 = - diff.dot( segDir );
  13479. var c = diff.lengthSq();
  13480. var det = Math.abs( 1 - a01 * a01 );
  13481. var s0, s1, sqrDist, extDet;
  13482. if ( det > 0 ) {
  13483. // The ray and segment are not parallel.
  13484. s0 = a01 * b1 - b0;
  13485. s1 = a01 * b0 - b1;
  13486. extDet = segExtent * det;
  13487. if ( s0 >= 0 ) {
  13488. if ( s1 >= - extDet ) {
  13489. if ( s1 <= extDet ) {
  13490. // region 0
  13491. // Minimum at interior points of ray and segment.
  13492. var invDet = 1 / det;
  13493. s0 *= invDet;
  13494. s1 *= invDet;
  13495. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  13496. } else {
  13497. // region 1
  13498. s1 = segExtent;
  13499. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13500. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13501. }
  13502. } else {
  13503. // region 5
  13504. s1 = - segExtent;
  13505. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13506. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13507. }
  13508. } else {
  13509. if ( s1 <= - extDet ) {
  13510. // region 4
  13511. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  13512. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13513. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13514. } else if ( s1 <= extDet ) {
  13515. // region 3
  13516. s0 = 0;
  13517. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13518. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  13519. } else {
  13520. // region 2
  13521. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  13522. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  13523. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13524. }
  13525. }
  13526. } else {
  13527. // Ray and segment are parallel.
  13528. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  13529. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  13530. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  13531. }
  13532. if ( optionalPointOnRay ) {
  13533. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  13534. }
  13535. if ( optionalPointOnSegment ) {
  13536. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  13537. }
  13538. return sqrDist;
  13539. };
  13540. }(),
  13541. intersectSphere: function () {
  13542. var v1 = new Vector3();
  13543. return function intersectSphere( sphere, optionalTarget ) {
  13544. v1.subVectors( sphere.center, this.origin );
  13545. var tca = v1.dot( this.direction );
  13546. var d2 = v1.dot( v1 ) - tca * tca;
  13547. var radius2 = sphere.radius * sphere.radius;
  13548. if ( d2 > radius2 ) return null;
  13549. var thc = Math.sqrt( radius2 - d2 );
  13550. // t0 = first intersect point - entrance on front of sphere
  13551. var t0 = tca - thc;
  13552. // t1 = second intersect point - exit point on back of sphere
  13553. var t1 = tca + thc;
  13554. // test to see if both t0 and t1 are behind the ray - if so, return null
  13555. if ( t0 < 0 && t1 < 0 ) return null;
  13556. // test to see if t0 is behind the ray:
  13557. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  13558. // in order to always return an intersect point that is in front of the ray.
  13559. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  13560. // else t0 is in front of the ray, so return the first collision point scaled by t0
  13561. return this.at( t0, optionalTarget );
  13562. };
  13563. }(),
  13564. intersectsSphere: function ( sphere ) {
  13565. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  13566. },
  13567. distanceToPlane: function ( plane ) {
  13568. var denominator = plane.normal.dot( this.direction );
  13569. if ( denominator === 0 ) {
  13570. // line is coplanar, return origin
  13571. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  13572. return 0;
  13573. }
  13574. // Null is preferable to undefined since undefined means.... it is undefined
  13575. return null;
  13576. }
  13577. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  13578. // Return if the ray never intersects the plane
  13579. return t >= 0 ? t : null;
  13580. },
  13581. intersectPlane: function ( plane, optionalTarget ) {
  13582. var t = this.distanceToPlane( plane );
  13583. if ( t === null ) {
  13584. return null;
  13585. }
  13586. return this.at( t, optionalTarget );
  13587. },
  13588. intersectsPlane: function ( plane ) {
  13589. // check if the ray lies on the plane first
  13590. var distToPoint = plane.distanceToPoint( this.origin );
  13591. if ( distToPoint === 0 ) {
  13592. return true;
  13593. }
  13594. var denominator = plane.normal.dot( this.direction );
  13595. if ( denominator * distToPoint < 0 ) {
  13596. return true;
  13597. }
  13598. // ray origin is behind the plane (and is pointing behind it)
  13599. return false;
  13600. },
  13601. intersectBox: function ( box, optionalTarget ) {
  13602. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  13603. var invdirx = 1 / this.direction.x,
  13604. invdiry = 1 / this.direction.y,
  13605. invdirz = 1 / this.direction.z;
  13606. var origin = this.origin;
  13607. if ( invdirx >= 0 ) {
  13608. tmin = ( box.min.x - origin.x ) * invdirx;
  13609. tmax = ( box.max.x - origin.x ) * invdirx;
  13610. } else {
  13611. tmin = ( box.max.x - origin.x ) * invdirx;
  13612. tmax = ( box.min.x - origin.x ) * invdirx;
  13613. }
  13614. if ( invdiry >= 0 ) {
  13615. tymin = ( box.min.y - origin.y ) * invdiry;
  13616. tymax = ( box.max.y - origin.y ) * invdiry;
  13617. } else {
  13618. tymin = ( box.max.y - origin.y ) * invdiry;
  13619. tymax = ( box.min.y - origin.y ) * invdiry;
  13620. }
  13621. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  13622. // These lines also handle the case where tmin or tmax is NaN
  13623. // (result of 0 * Infinity). x !== x returns true if x is NaN
  13624. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  13625. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  13626. if ( invdirz >= 0 ) {
  13627. tzmin = ( box.min.z - origin.z ) * invdirz;
  13628. tzmax = ( box.max.z - origin.z ) * invdirz;
  13629. } else {
  13630. tzmin = ( box.max.z - origin.z ) * invdirz;
  13631. tzmax = ( box.min.z - origin.z ) * invdirz;
  13632. }
  13633. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  13634. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  13635. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  13636. //return point closest to the ray (positive side)
  13637. if ( tmax < 0 ) return null;
  13638. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  13639. },
  13640. intersectsBox: ( function () {
  13641. var v = new Vector3();
  13642. return function intersectsBox( box ) {
  13643. return this.intersectBox( box, v ) !== null;
  13644. };
  13645. } )(),
  13646. intersectTriangle: function () {
  13647. // Compute the offset origin, edges, and normal.
  13648. var diff = new Vector3();
  13649. var edge1 = new Vector3();
  13650. var edge2 = new Vector3();
  13651. var normal = new Vector3();
  13652. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  13653. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  13654. edge1.subVectors( b, a );
  13655. edge2.subVectors( c, a );
  13656. normal.crossVectors( edge1, edge2 );
  13657. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  13658. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  13659. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  13660. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  13661. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  13662. var DdN = this.direction.dot( normal );
  13663. var sign;
  13664. if ( DdN > 0 ) {
  13665. if ( backfaceCulling ) return null;
  13666. sign = 1;
  13667. } else if ( DdN < 0 ) {
  13668. sign = - 1;
  13669. DdN = - DdN;
  13670. } else {
  13671. return null;
  13672. }
  13673. diff.subVectors( this.origin, a );
  13674. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  13675. // b1 < 0, no intersection
  13676. if ( DdQxE2 < 0 ) {
  13677. return null;
  13678. }
  13679. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  13680. // b2 < 0, no intersection
  13681. if ( DdE1xQ < 0 ) {
  13682. return null;
  13683. }
  13684. // b1+b2 > 1, no intersection
  13685. if ( DdQxE2 + DdE1xQ > DdN ) {
  13686. return null;
  13687. }
  13688. // Line intersects triangle, check if ray does.
  13689. var QdN = - sign * diff.dot( normal );
  13690. // t < 0, no intersection
  13691. if ( QdN < 0 ) {
  13692. return null;
  13693. }
  13694. // Ray intersects triangle.
  13695. return this.at( QdN / DdN, optionalTarget );
  13696. };
  13697. }(),
  13698. applyMatrix4: function ( matrix4 ) {
  13699. this.origin.applyMatrix4( matrix4 );
  13700. this.direction.transformDirection( matrix4 );
  13701. return this;
  13702. },
  13703. equals: function ( ray ) {
  13704. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  13705. }
  13706. } );
  13707. /**
  13708. * @author bhouston / http://clara.io
  13709. */
  13710. function Line3( start, end ) {
  13711. this.start = ( start !== undefined ) ? start : new Vector3();
  13712. this.end = ( end !== undefined ) ? end : new Vector3();
  13713. }
  13714. Object.assign( Line3.prototype, {
  13715. set: function ( start, end ) {
  13716. this.start.copy( start );
  13717. this.end.copy( end );
  13718. return this;
  13719. },
  13720. clone: function () {
  13721. return new this.constructor().copy( this );
  13722. },
  13723. copy: function ( line ) {
  13724. this.start.copy( line.start );
  13725. this.end.copy( line.end );
  13726. return this;
  13727. },
  13728. getCenter: function ( optionalTarget ) {
  13729. var result = optionalTarget || new Vector3();
  13730. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  13731. },
  13732. delta: function ( optionalTarget ) {
  13733. var result = optionalTarget || new Vector3();
  13734. return result.subVectors( this.end, this.start );
  13735. },
  13736. distanceSq: function () {
  13737. return this.start.distanceToSquared( this.end );
  13738. },
  13739. distance: function () {
  13740. return this.start.distanceTo( this.end );
  13741. },
  13742. at: function ( t, optionalTarget ) {
  13743. var result = optionalTarget || new Vector3();
  13744. return this.delta( result ).multiplyScalar( t ).add( this.start );
  13745. },
  13746. closestPointToPointParameter: function () {
  13747. var startP = new Vector3();
  13748. var startEnd = new Vector3();
  13749. return function closestPointToPointParameter( point, clampToLine ) {
  13750. startP.subVectors( point, this.start );
  13751. startEnd.subVectors( this.end, this.start );
  13752. var startEnd2 = startEnd.dot( startEnd );
  13753. var startEnd_startP = startEnd.dot( startP );
  13754. var t = startEnd_startP / startEnd2;
  13755. if ( clampToLine ) {
  13756. t = _Math.clamp( t, 0, 1 );
  13757. }
  13758. return t;
  13759. };
  13760. }(),
  13761. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  13762. var t = this.closestPointToPointParameter( point, clampToLine );
  13763. var result = optionalTarget || new Vector3();
  13764. return this.delta( result ).multiplyScalar( t ).add( this.start );
  13765. },
  13766. applyMatrix4: function ( matrix ) {
  13767. this.start.applyMatrix4( matrix );
  13768. this.end.applyMatrix4( matrix );
  13769. return this;
  13770. },
  13771. equals: function ( line ) {
  13772. return line.start.equals( this.start ) && line.end.equals( this.end );
  13773. }
  13774. } );
  13775. /**
  13776. * @author bhouston / http://clara.io
  13777. * @author mrdoob / http://mrdoob.com/
  13778. */
  13779. function Triangle( a, b, c ) {
  13780. this.a = ( a !== undefined ) ? a : new Vector3();
  13781. this.b = ( b !== undefined ) ? b : new Vector3();
  13782. this.c = ( c !== undefined ) ? c : new Vector3();
  13783. }
  13784. Object.assign( Triangle, {
  13785. normal: function () {
  13786. var v0 = new Vector3();
  13787. return function normal( a, b, c, optionalTarget ) {
  13788. var result = optionalTarget || new Vector3();
  13789. result.subVectors( c, b );
  13790. v0.subVectors( a, b );
  13791. result.cross( v0 );
  13792. var resultLengthSq = result.lengthSq();
  13793. if ( resultLengthSq > 0 ) {
  13794. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  13795. }
  13796. return result.set( 0, 0, 0 );
  13797. };
  13798. }(),
  13799. // static/instance method to calculate barycentric coordinates
  13800. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  13801. barycoordFromPoint: function () {
  13802. var v0 = new Vector3();
  13803. var v1 = new Vector3();
  13804. var v2 = new Vector3();
  13805. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  13806. v0.subVectors( c, a );
  13807. v1.subVectors( b, a );
  13808. v2.subVectors( point, a );
  13809. var dot00 = v0.dot( v0 );
  13810. var dot01 = v0.dot( v1 );
  13811. var dot02 = v0.dot( v2 );
  13812. var dot11 = v1.dot( v1 );
  13813. var dot12 = v1.dot( v2 );
  13814. var denom = ( dot00 * dot11 - dot01 * dot01 );
  13815. var result = optionalTarget || new Vector3();
  13816. // collinear or singular triangle
  13817. if ( denom === 0 ) {
  13818. // arbitrary location outside of triangle?
  13819. // not sure if this is the best idea, maybe should be returning undefined
  13820. return result.set( - 2, - 1, - 1 );
  13821. }
  13822. var invDenom = 1 / denom;
  13823. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  13824. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  13825. // barycentric coordinates must always sum to 1
  13826. return result.set( 1 - u - v, v, u );
  13827. };
  13828. }(),
  13829. containsPoint: function () {
  13830. var v1 = new Vector3();
  13831. return function containsPoint( point, a, b, c ) {
  13832. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  13833. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  13834. };
  13835. }()
  13836. } );
  13837. Object.assign( Triangle.prototype, {
  13838. set: function ( a, b, c ) {
  13839. this.a.copy( a );
  13840. this.b.copy( b );
  13841. this.c.copy( c );
  13842. return this;
  13843. },
  13844. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  13845. this.a.copy( points[ i0 ] );
  13846. this.b.copy( points[ i1 ] );
  13847. this.c.copy( points[ i2 ] );
  13848. return this;
  13849. },
  13850. clone: function () {
  13851. return new this.constructor().copy( this );
  13852. },
  13853. copy: function ( triangle ) {
  13854. this.a.copy( triangle.a );
  13855. this.b.copy( triangle.b );
  13856. this.c.copy( triangle.c );
  13857. return this;
  13858. },
  13859. area: function () {
  13860. var v0 = new Vector3();
  13861. var v1 = new Vector3();
  13862. return function area() {
  13863. v0.subVectors( this.c, this.b );
  13864. v1.subVectors( this.a, this.b );
  13865. return v0.cross( v1 ).length() * 0.5;
  13866. };
  13867. }(),
  13868. midpoint: function ( optionalTarget ) {
  13869. var result = optionalTarget || new Vector3();
  13870. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  13871. },
  13872. normal: function ( optionalTarget ) {
  13873. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  13874. },
  13875. plane: function ( optionalTarget ) {
  13876. var result = optionalTarget || new Plane();
  13877. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  13878. },
  13879. barycoordFromPoint: function ( point, optionalTarget ) {
  13880. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  13881. },
  13882. containsPoint: function ( point ) {
  13883. return Triangle.containsPoint( point, this.a, this.b, this.c );
  13884. },
  13885. closestPointToPoint: function () {
  13886. var plane = new Plane();
  13887. var edgeList = [ new Line3(), new Line3(), new Line3() ];
  13888. var projectedPoint = new Vector3();
  13889. var closestPoint = new Vector3();
  13890. return function closestPointToPoint( point, optionalTarget ) {
  13891. var result = optionalTarget || new Vector3();
  13892. var minDistance = Infinity;
  13893. // project the point onto the plane of the triangle
  13894. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  13895. plane.projectPoint( point, projectedPoint );
  13896. // check if the projection lies within the triangle
  13897. if ( this.containsPoint( projectedPoint ) === true ) {
  13898. // if so, this is the closest point
  13899. result.copy( projectedPoint );
  13900. } else {
  13901. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  13902. edgeList[ 0 ].set( this.a, this.b );
  13903. edgeList[ 1 ].set( this.b, this.c );
  13904. edgeList[ 2 ].set( this.c, this.a );
  13905. for ( var i = 0; i < edgeList.length; i ++ ) {
  13906. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  13907. var distance = projectedPoint.distanceToSquared( closestPoint );
  13908. if ( distance < minDistance ) {
  13909. minDistance = distance;
  13910. result.copy( closestPoint );
  13911. }
  13912. }
  13913. }
  13914. return result;
  13915. };
  13916. }(),
  13917. equals: function ( triangle ) {
  13918. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  13919. }
  13920. } );
  13921. /**
  13922. * @author mrdoob / http://mrdoob.com/
  13923. * @author alteredq / http://alteredqualia.com/
  13924. * @author mikael emtinger / http://gomo.se/
  13925. * @author jonobr1 / http://jonobr1.com/
  13926. */
  13927. function Mesh( geometry, material ) {
  13928. Object3D.call( this );
  13929. this.type = 'Mesh';
  13930. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13931. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13932. this.drawMode = TrianglesDrawMode;
  13933. this.updateMorphTargets();
  13934. }
  13935. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13936. constructor: Mesh,
  13937. isMesh: true,
  13938. setDrawMode: function ( value ) {
  13939. this.drawMode = value;
  13940. },
  13941. copy: function ( source ) {
  13942. Object3D.prototype.copy.call( this, source );
  13943. this.drawMode = source.drawMode;
  13944. if ( source.morphTargetInfluences !== undefined ) {
  13945. this.morphTargetInfluences = source.morphTargetInfluences.slice();
  13946. }
  13947. if ( source.morphTargetDictionary !== undefined ) {
  13948. this.morphTargetDictionary = Object.assign( {}, source.morphTargetDictionary );
  13949. }
  13950. return this;
  13951. },
  13952. updateMorphTargets: function () {
  13953. var geometry = this.geometry;
  13954. var m, ml, name;
  13955. if ( geometry.isBufferGeometry ) {
  13956. var morphAttributes = geometry.morphAttributes;
  13957. var keys = Object.keys( morphAttributes );
  13958. if ( keys.length > 0 ) {
  13959. var morphAttribute = morphAttributes[ keys[ 0 ] ];
  13960. if ( morphAttribute !== undefined ) {
  13961. this.morphTargetInfluences = [];
  13962. this.morphTargetDictionary = {};
  13963. for ( m = 0, ml = morphAttribute.length; m < ml; m ++ ) {
  13964. name = morphAttribute[ m ].name || String( m );
  13965. this.morphTargetInfluences.push( 0 );
  13966. this.morphTargetDictionary[ name ] = m;
  13967. }
  13968. }
  13969. }
  13970. } else {
  13971. var morphTargets = geometry.morphTargets;
  13972. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13973. this.morphTargetInfluences = [];
  13974. this.morphTargetDictionary = {};
  13975. for ( m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  13976. name = morphTargets[ m ].name || String( m );
  13977. this.morphTargetInfluences.push( 0 );
  13978. this.morphTargetDictionary[ name ] = m;
  13979. }
  13980. }
  13981. }
  13982. },
  13983. raycast: ( function () {
  13984. var inverseMatrix = new Matrix4();
  13985. var ray = new Ray();
  13986. var sphere = new Sphere();
  13987. var vA = new Vector3();
  13988. var vB = new Vector3();
  13989. var vC = new Vector3();
  13990. var tempA = new Vector3();
  13991. var tempB = new Vector3();
  13992. var tempC = new Vector3();
  13993. var uvA = new Vector2();
  13994. var uvB = new Vector2();
  13995. var uvC = new Vector2();
  13996. var barycoord = new Vector3();
  13997. var intersectionPoint = new Vector3();
  13998. var intersectionPointWorld = new Vector3();
  13999. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  14000. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  14001. uv1.multiplyScalar( barycoord.x );
  14002. uv2.multiplyScalar( barycoord.y );
  14003. uv3.multiplyScalar( barycoord.z );
  14004. uv1.add( uv2 ).add( uv3 );
  14005. return uv1.clone();
  14006. }
  14007. function checkIntersection( object, material, raycaster, ray, pA, pB, pC, point ) {
  14008. var intersect;
  14009. if ( material.side === BackSide ) {
  14010. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  14011. } else {
  14012. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  14013. }
  14014. if ( intersect === null ) return null;
  14015. intersectionPointWorld.copy( point );
  14016. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  14017. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  14018. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  14019. return {
  14020. distance: distance,
  14021. point: intersectionPointWorld.clone(),
  14022. object: object
  14023. };
  14024. }
  14025. function checkBufferGeometryIntersection( object, raycaster, ray, position, uv, a, b, c ) {
  14026. vA.fromBufferAttribute( position, a );
  14027. vB.fromBufferAttribute( position, b );
  14028. vC.fromBufferAttribute( position, c );
  14029. var intersection = checkIntersection( object, object.material, raycaster, ray, vA, vB, vC, intersectionPoint );
  14030. if ( intersection ) {
  14031. if ( uv ) {
  14032. uvA.fromBufferAttribute( uv, a );
  14033. uvB.fromBufferAttribute( uv, b );
  14034. uvC.fromBufferAttribute( uv, c );
  14035. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  14036. }
  14037. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  14038. intersection.faceIndex = a;
  14039. }
  14040. return intersection;
  14041. }
  14042. return function raycast( raycaster, intersects ) {
  14043. var geometry = this.geometry;
  14044. var material = this.material;
  14045. var matrixWorld = this.matrixWorld;
  14046. if ( material === undefined ) return;
  14047. // Checking boundingSphere distance to ray
  14048. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  14049. sphere.copy( geometry.boundingSphere );
  14050. sphere.applyMatrix4( matrixWorld );
  14051. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  14052. //
  14053. inverseMatrix.getInverse( matrixWorld );
  14054. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  14055. // Check boundingBox before continuing
  14056. if ( geometry.boundingBox !== null ) {
  14057. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  14058. }
  14059. var intersection;
  14060. if ( geometry.isBufferGeometry ) {
  14061. var a, b, c;
  14062. var index = geometry.index;
  14063. var position = geometry.attributes.position;
  14064. var uv = geometry.attributes.uv;
  14065. var i, l;
  14066. if ( index !== null ) {
  14067. // indexed buffer geometry
  14068. for ( i = 0, l = index.count; i < l; i += 3 ) {
  14069. a = index.getX( i );
  14070. b = index.getX( i + 1 );
  14071. c = index.getX( i + 2 );
  14072. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  14073. if ( intersection ) {
  14074. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  14075. intersects.push( intersection );
  14076. }
  14077. }
  14078. } else if ( position !== undefined ) {
  14079. // non-indexed buffer geometry
  14080. for ( i = 0, l = position.count; i < l; i += 3 ) {
  14081. a = i;
  14082. b = i + 1;
  14083. c = i + 2;
  14084. intersection = checkBufferGeometryIntersection( this, raycaster, ray, position, uv, a, b, c );
  14085. if ( intersection ) {
  14086. intersection.index = a; // triangle number in positions buffer semantics
  14087. intersects.push( intersection );
  14088. }
  14089. }
  14090. }
  14091. } else if ( geometry.isGeometry ) {
  14092. var fvA, fvB, fvC;
  14093. var isMultiMaterial = Array.isArray( material );
  14094. var vertices = geometry.vertices;
  14095. var faces = geometry.faces;
  14096. var uvs;
  14097. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  14098. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  14099. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  14100. var face = faces[ f ];
  14101. var faceMaterial = isMultiMaterial ? material[ face.materialIndex ] : material;
  14102. if ( faceMaterial === undefined ) continue;
  14103. fvA = vertices[ face.a ];
  14104. fvB = vertices[ face.b ];
  14105. fvC = vertices[ face.c ];
  14106. if ( faceMaterial.morphTargets === true ) {
  14107. var morphTargets = geometry.morphTargets;
  14108. var morphInfluences = this.morphTargetInfluences;
  14109. vA.set( 0, 0, 0 );
  14110. vB.set( 0, 0, 0 );
  14111. vC.set( 0, 0, 0 );
  14112. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  14113. var influence = morphInfluences[ t ];
  14114. if ( influence === 0 ) continue;
  14115. var targets = morphTargets[ t ].vertices;
  14116. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  14117. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  14118. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  14119. }
  14120. vA.add( fvA );
  14121. vB.add( fvB );
  14122. vC.add( fvC );
  14123. fvA = vA;
  14124. fvB = vB;
  14125. fvC = vC;
  14126. }
  14127. intersection = checkIntersection( this, faceMaterial, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  14128. if ( intersection ) {
  14129. if ( uvs && uvs[ f ] ) {
  14130. var uvs_f = uvs[ f ];
  14131. uvA.copy( uvs_f[ 0 ] );
  14132. uvB.copy( uvs_f[ 1 ] );
  14133. uvC.copy( uvs_f[ 2 ] );
  14134. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  14135. }
  14136. intersection.face = face;
  14137. intersection.faceIndex = f;
  14138. intersects.push( intersection );
  14139. }
  14140. }
  14141. }
  14142. };
  14143. }() ),
  14144. clone: function () {
  14145. return new this.constructor( this.geometry, this.material ).copy( this );
  14146. }
  14147. } );
  14148. /**
  14149. * @author mrdoob / http://mrdoob.com/
  14150. */
  14151. function WebGLBackground( renderer, state, geometries, premultipliedAlpha ) {
  14152. var clearColor = new Color( 0x000000 );
  14153. var clearAlpha = 0;
  14154. var planeCamera, planeMesh;
  14155. var boxMesh;
  14156. function render( renderList, scene, camera, forceClear ) {
  14157. var background = scene.background;
  14158. if ( background === null ) {
  14159. setClear( clearColor, clearAlpha );
  14160. } else if ( background && background.isColor ) {
  14161. setClear( background, 1 );
  14162. forceClear = true;
  14163. }
  14164. if ( renderer.autoClear || forceClear ) {
  14165. renderer.clear( renderer.autoClearColor, renderer.autoClearDepth, renderer.autoClearStencil );
  14166. }
  14167. if ( background && background.isCubeTexture ) {
  14168. if ( boxMesh === undefined ) {
  14169. boxMesh = new Mesh(
  14170. new BoxBufferGeometry( 1, 1, 1 ),
  14171. new ShaderMaterial( {
  14172. uniforms: ShaderLib.cube.uniforms,
  14173. vertexShader: ShaderLib.cube.vertexShader,
  14174. fragmentShader: ShaderLib.cube.fragmentShader,
  14175. side: BackSide,
  14176. depthTest: true,
  14177. depthWrite: false,
  14178. fog: false
  14179. } )
  14180. );
  14181. boxMesh.geometry.removeAttribute( 'normal' );
  14182. boxMesh.geometry.removeAttribute( 'uv' );
  14183. boxMesh.onBeforeRender = function ( renderer, scene, camera ) {
  14184. this.matrixWorld.copyPosition( camera.matrixWorld );
  14185. };
  14186. geometries.update( boxMesh.geometry );
  14187. }
  14188. boxMesh.material.uniforms.tCube.value = background;
  14189. renderList.push( boxMesh, boxMesh.geometry, boxMesh.material, 0, null );
  14190. } else if ( background && background.isTexture ) {
  14191. if ( planeCamera === undefined ) {
  14192. planeCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  14193. planeMesh = new Mesh(
  14194. new PlaneBufferGeometry( 2, 2 ),
  14195. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  14196. );
  14197. geometries.update( planeMesh.geometry );
  14198. }
  14199. planeMesh.material.map = background;
  14200. // TODO Push this to renderList
  14201. renderer.renderBufferDirect( planeCamera, null, planeMesh.geometry, planeMesh.material, planeMesh, null );
  14202. }
  14203. }
  14204. function setClear( color, alpha ) {
  14205. state.buffers.color.setClear( color.r, color.g, color.b, alpha, premultipliedAlpha );
  14206. }
  14207. return {
  14208. getClearColor: function () {
  14209. return clearColor;
  14210. },
  14211. setClearColor: function ( color, alpha ) {
  14212. clearColor.set( color );
  14213. clearAlpha = alpha !== undefined ? alpha : 1;
  14214. setClear( clearColor, clearAlpha );
  14215. },
  14216. getClearAlpha: function () {
  14217. return clearAlpha;
  14218. },
  14219. setClearAlpha: function ( alpha ) {
  14220. clearAlpha = alpha;
  14221. setClear( clearColor, clearAlpha );
  14222. },
  14223. render: render
  14224. };
  14225. }
  14226. /**
  14227. * @author mrdoob / http://mrdoob.com/
  14228. */
  14229. function painterSortStable( a, b ) {
  14230. if ( a.renderOrder !== b.renderOrder ) {
  14231. return a.renderOrder - b.renderOrder;
  14232. } else if ( a.program && b.program && a.program !== b.program ) {
  14233. return a.program.id - b.program.id;
  14234. } else if ( a.material.id !== b.material.id ) {
  14235. return a.material.id - b.material.id;
  14236. } else if ( a.z !== b.z ) {
  14237. return a.z - b.z;
  14238. } else {
  14239. return a.id - b.id;
  14240. }
  14241. }
  14242. function reversePainterSortStable( a, b ) {
  14243. if ( a.renderOrder !== b.renderOrder ) {
  14244. return a.renderOrder - b.renderOrder;
  14245. } if ( a.z !== b.z ) {
  14246. return b.z - a.z;
  14247. } else {
  14248. return a.id - b.id;
  14249. }
  14250. }
  14251. function WebGLRenderList() {
  14252. var renderItems = [];
  14253. var renderItemsIndex = 0;
  14254. var opaque = [];
  14255. var transparent = [];
  14256. function init() {
  14257. renderItemsIndex = 0;
  14258. opaque.length = 0;
  14259. transparent.length = 0;
  14260. }
  14261. function push( object, geometry, material, z, group ) {
  14262. var renderItem = renderItems[ renderItemsIndex ];
  14263. if ( renderItem === undefined ) {
  14264. renderItem = {
  14265. id: object.id,
  14266. object: object,
  14267. geometry: geometry,
  14268. material: material,
  14269. program: material.program,
  14270. renderOrder: object.renderOrder,
  14271. z: z,
  14272. group: group
  14273. };
  14274. renderItems[ renderItemsIndex ] = renderItem;
  14275. } else {
  14276. renderItem.id = object.id;
  14277. renderItem.object = object;
  14278. renderItem.geometry = geometry;
  14279. renderItem.material = material;
  14280. renderItem.program = material.program;
  14281. renderItem.renderOrder = object.renderOrder;
  14282. renderItem.z = z;
  14283. renderItem.group = group;
  14284. }
  14285. ( material.transparent === true ? transparent : opaque ).push( renderItem );
  14286. renderItemsIndex ++;
  14287. }
  14288. function sort() {
  14289. if ( opaque.length > 1 ) opaque.sort( painterSortStable );
  14290. if ( transparent.length > 1 ) transparent.sort( reversePainterSortStable );
  14291. }
  14292. return {
  14293. opaque: opaque,
  14294. transparent: transparent,
  14295. init: init,
  14296. push: push,
  14297. sort: sort
  14298. };
  14299. }
  14300. function WebGLRenderLists() {
  14301. var lists = {};
  14302. function get( scene, camera ) {
  14303. var hash = scene.id + ',' + camera.id;
  14304. var list = lists[ hash ];
  14305. if ( list === undefined ) {
  14306. // console.log( 'THREE.WebGLRenderLists:', hash );
  14307. list = new WebGLRenderList();
  14308. lists[ hash ] = list;
  14309. }
  14310. return list;
  14311. }
  14312. function dispose() {
  14313. lists = {};
  14314. }
  14315. return {
  14316. get: get,
  14317. dispose: dispose
  14318. };
  14319. }
  14320. /**
  14321. * @author mrdoob / http://mrdoob.com/
  14322. */
  14323. function absNumericalSort( a, b ) {
  14324. return Math.abs( b[ 1 ] ) - Math.abs( a[ 1 ] );
  14325. }
  14326. function WebGLMorphtargets( gl ) {
  14327. var influencesList = {};
  14328. var morphInfluences = new Float32Array( 8 );
  14329. function update( object, geometry, material, program ) {
  14330. var objectInfluences = object.morphTargetInfluences;
  14331. var length = objectInfluences.length;
  14332. var influences = influencesList[ geometry.id ];
  14333. if ( influences === undefined ) {
  14334. // initialise list
  14335. influences = [];
  14336. for ( var i = 0; i < length; i ++ ) {
  14337. influences[ i ] = [ i, 0 ];
  14338. }
  14339. influencesList[ geometry.id ] = influences;
  14340. }
  14341. var morphTargets = material.morphTargets && geometry.morphAttributes.position;
  14342. var morphNormals = material.morphNormals && geometry.morphAttributes.normal;
  14343. // Remove current morphAttributes
  14344. for ( var i = 0; i < length; i ++ ) {
  14345. var influence = influences[ i ];
  14346. if ( influence[ 1 ] !== 0 ) {
  14347. if ( morphTargets ) geometry.removeAttribute( 'morphTarget' + i );
  14348. if ( morphNormals ) geometry.removeAttribute( 'morphNormal' + i );
  14349. }
  14350. }
  14351. // Collect influences
  14352. for ( var i = 0; i < length; i ++ ) {
  14353. var influence = influences[ i ];
  14354. influence[ 0 ] = i;
  14355. influence[ 1 ] = objectInfluences[ i ];
  14356. }
  14357. influences.sort( absNumericalSort );
  14358. // Add morphAttributes
  14359. for ( var i = 0; i < 8; i ++ ) {
  14360. var influence = influences[ i ];
  14361. if ( influence ) {
  14362. var index = influence[ 0 ];
  14363. var value = influence[ 1 ];
  14364. if ( value ) {
  14365. if ( morphTargets ) geometry.addAttribute( 'morphTarget' + i, morphTargets[ index ] );
  14366. if ( morphNormals ) geometry.addAttribute( 'morphNormal' + i, morphNormals[ index ] );
  14367. morphInfluences[ i ] = value;
  14368. continue;
  14369. }
  14370. }
  14371. morphInfluences[ i ] = 0;
  14372. }
  14373. program.getUniforms().setValue( gl, 'morphTargetInfluences', morphInfluences );
  14374. }
  14375. return {
  14376. update: update
  14377. };
  14378. }
  14379. /**
  14380. * @author mrdoob / http://mrdoob.com/
  14381. */
  14382. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  14383. var mode;
  14384. function setMode( value ) {
  14385. mode = value;
  14386. }
  14387. var type, bytesPerElement;
  14388. function setIndex( value ) {
  14389. type = value.type;
  14390. bytesPerElement = value.bytesPerElement;
  14391. }
  14392. function render( start, count ) {
  14393. gl.drawElements( mode, count, type, start * bytesPerElement );
  14394. infoRender.calls ++;
  14395. infoRender.vertices += count;
  14396. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14397. else if ( mode === gl.POINTS ) infoRender.points += count;
  14398. }
  14399. function renderInstances( geometry, start, count ) {
  14400. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14401. if ( extension === null ) {
  14402. console.error( 'THREE.WebGLIndexedBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14403. return;
  14404. }
  14405. extension.drawElementsInstancedANGLE( mode, count, type, start * bytesPerElement, geometry.maxInstancedCount );
  14406. infoRender.calls ++;
  14407. infoRender.vertices += count * geometry.maxInstancedCount;
  14408. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14409. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  14410. }
  14411. //
  14412. this.setMode = setMode;
  14413. this.setIndex = setIndex;
  14414. this.render = render;
  14415. this.renderInstances = renderInstances;
  14416. }
  14417. /**
  14418. * @author mrdoob / http://mrdoob.com/
  14419. */
  14420. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  14421. var mode;
  14422. function setMode( value ) {
  14423. mode = value;
  14424. }
  14425. function render( start, count ) {
  14426. gl.drawArrays( mode, start, count );
  14427. infoRender.calls ++;
  14428. infoRender.vertices += count;
  14429. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  14430. else if ( mode === gl.POINTS ) infoRender.points += count;
  14431. }
  14432. function renderInstances( geometry, start, count ) {
  14433. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  14434. if ( extension === null ) {
  14435. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  14436. return;
  14437. }
  14438. var position = geometry.attributes.position;
  14439. if ( position.isInterleavedBufferAttribute ) {
  14440. count = position.data.count;
  14441. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  14442. } else {
  14443. extension.drawArraysInstancedANGLE( mode, start, count, geometry.maxInstancedCount );
  14444. }
  14445. infoRender.calls ++;
  14446. infoRender.vertices += count * geometry.maxInstancedCount;
  14447. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  14448. else if ( mode === gl.POINTS ) infoRender.points += geometry.maxInstancedCount * count;
  14449. }
  14450. //
  14451. this.setMode = setMode;
  14452. this.render = render;
  14453. this.renderInstances = renderInstances;
  14454. }
  14455. /**
  14456. * @author mrdoob / http://mrdoob.com/
  14457. */
  14458. function WebGLGeometries( gl, attributes, infoMemory ) {
  14459. var geometries = {};
  14460. var wireframeAttributes = {};
  14461. function onGeometryDispose( event ) {
  14462. var geometry = event.target;
  14463. var buffergeometry = geometries[ geometry.id ];
  14464. if ( buffergeometry.index !== null ) {
  14465. attributes.remove( buffergeometry.index );
  14466. }
  14467. for ( var name in buffergeometry.attributes ) {
  14468. attributes.remove( buffergeometry.attributes[ name ] );
  14469. }
  14470. geometry.removeEventListener( 'dispose', onGeometryDispose );
  14471. delete geometries[ geometry.id ];
  14472. // TODO Remove duplicate code
  14473. var attribute = wireframeAttributes[ geometry.id ];
  14474. if ( attribute ) {
  14475. attributes.remove( attribute );
  14476. delete wireframeAttributes[ geometry.id ];
  14477. }
  14478. attribute = wireframeAttributes[ buffergeometry.id ];
  14479. if ( attribute ) {
  14480. attributes.remove( attribute );
  14481. delete wireframeAttributes[ buffergeometry.id ];
  14482. }
  14483. //
  14484. infoMemory.geometries --;
  14485. }
  14486. function get( object, geometry ) {
  14487. var buffergeometry = geometries[ geometry.id ];
  14488. if ( buffergeometry ) return buffergeometry;
  14489. geometry.addEventListener( 'dispose', onGeometryDispose );
  14490. if ( geometry.isBufferGeometry ) {
  14491. buffergeometry = geometry;
  14492. } else if ( geometry.isGeometry ) {
  14493. if ( geometry._bufferGeometry === undefined ) {
  14494. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  14495. }
  14496. buffergeometry = geometry._bufferGeometry;
  14497. }
  14498. geometries[ geometry.id ] = buffergeometry;
  14499. infoMemory.geometries ++;
  14500. return buffergeometry;
  14501. }
  14502. function update( geometry ) {
  14503. var index = geometry.index;
  14504. var geometryAttributes = geometry.attributes;
  14505. if ( index !== null ) {
  14506. attributes.update( index, gl.ELEMENT_ARRAY_BUFFER );
  14507. }
  14508. for ( var name in geometryAttributes ) {
  14509. attributes.update( geometryAttributes[ name ], gl.ARRAY_BUFFER );
  14510. }
  14511. // morph targets
  14512. var morphAttributes = geometry.morphAttributes;
  14513. for ( var name in morphAttributes ) {
  14514. var array = morphAttributes[ name ];
  14515. for ( var i = 0, l = array.length; i < l; i ++ ) {
  14516. attributes.update( array[ i ], gl.ARRAY_BUFFER );
  14517. }
  14518. }
  14519. }
  14520. function getWireframeAttribute( geometry ) {
  14521. var attribute = wireframeAttributes[ geometry.id ];
  14522. if ( attribute ) return attribute;
  14523. var indices = [];
  14524. var geometryIndex = geometry.index;
  14525. var geometryAttributes = geometry.attributes;
  14526. // console.time( 'wireframe' );
  14527. if ( geometryIndex !== null ) {
  14528. var array = geometryIndex.array;
  14529. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  14530. var a = array[ i + 0 ];
  14531. var b = array[ i + 1 ];
  14532. var c = array[ i + 2 ];
  14533. indices.push( a, b, b, c, c, a );
  14534. }
  14535. } else {
  14536. var array = geometryAttributes.position.array;
  14537. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  14538. var a = i + 0;
  14539. var b = i + 1;
  14540. var c = i + 2;
  14541. indices.push( a, b, b, c, c, a );
  14542. }
  14543. }
  14544. // console.timeEnd( 'wireframe' );
  14545. attribute = new ( arrayMax( indices ) > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 );
  14546. attributes.update( attribute, gl.ELEMENT_ARRAY_BUFFER );
  14547. wireframeAttributes[ geometry.id ] = attribute;
  14548. return attribute;
  14549. }
  14550. return {
  14551. get: get,
  14552. update: update,
  14553. getWireframeAttribute: getWireframeAttribute
  14554. };
  14555. }
  14556. /**
  14557. * @author mrdoob / http://mrdoob.com/
  14558. */
  14559. function UniformsCache() {
  14560. var lights = {};
  14561. return {
  14562. get: function ( light ) {
  14563. if ( lights[ light.id ] !== undefined ) {
  14564. return lights[ light.id ];
  14565. }
  14566. var uniforms;
  14567. switch ( light.type ) {
  14568. case 'DirectionalLight':
  14569. uniforms = {
  14570. direction: new Vector3(),
  14571. color: new Color(),
  14572. shadow: false,
  14573. shadowBias: 0,
  14574. shadowRadius: 1,
  14575. shadowMapSize: new Vector2()
  14576. };
  14577. break;
  14578. case 'SpotLight':
  14579. uniforms = {
  14580. position: new Vector3(),
  14581. direction: new Vector3(),
  14582. color: new Color(),
  14583. distance: 0,
  14584. coneCos: 0,
  14585. penumbraCos: 0,
  14586. decay: 0,
  14587. shadow: false,
  14588. shadowBias: 0,
  14589. shadowRadius: 1,
  14590. shadowMapSize: new Vector2()
  14591. };
  14592. break;
  14593. case 'PointLight':
  14594. uniforms = {
  14595. position: new Vector3(),
  14596. color: new Color(),
  14597. distance: 0,
  14598. decay: 0,
  14599. shadow: false,
  14600. shadowBias: 0,
  14601. shadowRadius: 1,
  14602. shadowMapSize: new Vector2(),
  14603. shadowCameraNear: 1,
  14604. shadowCameraFar: 1000
  14605. };
  14606. break;
  14607. case 'HemisphereLight':
  14608. uniforms = {
  14609. direction: new Vector3(),
  14610. skyColor: new Color(),
  14611. groundColor: new Color()
  14612. };
  14613. break;
  14614. case 'RectAreaLight':
  14615. uniforms = {
  14616. color: new Color(),
  14617. position: new Vector3(),
  14618. halfWidth: new Vector3(),
  14619. halfHeight: new Vector3()
  14620. // TODO (abelnation): set RectAreaLight shadow uniforms
  14621. };
  14622. break;
  14623. }
  14624. lights[ light.id ] = uniforms;
  14625. return uniforms;
  14626. }
  14627. };
  14628. }
  14629. function WebGLLights() {
  14630. var cache = new UniformsCache();
  14631. var state = {
  14632. hash: '',
  14633. ambient: [ 0, 0, 0 ],
  14634. directional: [],
  14635. directionalShadowMap: [],
  14636. directionalShadowMatrix: [],
  14637. spot: [],
  14638. spotShadowMap: [],
  14639. spotShadowMatrix: [],
  14640. rectArea: [],
  14641. point: [],
  14642. pointShadowMap: [],
  14643. pointShadowMatrix: [],
  14644. hemi: []
  14645. };
  14646. var vector3 = new Vector3();
  14647. var matrix4 = new Matrix4();
  14648. var matrix42 = new Matrix4();
  14649. function setup( lights, shadows, camera ) {
  14650. var r = 0, g = 0, b = 0;
  14651. var directionalLength = 0;
  14652. var pointLength = 0;
  14653. var spotLength = 0;
  14654. var rectAreaLength = 0;
  14655. var hemiLength = 0;
  14656. var viewMatrix = camera.matrixWorldInverse;
  14657. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  14658. var light = lights[ i ];
  14659. var color = light.color;
  14660. var intensity = light.intensity;
  14661. var distance = light.distance;
  14662. var shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  14663. if ( light.isAmbientLight ) {
  14664. r += color.r * intensity;
  14665. g += color.g * intensity;
  14666. b += color.b * intensity;
  14667. } else if ( light.isDirectionalLight ) {
  14668. var uniforms = cache.get( light );
  14669. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14670. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14671. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14672. uniforms.direction.sub( vector3 );
  14673. uniforms.direction.transformDirection( viewMatrix );
  14674. uniforms.shadow = light.castShadow;
  14675. if ( light.castShadow ) {
  14676. var shadow = light.shadow;
  14677. uniforms.shadowBias = shadow.bias;
  14678. uniforms.shadowRadius = shadow.radius;
  14679. uniforms.shadowMapSize = shadow.mapSize;
  14680. }
  14681. state.directionalShadowMap[ directionalLength ] = shadowMap;
  14682. state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  14683. state.directional[ directionalLength ] = uniforms;
  14684. directionalLength ++;
  14685. } else if ( light.isSpotLight ) {
  14686. var uniforms = cache.get( light );
  14687. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14688. uniforms.position.applyMatrix4( viewMatrix );
  14689. uniforms.color.copy( color ).multiplyScalar( intensity );
  14690. uniforms.distance = distance;
  14691. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14692. vector3.setFromMatrixPosition( light.target.matrixWorld );
  14693. uniforms.direction.sub( vector3 );
  14694. uniforms.direction.transformDirection( viewMatrix );
  14695. uniforms.coneCos = Math.cos( light.angle );
  14696. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  14697. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14698. uniforms.shadow = light.castShadow;
  14699. if ( light.castShadow ) {
  14700. var shadow = light.shadow;
  14701. uniforms.shadowBias = shadow.bias;
  14702. uniforms.shadowRadius = shadow.radius;
  14703. uniforms.shadowMapSize = shadow.mapSize;
  14704. }
  14705. state.spotShadowMap[ spotLength ] = shadowMap;
  14706. state.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  14707. state.spot[ spotLength ] = uniforms;
  14708. spotLength ++;
  14709. } else if ( light.isRectAreaLight ) {
  14710. var uniforms = cache.get( light );
  14711. // (a) intensity controls irradiance of entire light
  14712. uniforms.color
  14713. .copy( color )
  14714. .multiplyScalar( intensity / ( light.width * light.height ) );
  14715. // (b) intensity controls the radiance per light area
  14716. // uniforms.color.copy( color ).multiplyScalar( intensity );
  14717. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14718. uniforms.position.applyMatrix4( viewMatrix );
  14719. // extract local rotation of light to derive width/height half vectors
  14720. matrix42.identity();
  14721. matrix4.copy( light.matrixWorld );
  14722. matrix4.premultiply( viewMatrix );
  14723. matrix42.extractRotation( matrix4 );
  14724. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  14725. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  14726. uniforms.halfWidth.applyMatrix4( matrix42 );
  14727. uniforms.halfHeight.applyMatrix4( matrix42 );
  14728. // TODO (abelnation): RectAreaLight distance?
  14729. // uniforms.distance = distance;
  14730. state.rectArea[ rectAreaLength ] = uniforms;
  14731. rectAreaLength ++;
  14732. } else if ( light.isPointLight ) {
  14733. var uniforms = cache.get( light );
  14734. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  14735. uniforms.position.applyMatrix4( viewMatrix );
  14736. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  14737. uniforms.distance = light.distance;
  14738. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  14739. uniforms.shadow = light.castShadow;
  14740. if ( light.castShadow ) {
  14741. var shadow = light.shadow;
  14742. uniforms.shadowBias = shadow.bias;
  14743. uniforms.shadowRadius = shadow.radius;
  14744. uniforms.shadowMapSize = shadow.mapSize;
  14745. uniforms.shadowCameraNear = shadow.camera.near;
  14746. uniforms.shadowCameraFar = shadow.camera.far;
  14747. }
  14748. state.pointShadowMap[ pointLength ] = shadowMap;
  14749. state.pointShadowMatrix[ pointLength ] = light.shadow.matrix;
  14750. state.point[ pointLength ] = uniforms;
  14751. pointLength ++;
  14752. } else if ( light.isHemisphereLight ) {
  14753. var uniforms = cache.get( light );
  14754. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  14755. uniforms.direction.transformDirection( viewMatrix );
  14756. uniforms.direction.normalize();
  14757. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  14758. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  14759. state.hemi[ hemiLength ] = uniforms;
  14760. hemiLength ++;
  14761. }
  14762. }
  14763. state.ambient[ 0 ] = r;
  14764. state.ambient[ 1 ] = g;
  14765. state.ambient[ 2 ] = b;
  14766. state.directional.length = directionalLength;
  14767. state.spot.length = spotLength;
  14768. state.rectArea.length = rectAreaLength;
  14769. state.point.length = pointLength;
  14770. state.hemi.length = hemiLength;
  14771. // TODO (sam-g-steel) why aren't we using join
  14772. state.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + shadows.length;
  14773. }
  14774. return {
  14775. setup: setup,
  14776. state: state
  14777. };
  14778. }
  14779. /**
  14780. * @author mrdoob / http://mrdoob.com/
  14781. */
  14782. function WebGLObjects( geometries, infoRender ) {
  14783. var updateList = {};
  14784. function update( object ) {
  14785. var frame = infoRender.frame;
  14786. var geometry = object.geometry;
  14787. var buffergeometry = geometries.get( object, geometry );
  14788. // Update once per frame
  14789. if ( updateList[ buffergeometry.id ] !== frame ) {
  14790. if ( geometry.isGeometry ) {
  14791. buffergeometry.updateFromObject( object );
  14792. }
  14793. geometries.update( buffergeometry );
  14794. updateList[ buffergeometry.id ] = frame;
  14795. }
  14796. return buffergeometry;
  14797. }
  14798. function clear() {
  14799. updateList = {};
  14800. }
  14801. return {
  14802. update: update,
  14803. clear: clear
  14804. };
  14805. }
  14806. /**
  14807. * @author mrdoob / http://mrdoob.com/
  14808. */
  14809. function addLineNumbers( string ) {
  14810. var lines = string.split( '\n' );
  14811. for ( var i = 0; i < lines.length; i ++ ) {
  14812. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  14813. }
  14814. return lines.join( '\n' );
  14815. }
  14816. function WebGLShader( gl, type, string ) {
  14817. var shader = gl.createShader( type );
  14818. gl.shaderSource( shader, string );
  14819. gl.compileShader( shader );
  14820. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  14821. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  14822. }
  14823. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  14824. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  14825. }
  14826. // --enable-privileged-webgl-extension
  14827. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  14828. return shader;
  14829. }
  14830. /**
  14831. * @author mrdoob / http://mrdoob.com/
  14832. */
  14833. var programIdCount = 0;
  14834. function getEncodingComponents( encoding ) {
  14835. switch ( encoding ) {
  14836. case LinearEncoding:
  14837. return [ 'Linear', '( value )' ];
  14838. case sRGBEncoding:
  14839. return [ 'sRGB', '( value )' ];
  14840. case RGBEEncoding:
  14841. return [ 'RGBE', '( value )' ];
  14842. case RGBM7Encoding:
  14843. return [ 'RGBM', '( value, 7.0 )' ];
  14844. case RGBM16Encoding:
  14845. return [ 'RGBM', '( value, 16.0 )' ];
  14846. case RGBDEncoding:
  14847. return [ 'RGBD', '( value, 256.0 )' ];
  14848. case GammaEncoding:
  14849. return [ 'Gamma', '( value, float( GAMMA_FACTOR ) )' ];
  14850. default:
  14851. throw new Error( 'unsupported encoding: ' + encoding );
  14852. }
  14853. }
  14854. function getTexelDecodingFunction( functionName, encoding ) {
  14855. var components = getEncodingComponents( encoding );
  14856. return 'vec4 ' + functionName + '( vec4 value ) { return ' + components[ 0 ] + 'ToLinear' + components[ 1 ] + '; }';
  14857. }
  14858. function getTexelEncodingFunction( functionName, encoding ) {
  14859. var components = getEncodingComponents( encoding );
  14860. return 'vec4 ' + functionName + '( vec4 value ) { return LinearTo' + components[ 0 ] + components[ 1 ] + '; }';
  14861. }
  14862. function getToneMappingFunction( functionName, toneMapping ) {
  14863. var toneMappingName;
  14864. switch ( toneMapping ) {
  14865. case LinearToneMapping:
  14866. toneMappingName = 'Linear';
  14867. break;
  14868. case ReinhardToneMapping:
  14869. toneMappingName = 'Reinhard';
  14870. break;
  14871. case Uncharted2ToneMapping:
  14872. toneMappingName = 'Uncharted2';
  14873. break;
  14874. case CineonToneMapping:
  14875. toneMappingName = 'OptimizedCineon';
  14876. break;
  14877. default:
  14878. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  14879. }
  14880. return 'vec3 ' + functionName + '( vec3 color ) { return ' + toneMappingName + 'ToneMapping( color ); }';
  14881. }
  14882. function generateExtensions( extensions, parameters, rendererExtensions ) {
  14883. extensions = extensions || {};
  14884. var chunks = [
  14885. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  14886. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  14887. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  14888. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  14889. ];
  14890. return chunks.filter( filterEmptyLine ).join( '\n' );
  14891. }
  14892. function generateDefines( defines ) {
  14893. var chunks = [];
  14894. for ( var name in defines ) {
  14895. var value = defines[ name ];
  14896. if ( value === false ) continue;
  14897. chunks.push( '#define ' + name + ' ' + value );
  14898. }
  14899. return chunks.join( '\n' );
  14900. }
  14901. function fetchAttributeLocations( gl, program ) {
  14902. var attributes = {};
  14903. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  14904. for ( var i = 0; i < n; i ++ ) {
  14905. var info = gl.getActiveAttrib( program, i );
  14906. var name = info.name;
  14907. // console.log( 'THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:', name, i );
  14908. attributes[ name ] = gl.getAttribLocation( program, name );
  14909. }
  14910. return attributes;
  14911. }
  14912. function filterEmptyLine( string ) {
  14913. return string !== '';
  14914. }
  14915. function replaceLightNums( string, parameters ) {
  14916. return string
  14917. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  14918. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  14919. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  14920. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  14921. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  14922. }
  14923. function parseIncludes( string ) {
  14924. var pattern = /^[ \t]*#include +<([\w\d.]+)>/gm;
  14925. function replace( match, include ) {
  14926. var replace = ShaderChunk[ include ];
  14927. if ( replace === undefined ) {
  14928. throw new Error( 'Can not resolve #include <' + include + '>' );
  14929. }
  14930. return parseIncludes( replace );
  14931. }
  14932. return string.replace( pattern, replace );
  14933. }
  14934. function unrollLoops( string ) {
  14935. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  14936. function replace( match, start, end, snippet ) {
  14937. var unroll = '';
  14938. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  14939. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  14940. }
  14941. return unroll;
  14942. }
  14943. return string.replace( pattern, replace );
  14944. }
  14945. function WebGLProgram( renderer, extensions, code, material, shader, parameters ) {
  14946. var gl = renderer.context;
  14947. var defines = material.defines;
  14948. var vertexShader = shader.vertexShader;
  14949. var fragmentShader = shader.fragmentShader;
  14950. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14951. if ( parameters.shadowMapType === PCFShadowMap ) {
  14952. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14953. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14954. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14955. }
  14956. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14957. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14958. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14959. if ( parameters.envMap ) {
  14960. switch ( material.envMap.mapping ) {
  14961. case CubeReflectionMapping:
  14962. case CubeRefractionMapping:
  14963. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14964. break;
  14965. case CubeUVReflectionMapping:
  14966. case CubeUVRefractionMapping:
  14967. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14968. break;
  14969. case EquirectangularReflectionMapping:
  14970. case EquirectangularRefractionMapping:
  14971. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14972. break;
  14973. case SphericalReflectionMapping:
  14974. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14975. break;
  14976. }
  14977. switch ( material.envMap.mapping ) {
  14978. case CubeRefractionMapping:
  14979. case EquirectangularRefractionMapping:
  14980. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14981. break;
  14982. }
  14983. switch ( material.combine ) {
  14984. case MultiplyOperation:
  14985. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14986. break;
  14987. case MixOperation:
  14988. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14989. break;
  14990. case AddOperation:
  14991. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14992. break;
  14993. }
  14994. }
  14995. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14996. // console.log( 'building new program ' );
  14997. //
  14998. var customExtensions = generateExtensions( material.extensions, parameters, extensions );
  14999. var customDefines = generateDefines( defines );
  15000. //
  15001. var program = gl.createProgram();
  15002. var prefixVertex, prefixFragment;
  15003. if ( material.isRawShaderMaterial ) {
  15004. prefixVertex = [
  15005. customDefines
  15006. ].filter( filterEmptyLine ).join( '\n' );
  15007. if ( prefixVertex.length > 0 ) {
  15008. prefixVertex += '\n';
  15009. }
  15010. prefixFragment = [
  15011. customExtensions,
  15012. customDefines
  15013. ].filter( filterEmptyLine ).join( '\n' );
  15014. if ( prefixFragment.length > 0 ) {
  15015. prefixFragment += '\n';
  15016. }
  15017. } else {
  15018. prefixVertex = [
  15019. 'precision ' + parameters.precision + ' float;',
  15020. 'precision ' + parameters.precision + ' int;',
  15021. '#define SHADER_NAME ' + shader.name,
  15022. customDefines,
  15023. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  15024. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15025. '#define MAX_BONES ' + parameters.maxBones,
  15026. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15027. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15028. parameters.map ? '#define USE_MAP' : '',
  15029. parameters.envMap ? '#define USE_ENVMAP' : '',
  15030. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15031. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15032. parameters.aoMap ? '#define USE_AOMAP' : '',
  15033. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15034. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15035. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15036. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  15037. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15038. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15039. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15040. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15041. parameters.vertexColors ? '#define USE_COLOR' : '',
  15042. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15043. parameters.skinning ? '#define USE_SKINNING' : '',
  15044. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  15045. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  15046. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  15047. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15048. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15049. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  15050. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15051. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15052. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  15053. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15054. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15055. 'uniform mat4 modelMatrix;',
  15056. 'uniform mat4 modelViewMatrix;',
  15057. 'uniform mat4 projectionMatrix;',
  15058. 'uniform mat4 viewMatrix;',
  15059. 'uniform mat3 normalMatrix;',
  15060. 'uniform vec3 cameraPosition;',
  15061. 'attribute vec3 position;',
  15062. 'attribute vec3 normal;',
  15063. 'attribute vec2 uv;',
  15064. '#ifdef USE_COLOR',
  15065. ' attribute vec3 color;',
  15066. '#endif',
  15067. '#ifdef USE_MORPHTARGETS',
  15068. ' attribute vec3 morphTarget0;',
  15069. ' attribute vec3 morphTarget1;',
  15070. ' attribute vec3 morphTarget2;',
  15071. ' attribute vec3 morphTarget3;',
  15072. ' #ifdef USE_MORPHNORMALS',
  15073. ' attribute vec3 morphNormal0;',
  15074. ' attribute vec3 morphNormal1;',
  15075. ' attribute vec3 morphNormal2;',
  15076. ' attribute vec3 morphNormal3;',
  15077. ' #else',
  15078. ' attribute vec3 morphTarget4;',
  15079. ' attribute vec3 morphTarget5;',
  15080. ' attribute vec3 morphTarget6;',
  15081. ' attribute vec3 morphTarget7;',
  15082. ' #endif',
  15083. '#endif',
  15084. '#ifdef USE_SKINNING',
  15085. ' attribute vec4 skinIndex;',
  15086. ' attribute vec4 skinWeight;',
  15087. '#endif',
  15088. '\n'
  15089. ].filter( filterEmptyLine ).join( '\n' );
  15090. prefixFragment = [
  15091. customExtensions,
  15092. 'precision ' + parameters.precision + ' float;',
  15093. 'precision ' + parameters.precision + ' int;',
  15094. '#define SHADER_NAME ' + shader.name,
  15095. customDefines,
  15096. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  15097. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  15098. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  15099. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  15100. parameters.map ? '#define USE_MAP' : '',
  15101. parameters.envMap ? '#define USE_ENVMAP' : '',
  15102. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  15103. parameters.envMap ? '#define ' + envMapModeDefine : '',
  15104. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  15105. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  15106. parameters.aoMap ? '#define USE_AOMAP' : '',
  15107. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  15108. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  15109. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  15110. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  15111. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  15112. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  15113. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  15114. parameters.vertexColors ? '#define USE_COLOR' : '',
  15115. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  15116. parameters.flatShading ? '#define FLAT_SHADED' : '',
  15117. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  15118. parameters.flipSided ? '#define FLIP_SIDED' : '',
  15119. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  15120. '#define UNION_CLIPPING_PLANES ' + ( parameters.numClippingPlanes - parameters.numClipIntersection ),
  15121. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  15122. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  15123. parameters.premultipliedAlpha ? '#define PREMULTIPLIED_ALPHA' : '',
  15124. parameters.physicallyCorrectLights ? '#define PHYSICALLY_CORRECT_LIGHTS' : '',
  15125. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  15126. parameters.logarithmicDepthBuffer && extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  15127. parameters.envMap && extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  15128. 'uniform mat4 viewMatrix;',
  15129. 'uniform vec3 cameraPosition;',
  15130. ( parameters.toneMapping !== NoToneMapping ) ? '#define TONE_MAPPING' : '',
  15131. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  15132. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( 'toneMapping', parameters.toneMapping ) : '',
  15133. parameters.dithering ? '#define DITHERING' : '',
  15134. ( 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
  15135. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  15136. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  15137. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  15138. parameters.outputEncoding ? getTexelEncodingFunction( 'linearToOutputTexel', parameters.outputEncoding ) : '',
  15139. parameters.depthPacking ? '#define DEPTH_PACKING ' + material.depthPacking : '',
  15140. '\n'
  15141. ].filter( filterEmptyLine ).join( '\n' );
  15142. }
  15143. vertexShader = parseIncludes( vertexShader );
  15144. vertexShader = replaceLightNums( vertexShader, parameters );
  15145. fragmentShader = parseIncludes( fragmentShader );
  15146. fragmentShader = replaceLightNums( fragmentShader, parameters );
  15147. if ( ! material.isShaderMaterial ) {
  15148. vertexShader = unrollLoops( vertexShader );
  15149. fragmentShader = unrollLoops( fragmentShader );
  15150. }
  15151. var vertexGlsl = prefixVertex + vertexShader;
  15152. var fragmentGlsl = prefixFragment + fragmentShader;
  15153. // console.log( '*VERTEX*', vertexGlsl );
  15154. // console.log( '*FRAGMENT*', fragmentGlsl );
  15155. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  15156. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  15157. gl.attachShader( program, glVertexShader );
  15158. gl.attachShader( program, glFragmentShader );
  15159. // Force a particular attribute to index 0.
  15160. if ( material.index0AttributeName !== undefined ) {
  15161. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  15162. } else if ( parameters.morphTargets === true ) {
  15163. // programs with morphTargets displace position out of attribute 0
  15164. gl.bindAttribLocation( program, 0, 'position' );
  15165. }
  15166. gl.linkProgram( program );
  15167. var programLog = gl.getProgramInfoLog( program );
  15168. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  15169. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  15170. var runnable = true;
  15171. var haveDiagnostics = true;
  15172. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  15173. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  15174. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  15175. runnable = false;
  15176. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  15177. } else if ( programLog !== '' ) {
  15178. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  15179. } else if ( vertexLog === '' || fragmentLog === '' ) {
  15180. haveDiagnostics = false;
  15181. }
  15182. if ( haveDiagnostics ) {
  15183. this.diagnostics = {
  15184. runnable: runnable,
  15185. material: material,
  15186. programLog: programLog,
  15187. vertexShader: {
  15188. log: vertexLog,
  15189. prefix: prefixVertex
  15190. },
  15191. fragmentShader: {
  15192. log: fragmentLog,
  15193. prefix: prefixFragment
  15194. }
  15195. };
  15196. }
  15197. // clean up
  15198. gl.deleteShader( glVertexShader );
  15199. gl.deleteShader( glFragmentShader );
  15200. // set up caching for uniform locations
  15201. var cachedUniforms;
  15202. this.getUniforms = function () {
  15203. if ( cachedUniforms === undefined ) {
  15204. cachedUniforms = new WebGLUniforms( gl, program, renderer );
  15205. }
  15206. return cachedUniforms;
  15207. };
  15208. // set up caching for attribute locations
  15209. var cachedAttributes;
  15210. this.getAttributes = function () {
  15211. if ( cachedAttributes === undefined ) {
  15212. cachedAttributes = fetchAttributeLocations( gl, program );
  15213. }
  15214. return cachedAttributes;
  15215. };
  15216. // free resource
  15217. this.destroy = function () {
  15218. gl.deleteProgram( program );
  15219. this.program = undefined;
  15220. };
  15221. // DEPRECATED
  15222. Object.defineProperties( this, {
  15223. uniforms: {
  15224. get: function () {
  15225. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  15226. return this.getUniforms();
  15227. }
  15228. },
  15229. attributes: {
  15230. get: function () {
  15231. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  15232. return this.getAttributes();
  15233. }
  15234. }
  15235. } );
  15236. //
  15237. this.id = programIdCount ++;
  15238. this.code = code;
  15239. this.usedTimes = 1;
  15240. this.program = program;
  15241. this.vertexShader = glVertexShader;
  15242. this.fragmentShader = glFragmentShader;
  15243. return this;
  15244. }
  15245. /**
  15246. * @author mrdoob / http://mrdoob.com/
  15247. */
  15248. function WebGLPrograms( renderer, extensions, capabilities ) {
  15249. var programs = [];
  15250. var shaderIDs = {
  15251. MeshDepthMaterial: 'depth',
  15252. MeshDistanceMaterial: 'distanceRGBA',
  15253. MeshNormalMaterial: 'normal',
  15254. MeshBasicMaterial: 'basic',
  15255. MeshLambertMaterial: 'lambert',
  15256. MeshPhongMaterial: 'phong',
  15257. MeshToonMaterial: 'phong',
  15258. MeshStandardMaterial: 'physical',
  15259. MeshPhysicalMaterial: 'physical',
  15260. LineBasicMaterial: 'basic',
  15261. LineDashedMaterial: 'dashed',
  15262. PointsMaterial: 'points',
  15263. ShadowMaterial: 'shadow'
  15264. };
  15265. var parameterNames = [
  15266. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  15267. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  15268. "roughnessMap", "metalnessMap", "gradientMap",
  15269. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  15270. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  15271. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  15272. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  15273. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  15274. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  15275. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking", "dithering"
  15276. ];
  15277. function allocateBones( object ) {
  15278. var skeleton = object.skeleton;
  15279. var bones = skeleton.bones;
  15280. if ( capabilities.floatVertexTextures ) {
  15281. return 1024;
  15282. } else {
  15283. // default for when object is not specified
  15284. // ( for example when prebuilding shader to be used with multiple objects )
  15285. //
  15286. // - leave some extra space for other uniforms
  15287. // - limit here is ANGLE's 254 max uniform vectors
  15288. // (up to 54 should be safe)
  15289. var nVertexUniforms = capabilities.maxVertexUniforms;
  15290. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15291. var maxBones = Math.min( nVertexMatrices, bones.length );
  15292. if ( maxBones < bones.length ) {
  15293. console.warn( 'THREE.WebGLRenderer: Skeleton has ' + bones.length + ' bones. This GPU supports ' + maxBones + '.' );
  15294. return 0;
  15295. }
  15296. return maxBones;
  15297. }
  15298. }
  15299. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  15300. var encoding;
  15301. if ( ! map ) {
  15302. encoding = LinearEncoding;
  15303. } else if ( map.isTexture ) {
  15304. encoding = map.encoding;
  15305. } else if ( map.isWebGLRenderTarget ) {
  15306. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  15307. encoding = map.texture.encoding;
  15308. }
  15309. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  15310. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  15311. encoding = GammaEncoding;
  15312. }
  15313. return encoding;
  15314. }
  15315. this.getParameters = function ( material, lights, shadows, fog, nClipPlanes, nClipIntersection, object ) {
  15316. var shaderID = shaderIDs[ material.type ];
  15317. // heuristics to create shader parameters according to lights in the scene
  15318. // (not to blow over maxLights budget)
  15319. var maxBones = object.isSkinnedMesh ? allocateBones( object ) : 0;
  15320. var precision = capabilities.precision;
  15321. if ( material.precision !== null ) {
  15322. precision = capabilities.getMaxPrecision( material.precision );
  15323. if ( precision !== material.precision ) {
  15324. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  15325. }
  15326. }
  15327. var currentRenderTarget = renderer.getRenderTarget();
  15328. var parameters = {
  15329. shaderID: shaderID,
  15330. precision: precision,
  15331. supportsVertexTextures: capabilities.vertexTextures,
  15332. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  15333. map: !! material.map,
  15334. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  15335. envMap: !! material.envMap,
  15336. envMapMode: material.envMap && material.envMap.mapping,
  15337. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  15338. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  15339. lightMap: !! material.lightMap,
  15340. aoMap: !! material.aoMap,
  15341. emissiveMap: !! material.emissiveMap,
  15342. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  15343. bumpMap: !! material.bumpMap,
  15344. normalMap: !! material.normalMap,
  15345. displacementMap: !! material.displacementMap,
  15346. roughnessMap: !! material.roughnessMap,
  15347. metalnessMap: !! material.metalnessMap,
  15348. specularMap: !! material.specularMap,
  15349. alphaMap: !! material.alphaMap,
  15350. gradientMap: !! material.gradientMap,
  15351. combine: material.combine,
  15352. vertexColors: material.vertexColors,
  15353. fog: !! fog,
  15354. useFog: material.fog,
  15355. fogExp: ( fog && fog.isFogExp2 ),
  15356. flatShading: material.flatShading,
  15357. sizeAttenuation: material.sizeAttenuation,
  15358. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  15359. skinning: material.skinning && maxBones > 0,
  15360. maxBones: maxBones,
  15361. useVertexTexture: capabilities.floatVertexTextures,
  15362. morphTargets: material.morphTargets,
  15363. morphNormals: material.morphNormals,
  15364. maxMorphTargets: renderer.maxMorphTargets,
  15365. maxMorphNormals: renderer.maxMorphNormals,
  15366. numDirLights: lights.directional.length,
  15367. numPointLights: lights.point.length,
  15368. numSpotLights: lights.spot.length,
  15369. numRectAreaLights: lights.rectArea.length,
  15370. numHemiLights: lights.hemi.length,
  15371. numClippingPlanes: nClipPlanes,
  15372. numClipIntersection: nClipIntersection,
  15373. dithering: material.dithering,
  15374. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && shadows.length > 0,
  15375. shadowMapType: renderer.shadowMap.type,
  15376. toneMapping: renderer.toneMapping,
  15377. physicallyCorrectLights: renderer.physicallyCorrectLights,
  15378. premultipliedAlpha: material.premultipliedAlpha,
  15379. alphaTest: material.alphaTest,
  15380. doubleSided: material.side === DoubleSide,
  15381. flipSided: material.side === BackSide,
  15382. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  15383. };
  15384. return parameters;
  15385. };
  15386. this.getProgramCode = function ( material, parameters ) {
  15387. var array = [];
  15388. if ( parameters.shaderID ) {
  15389. array.push( parameters.shaderID );
  15390. } else {
  15391. array.push( material.fragmentShader );
  15392. array.push( material.vertexShader );
  15393. }
  15394. if ( material.defines !== undefined ) {
  15395. for ( var name in material.defines ) {
  15396. array.push( name );
  15397. array.push( material.defines[ name ] );
  15398. }
  15399. }
  15400. for ( var i = 0; i < parameterNames.length; i ++ ) {
  15401. array.push( parameters[ parameterNames[ i ] ] );
  15402. }
  15403. array.push( material.onBeforeCompile.toString() );
  15404. array.push( renderer.gammaOutput );
  15405. return array.join();
  15406. };
  15407. this.acquireProgram = function ( material, shader, parameters, code ) {
  15408. var program;
  15409. // Check if code has been already compiled
  15410. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  15411. var programInfo = programs[ p ];
  15412. if ( programInfo.code === code ) {
  15413. program = programInfo;
  15414. ++ program.usedTimes;
  15415. break;
  15416. }
  15417. }
  15418. if ( program === undefined ) {
  15419. program = new WebGLProgram( renderer, extensions, code, material, shader, parameters );
  15420. programs.push( program );
  15421. }
  15422. return program;
  15423. };
  15424. this.releaseProgram = function ( program ) {
  15425. if ( -- program.usedTimes === 0 ) {
  15426. // Remove from unordered set
  15427. var i = programs.indexOf( program );
  15428. programs[ i ] = programs[ programs.length - 1 ];
  15429. programs.pop();
  15430. // Free WebGL resources
  15431. program.destroy();
  15432. }
  15433. };
  15434. // Exposed for resource monitoring & error feedback via renderer.info:
  15435. this.programs = programs;
  15436. }
  15437. /**
  15438. * @author mrdoob / http://mrdoob.com/
  15439. */
  15440. function WebGLTextures( _gl, extensions, state, properties, capabilities, utils, infoMemory ) {
  15441. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof window.WebGL2RenderingContext );
  15442. var _videoTextures = {};
  15443. //
  15444. function clampToMaxSize( image, maxSize ) {
  15445. if ( image.width > maxSize || image.height > maxSize ) {
  15446. // Warning: Scaling through the canvas will only work with images that use
  15447. // premultiplied alpha.
  15448. var scale = maxSize / Math.max( image.width, image.height );
  15449. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15450. canvas.width = Math.floor( image.width * scale );
  15451. canvas.height = Math.floor( image.height * scale );
  15452. var context = canvas.getContext( '2d' );
  15453. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  15454. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15455. return canvas;
  15456. }
  15457. return image;
  15458. }
  15459. function isPowerOfTwo( image ) {
  15460. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  15461. }
  15462. function makePowerOfTwo( image ) {
  15463. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof ImageBitmap ) {
  15464. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  15465. canvas.width = _Math.floorPowerOfTwo( image.width );
  15466. canvas.height = _Math.floorPowerOfTwo( image.height );
  15467. var context = canvas.getContext( '2d' );
  15468. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  15469. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  15470. return canvas;
  15471. }
  15472. return image;
  15473. }
  15474. function textureNeedsPowerOfTwo( texture ) {
  15475. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  15476. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  15477. }
  15478. function textureNeedsGenerateMipmaps( texture, isPowerOfTwo ) {
  15479. return texture.generateMipmaps && isPowerOfTwo &&
  15480. texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter;
  15481. }
  15482. // Fallback filters for non-power-of-2 textures
  15483. function filterFallback( f ) {
  15484. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  15485. return _gl.NEAREST;
  15486. }
  15487. return _gl.LINEAR;
  15488. }
  15489. //
  15490. function onTextureDispose( event ) {
  15491. var texture = event.target;
  15492. texture.removeEventListener( 'dispose', onTextureDispose );
  15493. deallocateTexture( texture );
  15494. if ( texture.isVideoTexture ) {
  15495. delete _videoTextures[ texture.id ];
  15496. }
  15497. infoMemory.textures --;
  15498. }
  15499. function onRenderTargetDispose( event ) {
  15500. var renderTarget = event.target;
  15501. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  15502. deallocateRenderTarget( renderTarget );
  15503. infoMemory.textures --;
  15504. }
  15505. //
  15506. function deallocateTexture( texture ) {
  15507. var textureProperties = properties.get( texture );
  15508. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  15509. // cube texture
  15510. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  15511. } else {
  15512. // 2D texture
  15513. if ( textureProperties.__webglInit === undefined ) return;
  15514. _gl.deleteTexture( textureProperties.__webglTexture );
  15515. }
  15516. // remove all webgl properties
  15517. properties.remove( texture );
  15518. }
  15519. function deallocateRenderTarget( renderTarget ) {
  15520. var renderTargetProperties = properties.get( renderTarget );
  15521. var textureProperties = properties.get( renderTarget.texture );
  15522. if ( ! renderTarget ) return;
  15523. if ( textureProperties.__webglTexture !== undefined ) {
  15524. _gl.deleteTexture( textureProperties.__webglTexture );
  15525. }
  15526. if ( renderTarget.depthTexture ) {
  15527. renderTarget.depthTexture.dispose();
  15528. }
  15529. if ( renderTarget.isWebGLRenderTargetCube ) {
  15530. for ( var i = 0; i < 6; i ++ ) {
  15531. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  15532. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  15533. }
  15534. } else {
  15535. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  15536. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  15537. }
  15538. properties.remove( renderTarget.texture );
  15539. properties.remove( renderTarget );
  15540. }
  15541. //
  15542. function setTexture2D( texture, slot ) {
  15543. var textureProperties = properties.get( texture );
  15544. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15545. var image = texture.image;
  15546. if ( image === undefined ) {
  15547. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  15548. } else if ( image.complete === false ) {
  15549. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  15550. } else {
  15551. uploadTexture( textureProperties, texture, slot );
  15552. return;
  15553. }
  15554. }
  15555. state.activeTexture( _gl.TEXTURE0 + slot );
  15556. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15557. }
  15558. function setTextureCube( texture, slot ) {
  15559. var textureProperties = properties.get( texture );
  15560. if ( texture.image.length === 6 ) {
  15561. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  15562. if ( ! textureProperties.__image__webglTextureCube ) {
  15563. texture.addEventListener( 'dispose', onTextureDispose );
  15564. textureProperties.__image__webglTextureCube = _gl.createTexture();
  15565. infoMemory.textures ++;
  15566. }
  15567. state.activeTexture( _gl.TEXTURE0 + slot );
  15568. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15569. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15570. var isCompressed = ( texture && texture.isCompressedTexture );
  15571. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  15572. var cubeImage = [];
  15573. for ( var i = 0; i < 6; i ++ ) {
  15574. if ( ! isCompressed && ! isDataTexture ) {
  15575. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  15576. } else {
  15577. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  15578. }
  15579. }
  15580. var image = cubeImage[ 0 ],
  15581. isPowerOfTwoImage = isPowerOfTwo( image ),
  15582. glFormat = utils.convert( texture.format ),
  15583. glType = utils.convert( texture.type );
  15584. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  15585. for ( var i = 0; i < 6; i ++ ) {
  15586. if ( ! isCompressed ) {
  15587. if ( isDataTexture ) {
  15588. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  15589. } else {
  15590. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15591. }
  15592. } else {
  15593. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15594. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15595. mipmap = mipmaps[ j ];
  15596. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15597. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15598. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15599. } else {
  15600. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()' );
  15601. }
  15602. } else {
  15603. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15604. }
  15605. }
  15606. }
  15607. }
  15608. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) {
  15609. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15610. }
  15611. textureProperties.__version = texture.version;
  15612. if ( texture.onUpdate ) texture.onUpdate( texture );
  15613. } else {
  15614. state.activeTexture( _gl.TEXTURE0 + slot );
  15615. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  15616. }
  15617. }
  15618. }
  15619. function setTextureCubeDynamic( texture, slot ) {
  15620. state.activeTexture( _gl.TEXTURE0 + slot );
  15621. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  15622. }
  15623. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  15624. var extension;
  15625. if ( isPowerOfTwoImage ) {
  15626. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, utils.convert( texture.wrapS ) );
  15627. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, utils.convert( texture.wrapT ) );
  15628. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, utils.convert( texture.magFilter ) );
  15629. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, utils.convert( texture.minFilter ) );
  15630. } else {
  15631. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15632. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15633. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  15634. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  15635. }
  15636. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15637. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15638. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  15639. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  15640. }
  15641. }
  15642. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15643. if ( extension ) {
  15644. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  15645. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  15646. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  15647. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  15648. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  15649. }
  15650. }
  15651. }
  15652. function uploadTexture( textureProperties, texture, slot ) {
  15653. if ( textureProperties.__webglInit === undefined ) {
  15654. textureProperties.__webglInit = true;
  15655. texture.addEventListener( 'dispose', onTextureDispose );
  15656. textureProperties.__webglTexture = _gl.createTexture();
  15657. if ( texture.isVideoTexture ) {
  15658. _videoTextures[ texture.id ] = texture;
  15659. }
  15660. infoMemory.textures ++;
  15661. }
  15662. state.activeTexture( _gl.TEXTURE0 + slot );
  15663. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15664. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15665. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15666. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15667. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  15668. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  15669. image = makePowerOfTwo( image );
  15670. }
  15671. var isPowerOfTwoImage = isPowerOfTwo( image ),
  15672. glFormat = utils.convert( texture.format ),
  15673. glType = utils.convert( texture.type );
  15674. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  15675. var mipmap, mipmaps = texture.mipmaps;
  15676. if ( texture.isDepthTexture ) {
  15677. // populate depth texture with dummy data
  15678. var internalFormat = _gl.DEPTH_COMPONENT;
  15679. if ( texture.type === FloatType ) {
  15680. if ( ! _isWebGL2 ) throw new Error( 'Float Depth Texture only supported in WebGL2.0' );
  15681. internalFormat = _gl.DEPTH_COMPONENT32F;
  15682. } else if ( _isWebGL2 ) {
  15683. // WebGL 2.0 requires signed internalformat for glTexImage2D
  15684. internalFormat = _gl.DEPTH_COMPONENT16;
  15685. }
  15686. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  15687. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15688. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  15689. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15690. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  15691. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  15692. texture.type = UnsignedShortType;
  15693. glType = utils.convert( texture.type );
  15694. }
  15695. }
  15696. // Depth stencil textures need the DEPTH_STENCIL internal format
  15697. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15698. if ( texture.format === DepthStencilFormat ) {
  15699. internalFormat = _gl.DEPTH_STENCIL;
  15700. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  15701. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  15702. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  15703. if ( texture.type !== UnsignedInt248Type ) {
  15704. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  15705. texture.type = UnsignedInt248Type;
  15706. glType = utils.convert( texture.type );
  15707. }
  15708. }
  15709. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  15710. } else if ( texture.isDataTexture ) {
  15711. // use manually created mipmaps if available
  15712. // if there are no manual mipmaps
  15713. // set 0 level mipmap and then use GL to generate other mipmap levels
  15714. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15715. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15716. mipmap = mipmaps[ i ];
  15717. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15718. }
  15719. texture.generateMipmaps = false;
  15720. } else {
  15721. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15722. }
  15723. } else if ( texture.isCompressedTexture ) {
  15724. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15725. mipmap = mipmaps[ i ];
  15726. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  15727. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  15728. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15729. } else {
  15730. console.warn( 'THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()' );
  15731. }
  15732. } else {
  15733. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15734. }
  15735. }
  15736. } else {
  15737. // regular Texture (image, video, canvas)
  15738. // use manually created mipmaps if available
  15739. // if there are no manual mipmaps
  15740. // set 0 level mipmap and then use GL to generate other mipmap levels
  15741. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  15742. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15743. mipmap = mipmaps[ i ];
  15744. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15745. }
  15746. texture.generateMipmaps = false;
  15747. } else {
  15748. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  15749. }
  15750. }
  15751. if ( textureNeedsGenerateMipmaps( texture, isPowerOfTwoImage ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15752. textureProperties.__version = texture.version;
  15753. if ( texture.onUpdate ) texture.onUpdate( texture );
  15754. }
  15755. // Render targets
  15756. // Setup storage for target texture and bind it to correct framebuffer
  15757. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  15758. var glFormat = utils.convert( renderTarget.texture.format );
  15759. var glType = utils.convert( renderTarget.texture.type );
  15760. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15761. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15762. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  15763. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15764. }
  15765. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15766. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  15767. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15768. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15769. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15770. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15771. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15772. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15773. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15774. } else {
  15775. // FIXME: We don't support !depth !stencil
  15776. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15777. }
  15778. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15779. }
  15780. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15781. function setupDepthTexture( framebuffer, renderTarget ) {
  15782. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  15783. if ( isCube ) throw new Error( 'Depth Texture with cube render targets is not supported' );
  15784. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15785. if ( ! ( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15786. throw new Error( 'renderTarget.depthTexture must be an instance of THREE.DepthTexture' );
  15787. }
  15788. // upload an empty depth texture with framebuffer size
  15789. if ( ! properties.get( renderTarget.depthTexture ).__webglTexture ||
  15790. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15791. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15792. renderTarget.depthTexture.image.width = renderTarget.width;
  15793. renderTarget.depthTexture.image.height = renderTarget.height;
  15794. renderTarget.depthTexture.needsUpdate = true;
  15795. }
  15796. setTexture2D( renderTarget.depthTexture, 0 );
  15797. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15798. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15799. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15800. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15801. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15802. } else {
  15803. throw new Error( 'Unknown depthTexture format' );
  15804. }
  15805. }
  15806. // Setup GL resources for a non-texture depth buffer
  15807. function setupDepthRenderbuffer( renderTarget ) {
  15808. var renderTargetProperties = properties.get( renderTarget );
  15809. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15810. if ( renderTarget.depthTexture ) {
  15811. if ( isCube ) throw new Error( 'target.depthTexture not supported in Cube render targets' );
  15812. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15813. } else {
  15814. if ( isCube ) {
  15815. renderTargetProperties.__webglDepthbuffer = [];
  15816. for ( var i = 0; i < 6; i ++ ) {
  15817. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15818. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15819. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  15820. }
  15821. } else {
  15822. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15823. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15824. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  15825. }
  15826. }
  15827. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15828. }
  15829. // Set up GL resources for the render target
  15830. function setupRenderTarget( renderTarget ) {
  15831. var renderTargetProperties = properties.get( renderTarget );
  15832. var textureProperties = properties.get( renderTarget.texture );
  15833. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15834. textureProperties.__webglTexture = _gl.createTexture();
  15835. infoMemory.textures ++;
  15836. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15837. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15838. // Setup framebuffer
  15839. if ( isCube ) {
  15840. renderTargetProperties.__webglFramebuffer = [];
  15841. for ( var i = 0; i < 6; i ++ ) {
  15842. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15843. }
  15844. } else {
  15845. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15846. }
  15847. // Setup color buffer
  15848. if ( isCube ) {
  15849. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15850. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  15851. for ( var i = 0; i < 6; i ++ ) {
  15852. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15853. }
  15854. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15855. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15856. } else {
  15857. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15858. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  15859. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  15860. if ( textureNeedsGenerateMipmaps( renderTarget.texture, isTargetPowerOfTwo ) ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15861. state.bindTexture( _gl.TEXTURE_2D, null );
  15862. }
  15863. // Setup depth and stencil buffers
  15864. if ( renderTarget.depthBuffer ) {
  15865. setupDepthRenderbuffer( renderTarget );
  15866. }
  15867. }
  15868. function updateRenderTargetMipmap( renderTarget ) {
  15869. var texture = renderTarget.texture;
  15870. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15871. if ( textureNeedsGenerateMipmaps( texture, isTargetPowerOfTwo ) ) {
  15872. var target = renderTarget.isWebGLRenderTargetCube ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15873. var webglTexture = properties.get( texture ).__webglTexture;
  15874. state.bindTexture( target, webglTexture );
  15875. _gl.generateMipmap( target );
  15876. state.bindTexture( target, null );
  15877. }
  15878. }
  15879. function updateVideoTextures() {
  15880. for ( var id in _videoTextures ) {
  15881. _videoTextures[ id ].update();
  15882. }
  15883. }
  15884. this.setTexture2D = setTexture2D;
  15885. this.setTextureCube = setTextureCube;
  15886. this.setTextureCubeDynamic = setTextureCubeDynamic;
  15887. this.setupRenderTarget = setupRenderTarget;
  15888. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15889. this.updateVideoTextures = updateVideoTextures;
  15890. }
  15891. /**
  15892. * @author fordacious / fordacious.github.io
  15893. */
  15894. function WebGLProperties() {
  15895. var properties = {};
  15896. function get( object ) {
  15897. var uuid = object.uuid;
  15898. var map = properties[ uuid ];
  15899. if ( map === undefined ) {
  15900. map = {};
  15901. properties[ uuid ] = map;
  15902. }
  15903. return map;
  15904. }
  15905. function remove( object ) {
  15906. delete properties[ object.uuid ];
  15907. }
  15908. function clear() {
  15909. properties = {};
  15910. }
  15911. return {
  15912. get: get,
  15913. remove: remove,
  15914. clear: clear
  15915. };
  15916. }
  15917. /**
  15918. * @author mrdoob / http://mrdoob.com/
  15919. */
  15920. function WebGLState( gl, extensions, utils ) {
  15921. function ColorBuffer() {
  15922. var locked = false;
  15923. var color = new Vector4();
  15924. var currentColorMask = null;
  15925. var currentColorClear = new Vector4( 0, 0, 0, 0 );
  15926. return {
  15927. setMask: function ( colorMask ) {
  15928. if ( currentColorMask !== colorMask && ! locked ) {
  15929. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15930. currentColorMask = colorMask;
  15931. }
  15932. },
  15933. setLocked: function ( lock ) {
  15934. locked = lock;
  15935. },
  15936. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15937. if ( premultipliedAlpha === true ) {
  15938. r *= a; g *= a; b *= a;
  15939. }
  15940. color.set( r, g, b, a );
  15941. if ( currentColorClear.equals( color ) === false ) {
  15942. gl.clearColor( r, g, b, a );
  15943. currentColorClear.copy( color );
  15944. }
  15945. },
  15946. reset: function () {
  15947. locked = false;
  15948. currentColorMask = null;
  15949. currentColorClear.set( - 1, 0, 0, 0 ); // set to invalid state
  15950. }
  15951. };
  15952. }
  15953. function DepthBuffer() {
  15954. var locked = false;
  15955. var currentDepthMask = null;
  15956. var currentDepthFunc = null;
  15957. var currentDepthClear = null;
  15958. return {
  15959. setTest: function ( depthTest ) {
  15960. if ( depthTest ) {
  15961. enable( gl.DEPTH_TEST );
  15962. } else {
  15963. disable( gl.DEPTH_TEST );
  15964. }
  15965. },
  15966. setMask: function ( depthMask ) {
  15967. if ( currentDepthMask !== depthMask && ! locked ) {
  15968. gl.depthMask( depthMask );
  15969. currentDepthMask = depthMask;
  15970. }
  15971. },
  15972. setFunc: function ( depthFunc ) {
  15973. if ( currentDepthFunc !== depthFunc ) {
  15974. if ( depthFunc ) {
  15975. switch ( depthFunc ) {
  15976. case NeverDepth:
  15977. gl.depthFunc( gl.NEVER );
  15978. break;
  15979. case AlwaysDepth:
  15980. gl.depthFunc( gl.ALWAYS );
  15981. break;
  15982. case LessDepth:
  15983. gl.depthFunc( gl.LESS );
  15984. break;
  15985. case LessEqualDepth:
  15986. gl.depthFunc( gl.LEQUAL );
  15987. break;
  15988. case EqualDepth:
  15989. gl.depthFunc( gl.EQUAL );
  15990. break;
  15991. case GreaterEqualDepth:
  15992. gl.depthFunc( gl.GEQUAL );
  15993. break;
  15994. case GreaterDepth:
  15995. gl.depthFunc( gl.GREATER );
  15996. break;
  15997. case NotEqualDepth:
  15998. gl.depthFunc( gl.NOTEQUAL );
  15999. break;
  16000. default:
  16001. gl.depthFunc( gl.LEQUAL );
  16002. }
  16003. } else {
  16004. gl.depthFunc( gl.LEQUAL );
  16005. }
  16006. currentDepthFunc = depthFunc;
  16007. }
  16008. },
  16009. setLocked: function ( lock ) {
  16010. locked = lock;
  16011. },
  16012. setClear: function ( depth ) {
  16013. if ( currentDepthClear !== depth ) {
  16014. gl.clearDepth( depth );
  16015. currentDepthClear = depth;
  16016. }
  16017. },
  16018. reset: function () {
  16019. locked = false;
  16020. currentDepthMask = null;
  16021. currentDepthFunc = null;
  16022. currentDepthClear = null;
  16023. }
  16024. };
  16025. }
  16026. function StencilBuffer() {
  16027. var locked = false;
  16028. var currentStencilMask = null;
  16029. var currentStencilFunc = null;
  16030. var currentStencilRef = null;
  16031. var currentStencilFuncMask = null;
  16032. var currentStencilFail = null;
  16033. var currentStencilZFail = null;
  16034. var currentStencilZPass = null;
  16035. var currentStencilClear = null;
  16036. return {
  16037. setTest: function ( stencilTest ) {
  16038. if ( stencilTest ) {
  16039. enable( gl.STENCIL_TEST );
  16040. } else {
  16041. disable( gl.STENCIL_TEST );
  16042. }
  16043. },
  16044. setMask: function ( stencilMask ) {
  16045. if ( currentStencilMask !== stencilMask && ! locked ) {
  16046. gl.stencilMask( stencilMask );
  16047. currentStencilMask = stencilMask;
  16048. }
  16049. },
  16050. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  16051. if ( currentStencilFunc !== stencilFunc ||
  16052. currentStencilRef !== stencilRef ||
  16053. currentStencilFuncMask !== stencilMask ) {
  16054. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  16055. currentStencilFunc = stencilFunc;
  16056. currentStencilRef = stencilRef;
  16057. currentStencilFuncMask = stencilMask;
  16058. }
  16059. },
  16060. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  16061. if ( currentStencilFail !== stencilFail ||
  16062. currentStencilZFail !== stencilZFail ||
  16063. currentStencilZPass !== stencilZPass ) {
  16064. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  16065. currentStencilFail = stencilFail;
  16066. currentStencilZFail = stencilZFail;
  16067. currentStencilZPass = stencilZPass;
  16068. }
  16069. },
  16070. setLocked: function ( lock ) {
  16071. locked = lock;
  16072. },
  16073. setClear: function ( stencil ) {
  16074. if ( currentStencilClear !== stencil ) {
  16075. gl.clearStencil( stencil );
  16076. currentStencilClear = stencil;
  16077. }
  16078. },
  16079. reset: function () {
  16080. locked = false;
  16081. currentStencilMask = null;
  16082. currentStencilFunc = null;
  16083. currentStencilRef = null;
  16084. currentStencilFuncMask = null;
  16085. currentStencilFail = null;
  16086. currentStencilZFail = null;
  16087. currentStencilZPass = null;
  16088. currentStencilClear = null;
  16089. }
  16090. };
  16091. }
  16092. //
  16093. var colorBuffer = new ColorBuffer();
  16094. var depthBuffer = new DepthBuffer();
  16095. var stencilBuffer = new StencilBuffer();
  16096. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16097. var newAttributes = new Uint8Array( maxVertexAttributes );
  16098. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  16099. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  16100. var capabilities = {};
  16101. var compressedTextureFormats = null;
  16102. var currentProgram = null;
  16103. var currentBlending = null;
  16104. var currentBlendEquation = null;
  16105. var currentBlendSrc = null;
  16106. var currentBlendDst = null;
  16107. var currentBlendEquationAlpha = null;
  16108. var currentBlendSrcAlpha = null;
  16109. var currentBlendDstAlpha = null;
  16110. var currentPremultipledAlpha = false;
  16111. var currentFlipSided = null;
  16112. var currentCullFace = null;
  16113. var currentLineWidth = null;
  16114. var currentPolygonOffsetFactor = null;
  16115. var currentPolygonOffsetUnits = null;
  16116. var maxTextures = gl.getParameter( gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS );
  16117. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  16118. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  16119. var currentTextureSlot = null;
  16120. var currentBoundTextures = {};
  16121. var currentScissor = new Vector4();
  16122. var currentViewport = new Vector4();
  16123. function createTexture( type, target, count ) {
  16124. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  16125. var texture = gl.createTexture();
  16126. gl.bindTexture( type, texture );
  16127. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  16128. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  16129. for ( var i = 0; i < count; i ++ ) {
  16130. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  16131. }
  16132. return texture;
  16133. }
  16134. var emptyTextures = {};
  16135. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  16136. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  16137. // init
  16138. colorBuffer.setClear( 0, 0, 0, 1 );
  16139. depthBuffer.setClear( 1 );
  16140. stencilBuffer.setClear( 0 );
  16141. enable( gl.DEPTH_TEST );
  16142. depthBuffer.setFunc( LessEqualDepth );
  16143. setFlipSided( false );
  16144. setCullFace( CullFaceBack );
  16145. enable( gl.CULL_FACE );
  16146. enable( gl.BLEND );
  16147. setBlending( NormalBlending );
  16148. //
  16149. function initAttributes() {
  16150. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  16151. newAttributes[ i ] = 0;
  16152. }
  16153. }
  16154. function enableAttribute( attribute ) {
  16155. newAttributes[ attribute ] = 1;
  16156. if ( enabledAttributes[ attribute ] === 0 ) {
  16157. gl.enableVertexAttribArray( attribute );
  16158. enabledAttributes[ attribute ] = 1;
  16159. }
  16160. if ( attributeDivisors[ attribute ] !== 0 ) {
  16161. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16162. extension.vertexAttribDivisorANGLE( attribute, 0 );
  16163. attributeDivisors[ attribute ] = 0;
  16164. }
  16165. }
  16166. function enableAttributeAndDivisor( attribute, meshPerAttribute ) {
  16167. newAttributes[ attribute ] = 1;
  16168. if ( enabledAttributes[ attribute ] === 0 ) {
  16169. gl.enableVertexAttribArray( attribute );
  16170. enabledAttributes[ attribute ] = 1;
  16171. }
  16172. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  16173. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  16174. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  16175. attributeDivisors[ attribute ] = meshPerAttribute;
  16176. }
  16177. }
  16178. function disableUnusedAttributes() {
  16179. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  16180. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  16181. gl.disableVertexAttribArray( i );
  16182. enabledAttributes[ i ] = 0;
  16183. }
  16184. }
  16185. }
  16186. function enable( id ) {
  16187. if ( capabilities[ id ] !== true ) {
  16188. gl.enable( id );
  16189. capabilities[ id ] = true;
  16190. }
  16191. }
  16192. function disable( id ) {
  16193. if ( capabilities[ id ] !== false ) {
  16194. gl.disable( id );
  16195. capabilities[ id ] = false;
  16196. }
  16197. }
  16198. function getCompressedTextureFormats() {
  16199. if ( compressedTextureFormats === null ) {
  16200. compressedTextureFormats = [];
  16201. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  16202. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  16203. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  16204. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  16205. for ( var i = 0; i < formats.length; i ++ ) {
  16206. compressedTextureFormats.push( formats[ i ] );
  16207. }
  16208. }
  16209. }
  16210. return compressedTextureFormats;
  16211. }
  16212. function useProgram( program ) {
  16213. if ( currentProgram !== program ) {
  16214. gl.useProgram( program );
  16215. currentProgram = program;
  16216. return true;
  16217. }
  16218. return false;
  16219. }
  16220. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  16221. if ( blending !== NoBlending ) {
  16222. enable( gl.BLEND );
  16223. } else {
  16224. disable( gl.BLEND );
  16225. }
  16226. if ( blending !== CustomBlending ) {
  16227. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  16228. switch ( blending ) {
  16229. case AdditiveBlending:
  16230. if ( premultipliedAlpha ) {
  16231. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16232. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  16233. } else {
  16234. gl.blendEquation( gl.FUNC_ADD );
  16235. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  16236. }
  16237. break;
  16238. case SubtractiveBlending:
  16239. if ( premultipliedAlpha ) {
  16240. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16241. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  16242. } else {
  16243. gl.blendEquation( gl.FUNC_ADD );
  16244. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  16245. }
  16246. break;
  16247. case MultiplyBlending:
  16248. if ( premultipliedAlpha ) {
  16249. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16250. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  16251. } else {
  16252. gl.blendEquation( gl.FUNC_ADD );
  16253. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  16254. }
  16255. break;
  16256. default:
  16257. if ( premultipliedAlpha ) {
  16258. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16259. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  16260. } else {
  16261. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  16262. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  16263. }
  16264. }
  16265. }
  16266. currentBlendEquation = null;
  16267. currentBlendSrc = null;
  16268. currentBlendDst = null;
  16269. currentBlendEquationAlpha = null;
  16270. currentBlendSrcAlpha = null;
  16271. currentBlendDstAlpha = null;
  16272. } else {
  16273. blendEquationAlpha = blendEquationAlpha || blendEquation;
  16274. blendSrcAlpha = blendSrcAlpha || blendSrc;
  16275. blendDstAlpha = blendDstAlpha || blendDst;
  16276. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  16277. gl.blendEquationSeparate( utils.convert( blendEquation ), utils.convert( blendEquationAlpha ) );
  16278. currentBlendEquation = blendEquation;
  16279. currentBlendEquationAlpha = blendEquationAlpha;
  16280. }
  16281. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  16282. gl.blendFuncSeparate( utils.convert( blendSrc ), utils.convert( blendDst ), utils.convert( blendSrcAlpha ), utils.convert( blendDstAlpha ) );
  16283. currentBlendSrc = blendSrc;
  16284. currentBlendDst = blendDst;
  16285. currentBlendSrcAlpha = blendSrcAlpha;
  16286. currentBlendDstAlpha = blendDstAlpha;
  16287. }
  16288. }
  16289. currentBlending = blending;
  16290. currentPremultipledAlpha = premultipliedAlpha;
  16291. }
  16292. function setMaterial( material, frontFaceCW ) {
  16293. material.side === DoubleSide
  16294. ? disable( gl.CULL_FACE )
  16295. : enable( gl.CULL_FACE );
  16296. var flipSided = ( material.side === BackSide );
  16297. if ( frontFaceCW ) flipSided = ! flipSided;
  16298. setFlipSided( flipSided );
  16299. material.transparent === true
  16300. ? setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  16301. : setBlending( NoBlending );
  16302. depthBuffer.setFunc( material.depthFunc );
  16303. depthBuffer.setTest( material.depthTest );
  16304. depthBuffer.setMask( material.depthWrite );
  16305. colorBuffer.setMask( material.colorWrite );
  16306. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16307. }
  16308. //
  16309. function setFlipSided( flipSided ) {
  16310. if ( currentFlipSided !== flipSided ) {
  16311. if ( flipSided ) {
  16312. gl.frontFace( gl.CW );
  16313. } else {
  16314. gl.frontFace( gl.CCW );
  16315. }
  16316. currentFlipSided = flipSided;
  16317. }
  16318. }
  16319. function setCullFace( cullFace ) {
  16320. if ( cullFace !== CullFaceNone ) {
  16321. enable( gl.CULL_FACE );
  16322. if ( cullFace !== currentCullFace ) {
  16323. if ( cullFace === CullFaceBack ) {
  16324. gl.cullFace( gl.BACK );
  16325. } else if ( cullFace === CullFaceFront ) {
  16326. gl.cullFace( gl.FRONT );
  16327. } else {
  16328. gl.cullFace( gl.FRONT_AND_BACK );
  16329. }
  16330. }
  16331. } else {
  16332. disable( gl.CULL_FACE );
  16333. }
  16334. currentCullFace = cullFace;
  16335. }
  16336. function setLineWidth( width ) {
  16337. if ( width !== currentLineWidth ) {
  16338. if ( lineWidthAvailable ) gl.lineWidth( width );
  16339. currentLineWidth = width;
  16340. }
  16341. }
  16342. function setPolygonOffset( polygonOffset, factor, units ) {
  16343. if ( polygonOffset ) {
  16344. enable( gl.POLYGON_OFFSET_FILL );
  16345. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  16346. gl.polygonOffset( factor, units );
  16347. currentPolygonOffsetFactor = factor;
  16348. currentPolygonOffsetUnits = units;
  16349. }
  16350. } else {
  16351. disable( gl.POLYGON_OFFSET_FILL );
  16352. }
  16353. }
  16354. function setScissorTest( scissorTest ) {
  16355. if ( scissorTest ) {
  16356. enable( gl.SCISSOR_TEST );
  16357. } else {
  16358. disable( gl.SCISSOR_TEST );
  16359. }
  16360. }
  16361. // texture
  16362. function activeTexture( webglSlot ) {
  16363. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  16364. if ( currentTextureSlot !== webglSlot ) {
  16365. gl.activeTexture( webglSlot );
  16366. currentTextureSlot = webglSlot;
  16367. }
  16368. }
  16369. function bindTexture( webglType, webglTexture ) {
  16370. if ( currentTextureSlot === null ) {
  16371. activeTexture();
  16372. }
  16373. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  16374. if ( boundTexture === undefined ) {
  16375. boundTexture = { type: undefined, texture: undefined };
  16376. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  16377. }
  16378. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  16379. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  16380. boundTexture.type = webglType;
  16381. boundTexture.texture = webglTexture;
  16382. }
  16383. }
  16384. function compressedTexImage2D() {
  16385. try {
  16386. gl.compressedTexImage2D.apply( gl, arguments );
  16387. } catch ( error ) {
  16388. console.error( 'THREE.WebGLState:', error );
  16389. }
  16390. }
  16391. function texImage2D() {
  16392. try {
  16393. gl.texImage2D.apply( gl, arguments );
  16394. } catch ( error ) {
  16395. console.error( 'THREE.WebGLState:', error );
  16396. }
  16397. }
  16398. //
  16399. function scissor( scissor ) {
  16400. if ( currentScissor.equals( scissor ) === false ) {
  16401. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  16402. currentScissor.copy( scissor );
  16403. }
  16404. }
  16405. function viewport( viewport ) {
  16406. if ( currentViewport.equals( viewport ) === false ) {
  16407. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  16408. currentViewport.copy( viewport );
  16409. }
  16410. }
  16411. //
  16412. function reset() {
  16413. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  16414. if ( enabledAttributes[ i ] === 1 ) {
  16415. gl.disableVertexAttribArray( i );
  16416. enabledAttributes[ i ] = 0;
  16417. }
  16418. }
  16419. capabilities = {};
  16420. compressedTextureFormats = null;
  16421. currentTextureSlot = null;
  16422. currentBoundTextures = {};
  16423. currentProgram = null;
  16424. currentBlending = null;
  16425. currentFlipSided = null;
  16426. currentCullFace = null;
  16427. colorBuffer.reset();
  16428. depthBuffer.reset();
  16429. stencilBuffer.reset();
  16430. }
  16431. return {
  16432. buffers: {
  16433. color: colorBuffer,
  16434. depth: depthBuffer,
  16435. stencil: stencilBuffer
  16436. },
  16437. initAttributes: initAttributes,
  16438. enableAttribute: enableAttribute,
  16439. enableAttributeAndDivisor: enableAttributeAndDivisor,
  16440. disableUnusedAttributes: disableUnusedAttributes,
  16441. enable: enable,
  16442. disable: disable,
  16443. getCompressedTextureFormats: getCompressedTextureFormats,
  16444. useProgram: useProgram,
  16445. setBlending: setBlending,
  16446. setMaterial: setMaterial,
  16447. setFlipSided: setFlipSided,
  16448. setCullFace: setCullFace,
  16449. setLineWidth: setLineWidth,
  16450. setPolygonOffset: setPolygonOffset,
  16451. setScissorTest: setScissorTest,
  16452. activeTexture: activeTexture,
  16453. bindTexture: bindTexture,
  16454. compressedTexImage2D: compressedTexImage2D,
  16455. texImage2D: texImage2D,
  16456. scissor: scissor,
  16457. viewport: viewport,
  16458. reset: reset
  16459. };
  16460. }
  16461. /**
  16462. * @author mrdoob / http://mrdoob.com/
  16463. */
  16464. function WebGLCapabilities( gl, extensions, parameters ) {
  16465. var maxAnisotropy;
  16466. function getMaxAnisotropy() {
  16467. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  16468. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  16469. if ( extension !== null ) {
  16470. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  16471. } else {
  16472. maxAnisotropy = 0;
  16473. }
  16474. return maxAnisotropy;
  16475. }
  16476. function getMaxPrecision( precision ) {
  16477. if ( precision === 'highp' ) {
  16478. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  16479. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  16480. return 'highp';
  16481. }
  16482. precision = 'mediump';
  16483. }
  16484. if ( precision === 'mediump' ) {
  16485. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  16486. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  16487. return 'mediump';
  16488. }
  16489. }
  16490. return 'lowp';
  16491. }
  16492. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  16493. var maxPrecision = getMaxPrecision( precision );
  16494. if ( maxPrecision !== precision ) {
  16495. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  16496. precision = maxPrecision;
  16497. }
  16498. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true;
  16499. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  16500. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  16501. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  16502. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  16503. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  16504. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  16505. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  16506. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  16507. var vertexTextures = maxVertexTextures > 0;
  16508. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  16509. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  16510. return {
  16511. getMaxAnisotropy: getMaxAnisotropy,
  16512. getMaxPrecision: getMaxPrecision,
  16513. precision: precision,
  16514. logarithmicDepthBuffer: logarithmicDepthBuffer,
  16515. maxTextures: maxTextures,
  16516. maxVertexTextures: maxVertexTextures,
  16517. maxTextureSize: maxTextureSize,
  16518. maxCubemapSize: maxCubemapSize,
  16519. maxAttributes: maxAttributes,
  16520. maxVertexUniforms: maxVertexUniforms,
  16521. maxVaryings: maxVaryings,
  16522. maxFragmentUniforms: maxFragmentUniforms,
  16523. vertexTextures: vertexTextures,
  16524. floatFragmentTextures: floatFragmentTextures,
  16525. floatVertexTextures: floatVertexTextures
  16526. };
  16527. }
  16528. /**
  16529. * @author mrdoob / http://mrdoob.com/
  16530. * @author greggman / http://games.greggman.com/
  16531. * @author zz85 / http://www.lab4games.net/zz85/blog
  16532. * @author tschw
  16533. */
  16534. function PerspectiveCamera( fov, aspect, near, far ) {
  16535. Camera.call( this );
  16536. this.type = 'PerspectiveCamera';
  16537. this.fov = fov !== undefined ? fov : 50;
  16538. this.zoom = 1;
  16539. this.near = near !== undefined ? near : 0.1;
  16540. this.far = far !== undefined ? far : 2000;
  16541. this.focus = 10;
  16542. this.aspect = aspect !== undefined ? aspect : 1;
  16543. this.view = null;
  16544. this.filmGauge = 35; // width of the film (default in millimeters)
  16545. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  16546. this.updateProjectionMatrix();
  16547. }
  16548. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  16549. constructor: PerspectiveCamera,
  16550. isPerspectiveCamera: true,
  16551. copy: function ( source, recursive ) {
  16552. Camera.prototype.copy.call( this, source, recursive );
  16553. this.fov = source.fov;
  16554. this.zoom = source.zoom;
  16555. this.near = source.near;
  16556. this.far = source.far;
  16557. this.focus = source.focus;
  16558. this.aspect = source.aspect;
  16559. this.view = source.view === null ? null : Object.assign( {}, source.view );
  16560. this.filmGauge = source.filmGauge;
  16561. this.filmOffset = source.filmOffset;
  16562. return this;
  16563. },
  16564. /**
  16565. * Sets the FOV by focal length in respect to the current .filmGauge.
  16566. *
  16567. * The default film gauge is 35, so that the focal length can be specified for
  16568. * a 35mm (full frame) camera.
  16569. *
  16570. * Values for focal length and film gauge must have the same unit.
  16571. */
  16572. setFocalLength: function ( focalLength ) {
  16573. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  16574. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  16575. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  16576. this.updateProjectionMatrix();
  16577. },
  16578. /**
  16579. * Calculates the focal length from the current .fov and .filmGauge.
  16580. */
  16581. getFocalLength: function () {
  16582. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  16583. return 0.5 * this.getFilmHeight() / vExtentSlope;
  16584. },
  16585. getEffectiveFOV: function () {
  16586. return _Math.RAD2DEG * 2 * Math.atan(
  16587. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  16588. },
  16589. getFilmWidth: function () {
  16590. // film not completely covered in portrait format (aspect < 1)
  16591. return this.filmGauge * Math.min( this.aspect, 1 );
  16592. },
  16593. getFilmHeight: function () {
  16594. // film not completely covered in landscape format (aspect > 1)
  16595. return this.filmGauge / Math.max( this.aspect, 1 );
  16596. },
  16597. /**
  16598. * Sets an offset in a larger frustum. This is useful for multi-window or
  16599. * multi-monitor/multi-machine setups.
  16600. *
  16601. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  16602. * the monitors are in grid like this
  16603. *
  16604. * +---+---+---+
  16605. * | A | B | C |
  16606. * +---+---+---+
  16607. * | D | E | F |
  16608. * +---+---+---+
  16609. *
  16610. * then for each monitor you would call it like this
  16611. *
  16612. * var w = 1920;
  16613. * var h = 1080;
  16614. * var fullWidth = w * 3;
  16615. * var fullHeight = h * 2;
  16616. *
  16617. * --A--
  16618. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  16619. * --B--
  16620. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  16621. * --C--
  16622. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  16623. * --D--
  16624. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  16625. * --E--
  16626. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  16627. * --F--
  16628. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  16629. *
  16630. * Note there is no reason monitors have to be the same size or in a grid.
  16631. */
  16632. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  16633. this.aspect = fullWidth / fullHeight;
  16634. if ( this.view === null ) {
  16635. this.view = {
  16636. enabled: true,
  16637. fullWidth: 1,
  16638. fullHeight: 1,
  16639. offsetX: 0,
  16640. offsetY: 0,
  16641. width: 1,
  16642. height: 1
  16643. };
  16644. }
  16645. this.view.enabled = true;
  16646. this.view.fullWidth = fullWidth;
  16647. this.view.fullHeight = fullHeight;
  16648. this.view.offsetX = x;
  16649. this.view.offsetY = y;
  16650. this.view.width = width;
  16651. this.view.height = height;
  16652. this.updateProjectionMatrix();
  16653. },
  16654. clearViewOffset: function () {
  16655. if ( this.view !== null ) {
  16656. this.view.enabled = false;
  16657. }
  16658. this.updateProjectionMatrix();
  16659. },
  16660. updateProjectionMatrix: function () {
  16661. var near = this.near,
  16662. top = near * Math.tan(
  16663. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  16664. height = 2 * top,
  16665. width = this.aspect * height,
  16666. left = - 0.5 * width,
  16667. view = this.view;
  16668. if ( this.view !== null && this.view.enabled ) {
  16669. var fullWidth = view.fullWidth,
  16670. fullHeight = view.fullHeight;
  16671. left += view.offsetX * width / fullWidth;
  16672. top -= view.offsetY * height / fullHeight;
  16673. width *= view.width / fullWidth;
  16674. height *= view.height / fullHeight;
  16675. }
  16676. var skew = this.filmOffset;
  16677. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  16678. this.projectionMatrix.makePerspective( left, left + width, top, top - height, near, this.far );
  16679. },
  16680. toJSON: function ( meta ) {
  16681. var data = Object3D.prototype.toJSON.call( this, meta );
  16682. data.object.fov = this.fov;
  16683. data.object.zoom = this.zoom;
  16684. data.object.near = this.near;
  16685. data.object.far = this.far;
  16686. data.object.focus = this.focus;
  16687. data.object.aspect = this.aspect;
  16688. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  16689. data.object.filmGauge = this.filmGauge;
  16690. data.object.filmOffset = this.filmOffset;
  16691. return data;
  16692. }
  16693. } );
  16694. /**
  16695. * @author mrdoob / http://mrdoob.com/
  16696. */
  16697. function ArrayCamera( array ) {
  16698. PerspectiveCamera.call( this );
  16699. this.cameras = array || [];
  16700. }
  16701. ArrayCamera.prototype = Object.assign( Object.create( PerspectiveCamera.prototype ), {
  16702. constructor: ArrayCamera,
  16703. isArrayCamera: true
  16704. } );
  16705. /**
  16706. * @author mrdoob / http://mrdoob.com/
  16707. */
  16708. function WebVRManager( renderer ) {
  16709. var scope = this;
  16710. var device = null;
  16711. var frameData = null;
  16712. var poseTarget = null;
  16713. var standingMatrix = new Matrix4();
  16714. var standingMatrixInverse = new Matrix4();
  16715. scope.userHeight = 1.6;
  16716. if ( typeof window !== 'undefined' && 'VRFrameData' in window ) {
  16717. frameData = new window.VRFrameData();
  16718. }
  16719. var matrixWorldInverse = new Matrix4();
  16720. var cameraL = new PerspectiveCamera();
  16721. cameraL.bounds = new Vector4( 0.0, 0.0, 0.5, 1.0 );
  16722. cameraL.layers.enable( 1 );
  16723. var cameraR = new PerspectiveCamera();
  16724. cameraR.bounds = new Vector4( 0.5, 0.0, 0.5, 1.0 );
  16725. cameraR.layers.enable( 2 );
  16726. var cameraVR = new ArrayCamera( [ cameraL, cameraR ] );
  16727. cameraVR.layers.enable( 1 );
  16728. cameraVR.layers.enable( 2 );
  16729. //
  16730. var currentSize, currentPixelRatio;
  16731. function onVRDisplayPresentChange() {
  16732. if ( device !== null && device.isPresenting ) {
  16733. var eyeParameters = device.getEyeParameters( 'left' );
  16734. var renderWidth = eyeParameters.renderWidth;
  16735. var renderHeight = eyeParameters.renderHeight;
  16736. currentPixelRatio = renderer.getPixelRatio();
  16737. currentSize = renderer.getSize();
  16738. renderer.setDrawingBufferSize( renderWidth * 2, renderHeight, 1 );
  16739. } else if ( scope.enabled ) {
  16740. renderer.setDrawingBufferSize( currentSize.width, currentSize.height, currentPixelRatio );
  16741. }
  16742. }
  16743. if ( typeof window !== 'undefined' ) {
  16744. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  16745. }
  16746. //
  16747. this.enabled = false;
  16748. this.getDevice = function () {
  16749. return device;
  16750. };
  16751. this.setDevice = function ( value ) {
  16752. if ( value !== undefined ) device = value;
  16753. };
  16754. this.setPoseTarget = function ( object ) {
  16755. if ( object !== undefined ) poseTarget = object;
  16756. };
  16757. this.getCamera = function ( camera ) {
  16758. if ( device === null ) return camera;
  16759. device.depthNear = camera.near;
  16760. device.depthFar = camera.far;
  16761. device.getFrameData( frameData );
  16762. //
  16763. var pose = frameData.pose;
  16764. var poseObject = poseTarget !== null ? poseTarget : camera;
  16765. if ( pose.position !== null ) {
  16766. poseObject.position.fromArray( pose.position );
  16767. } else {
  16768. poseObject.position.set( 0, scope.userHeight, 0 );
  16769. }
  16770. if ( pose.orientation !== null ) {
  16771. poseObject.quaternion.fromArray( pose.orientation );
  16772. }
  16773. poseObject.updateMatrixWorld();
  16774. var stageParameters = device.stageParameters;
  16775. if (stageParameters) {
  16776. standingMatrix.fromArray( stageParameters.sittingToStandingTransform );
  16777. } else {
  16778. standingMatrix.makeTranslation(0, scope.userHeight, 0);
  16779. }
  16780. standingMatrixInverse.getInverse( standingMatrix );
  16781. poseObject.matrixWorld.multiply( standingMatrix );
  16782. camera.matrixWorldInverse.multiply( standingMatrixInverse );
  16783. if ( device.isPresenting === false ) return camera;
  16784. //
  16785. cameraL.near = camera.near;
  16786. cameraR.near = camera.near;
  16787. cameraL.far = camera.far;
  16788. cameraR.far = camera.far;
  16789. cameraVR.matrixWorld.copy( camera.matrixWorld );
  16790. cameraVR.matrixWorldInverse.copy( camera.matrixWorldInverse );
  16791. cameraL.matrixWorldInverse.fromArray( frameData.leftViewMatrix );
  16792. cameraR.matrixWorldInverse.fromArray( frameData.rightViewMatrix );
  16793. cameraL.matrixWorldInverse.multiply( standingMatrixInverse );
  16794. cameraR.matrixWorldInverse.multiply( standingMatrixInverse );
  16795. var parent = poseObject.parent;
  16796. if ( parent !== null ) {
  16797. matrixWorldInverse.getInverse( parent.matrixWorld );
  16798. cameraL.matrixWorldInverse.multiply( matrixWorldInverse );
  16799. cameraR.matrixWorldInverse.multiply( matrixWorldInverse );
  16800. }
  16801. // envMap and Mirror needs camera.matrixWorld
  16802. cameraL.matrixWorld.getInverse( cameraL.matrixWorldInverse );
  16803. cameraR.matrixWorld.getInverse( cameraR.matrixWorldInverse );
  16804. cameraL.projectionMatrix.fromArray( frameData.leftProjectionMatrix );
  16805. cameraR.projectionMatrix.fromArray( frameData.rightProjectionMatrix );
  16806. // HACK @mrdoob
  16807. // https://github.com/w3c/webvr/issues/203
  16808. cameraVR.projectionMatrix.copy( cameraL.projectionMatrix );
  16809. //
  16810. var layers = device.getLayers();
  16811. if ( layers.length ) {
  16812. var layer = layers[ 0 ];
  16813. if ( layer.leftBounds !== null && layer.leftBounds.length === 4 ) {
  16814. cameraL.bounds.fromArray( layer.leftBounds );
  16815. }
  16816. if ( layer.rightBounds !== null && layer.rightBounds.length === 4 ) {
  16817. cameraR.bounds.fromArray( layer.rightBounds );
  16818. }
  16819. }
  16820. return cameraVR;
  16821. };
  16822. this.getStandingMatrix = function () {
  16823. return standingMatrix;
  16824. };
  16825. this.submitFrame = function () {
  16826. if ( device && device.isPresenting ) device.submitFrame();
  16827. };
  16828. this.dispose = function () {
  16829. if ( typeof window !== 'undefined' ) {
  16830. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange );
  16831. }
  16832. };
  16833. }
  16834. /**
  16835. * @author mrdoob / http://mrdoob.com/
  16836. */
  16837. function WebGLExtensions( gl ) {
  16838. var extensions = {};
  16839. return {
  16840. get: function ( name ) {
  16841. if ( extensions[ name ] !== undefined ) {
  16842. return extensions[ name ];
  16843. }
  16844. var extension;
  16845. switch ( name ) {
  16846. case 'WEBGL_depth_texture':
  16847. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  16848. break;
  16849. case 'EXT_texture_filter_anisotropic':
  16850. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  16851. break;
  16852. case 'WEBGL_compressed_texture_s3tc':
  16853. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  16854. break;
  16855. case 'WEBGL_compressed_texture_pvrtc':
  16856. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  16857. break;
  16858. case 'WEBGL_compressed_texture_etc1':
  16859. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  16860. break;
  16861. default:
  16862. extension = gl.getExtension( name );
  16863. }
  16864. if ( extension === null ) {
  16865. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  16866. }
  16867. extensions[ name ] = extension;
  16868. return extension;
  16869. }
  16870. };
  16871. }
  16872. /**
  16873. * @author tschw
  16874. */
  16875. function WebGLClipping() {
  16876. var scope = this,
  16877. globalState = null,
  16878. numGlobalPlanes = 0,
  16879. localClippingEnabled = false,
  16880. renderingShadows = false,
  16881. plane = new Plane(),
  16882. viewNormalMatrix = new Matrix3(),
  16883. uniform = { value: null, needsUpdate: false };
  16884. this.uniform = uniform;
  16885. this.numPlanes = 0;
  16886. this.numIntersection = 0;
  16887. this.init = function ( planes, enableLocalClipping, camera ) {
  16888. var enabled =
  16889. planes.length !== 0 ||
  16890. enableLocalClipping ||
  16891. // enable state of previous frame - the clipping code has to
  16892. // run another frame in order to reset the state:
  16893. numGlobalPlanes !== 0 ||
  16894. localClippingEnabled;
  16895. localClippingEnabled = enableLocalClipping;
  16896. globalState = projectPlanes( planes, camera, 0 );
  16897. numGlobalPlanes = planes.length;
  16898. return enabled;
  16899. };
  16900. this.beginShadows = function () {
  16901. renderingShadows = true;
  16902. projectPlanes( null );
  16903. };
  16904. this.endShadows = function () {
  16905. renderingShadows = false;
  16906. resetGlobalState();
  16907. };
  16908. this.setState = function ( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  16909. if ( ! localClippingEnabled || planes === null || planes.length === 0 || renderingShadows && ! clipShadows ) {
  16910. // there's no local clipping
  16911. if ( renderingShadows ) {
  16912. // there's no global clipping
  16913. projectPlanes( null );
  16914. } else {
  16915. resetGlobalState();
  16916. }
  16917. } else {
  16918. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  16919. lGlobal = nGlobal * 4,
  16920. dstArray = cache.clippingState || null;
  16921. uniform.value = dstArray; // ensure unique state
  16922. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  16923. for ( var i = 0; i !== lGlobal; ++ i ) {
  16924. dstArray[ i ] = globalState[ i ];
  16925. }
  16926. cache.clippingState = dstArray;
  16927. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  16928. this.numPlanes += nGlobal;
  16929. }
  16930. };
  16931. function resetGlobalState() {
  16932. if ( uniform.value !== globalState ) {
  16933. uniform.value = globalState;
  16934. uniform.needsUpdate = numGlobalPlanes > 0;
  16935. }
  16936. scope.numPlanes = numGlobalPlanes;
  16937. scope.numIntersection = 0;
  16938. }
  16939. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  16940. var nPlanes = planes !== null ? planes.length : 0,
  16941. dstArray = null;
  16942. if ( nPlanes !== 0 ) {
  16943. dstArray = uniform.value;
  16944. if ( skipTransform !== true || dstArray === null ) {
  16945. var flatSize = dstOffset + nPlanes * 4,
  16946. viewMatrix = camera.matrixWorldInverse;
  16947. viewNormalMatrix.getNormalMatrix( viewMatrix );
  16948. if ( dstArray === null || dstArray.length < flatSize ) {
  16949. dstArray = new Float32Array( flatSize );
  16950. }
  16951. for ( var i = 0, i4 = dstOffset; i !== nPlanes; ++ i, i4 += 4 ) {
  16952. plane.copy( planes[ i ] ).applyMatrix4( viewMatrix, viewNormalMatrix );
  16953. plane.normal.toArray( dstArray, i4 );
  16954. dstArray[ i4 + 3 ] = plane.constant;
  16955. }
  16956. }
  16957. uniform.value = dstArray;
  16958. uniform.needsUpdate = true;
  16959. }
  16960. scope.numPlanes = nPlanes;
  16961. return dstArray;
  16962. }
  16963. }
  16964. /**
  16965. * @author thespite / http://www.twitter.com/thespite
  16966. */
  16967. function WebGLUtils( gl, extensions ) {
  16968. function convert( p ) {
  16969. var extension;
  16970. if ( p === RepeatWrapping ) return gl.REPEAT;
  16971. if ( p === ClampToEdgeWrapping ) return gl.CLAMP_TO_EDGE;
  16972. if ( p === MirroredRepeatWrapping ) return gl.MIRRORED_REPEAT;
  16973. if ( p === NearestFilter ) return gl.NEAREST;
  16974. if ( p === NearestMipMapNearestFilter ) return gl.NEAREST_MIPMAP_NEAREST;
  16975. if ( p === NearestMipMapLinearFilter ) return gl.NEAREST_MIPMAP_LINEAR;
  16976. if ( p === LinearFilter ) return gl.LINEAR;
  16977. if ( p === LinearMipMapNearestFilter ) return gl.LINEAR_MIPMAP_NEAREST;
  16978. if ( p === LinearMipMapLinearFilter ) return gl.LINEAR_MIPMAP_LINEAR;
  16979. if ( p === UnsignedByteType ) return gl.UNSIGNED_BYTE;
  16980. if ( p === UnsignedShort4444Type ) return gl.UNSIGNED_SHORT_4_4_4_4;
  16981. if ( p === UnsignedShort5551Type ) return gl.UNSIGNED_SHORT_5_5_5_1;
  16982. if ( p === UnsignedShort565Type ) return gl.UNSIGNED_SHORT_5_6_5;
  16983. if ( p === ByteType ) return gl.BYTE;
  16984. if ( p === ShortType ) return gl.SHORT;
  16985. if ( p === UnsignedShortType ) return gl.UNSIGNED_SHORT;
  16986. if ( p === IntType ) return gl.INT;
  16987. if ( p === UnsignedIntType ) return gl.UNSIGNED_INT;
  16988. if ( p === FloatType ) return gl.FLOAT;
  16989. if ( p === HalfFloatType ) {
  16990. extension = extensions.get( 'OES_texture_half_float' );
  16991. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  16992. }
  16993. if ( p === AlphaFormat ) return gl.ALPHA;
  16994. if ( p === RGBFormat ) return gl.RGB;
  16995. if ( p === RGBAFormat ) return gl.RGBA;
  16996. if ( p === LuminanceFormat ) return gl.LUMINANCE;
  16997. if ( p === LuminanceAlphaFormat ) return gl.LUMINANCE_ALPHA;
  16998. if ( p === DepthFormat ) return gl.DEPTH_COMPONENT;
  16999. if ( p === DepthStencilFormat ) return gl.DEPTH_STENCIL;
  17000. if ( p === AddEquation ) return gl.FUNC_ADD;
  17001. if ( p === SubtractEquation ) return gl.FUNC_SUBTRACT;
  17002. if ( p === ReverseSubtractEquation ) return gl.FUNC_REVERSE_SUBTRACT;
  17003. if ( p === ZeroFactor ) return gl.ZERO;
  17004. if ( p === OneFactor ) return gl.ONE;
  17005. if ( p === SrcColorFactor ) return gl.SRC_COLOR;
  17006. if ( p === OneMinusSrcColorFactor ) return gl.ONE_MINUS_SRC_COLOR;
  17007. if ( p === SrcAlphaFactor ) return gl.SRC_ALPHA;
  17008. if ( p === OneMinusSrcAlphaFactor ) return gl.ONE_MINUS_SRC_ALPHA;
  17009. if ( p === DstAlphaFactor ) return gl.DST_ALPHA;
  17010. if ( p === OneMinusDstAlphaFactor ) return gl.ONE_MINUS_DST_ALPHA;
  17011. if ( p === DstColorFactor ) return gl.DST_COLOR;
  17012. if ( p === OneMinusDstColorFactor ) return gl.ONE_MINUS_DST_COLOR;
  17013. if ( p === SrcAlphaSaturateFactor ) return gl.SRC_ALPHA_SATURATE;
  17014. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17015. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  17016. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17017. if ( extension !== null ) {
  17018. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  17019. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17020. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17021. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17022. }
  17023. }
  17024. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  17025. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  17026. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17027. if ( extension !== null ) {
  17028. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  17029. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  17030. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  17031. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  17032. }
  17033. }
  17034. if ( p === RGB_ETC1_Format ) {
  17035. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  17036. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  17037. }
  17038. if ( p === MinEquation || p === MaxEquation ) {
  17039. extension = extensions.get( 'EXT_blend_minmax' );
  17040. if ( extension !== null ) {
  17041. if ( p === MinEquation ) return extension.MIN_EXT;
  17042. if ( p === MaxEquation ) return extension.MAX_EXT;
  17043. }
  17044. }
  17045. if ( p === UnsignedInt248Type ) {
  17046. extension = extensions.get( 'WEBGL_depth_texture' );
  17047. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  17048. }
  17049. return 0;
  17050. }
  17051. return { convert: convert };
  17052. }
  17053. /**
  17054. * @author supereggbert / http://www.paulbrunt.co.uk/
  17055. * @author mrdoob / http://mrdoob.com/
  17056. * @author alteredq / http://alteredqualia.com/
  17057. * @author szimek / https://github.com/szimek/
  17058. * @author tschw
  17059. */
  17060. function WebGLRenderer( parameters ) {
  17061. console.log( 'THREE.WebGLRenderer', REVISION );
  17062. parameters = parameters || {};
  17063. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  17064. _context = parameters.context !== undefined ? parameters.context : null,
  17065. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  17066. _depth = parameters.depth !== undefined ? parameters.depth : true,
  17067. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  17068. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  17069. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  17070. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  17071. _powerPreference = parameters.powerPreference !== undefined ? parameters.powerPreference : 'default';
  17072. var lightsArray = [];
  17073. var shadowsArray = [];
  17074. var currentRenderList = null;
  17075. var spritesArray = [];
  17076. var flaresArray = [];
  17077. // public properties
  17078. this.domElement = _canvas;
  17079. this.context = null;
  17080. // clearing
  17081. this.autoClear = true;
  17082. this.autoClearColor = true;
  17083. this.autoClearDepth = true;
  17084. this.autoClearStencil = true;
  17085. // scene graph
  17086. this.sortObjects = true;
  17087. // user-defined clipping
  17088. this.clippingPlanes = [];
  17089. this.localClippingEnabled = false;
  17090. // physically based shading
  17091. this.gammaFactor = 2.0; // for backwards compatibility
  17092. this.gammaInput = false;
  17093. this.gammaOutput = false;
  17094. // physical lights
  17095. this.physicallyCorrectLights = false;
  17096. // tone mapping
  17097. this.toneMapping = LinearToneMapping;
  17098. this.toneMappingExposure = 1.0;
  17099. this.toneMappingWhitePoint = 1.0;
  17100. // morphs
  17101. this.maxMorphTargets = 8;
  17102. this.maxMorphNormals = 4;
  17103. // internal properties
  17104. var _this = this,
  17105. _isContextLost = false,
  17106. // internal state cache
  17107. _currentRenderTarget = null,
  17108. _currentFramebuffer = null,
  17109. _currentMaterialId = - 1,
  17110. _currentGeometryProgram = '',
  17111. _currentCamera = null,
  17112. _currentArrayCamera = null,
  17113. _currentViewport = new Vector4(),
  17114. _currentScissor = new Vector4(),
  17115. _currentScissorTest = null,
  17116. //
  17117. _usedTextureUnits = 0,
  17118. //
  17119. _width = _canvas.width,
  17120. _height = _canvas.height,
  17121. _pixelRatio = 1,
  17122. _viewport = new Vector4( 0, 0, _width, _height ),
  17123. _scissor = new Vector4( 0, 0, _width, _height ),
  17124. _scissorTest = false,
  17125. // frustum
  17126. _frustum = new Frustum(),
  17127. // clipping
  17128. _clipping = new WebGLClipping(),
  17129. _clippingEnabled = false,
  17130. _localClippingEnabled = false,
  17131. // camera matrices cache
  17132. _projScreenMatrix = new Matrix4(),
  17133. _vector3 = new Vector3(),
  17134. // info
  17135. _infoMemory = {
  17136. geometries: 0,
  17137. textures: 0
  17138. },
  17139. _infoRender = {
  17140. frame: 0,
  17141. calls: 0,
  17142. vertices: 0,
  17143. faces: 0,
  17144. points: 0
  17145. };
  17146. this.info = {
  17147. render: _infoRender,
  17148. memory: _infoMemory,
  17149. programs: null
  17150. };
  17151. function getTargetPixelRatio() {
  17152. return _currentRenderTarget === null ? _pixelRatio : 1;
  17153. }
  17154. // initialize
  17155. var _gl;
  17156. try {
  17157. var contextAttributes = {
  17158. alpha: _alpha,
  17159. depth: _depth,
  17160. stencil: _stencil,
  17161. antialias: _antialias,
  17162. premultipliedAlpha: _premultipliedAlpha,
  17163. preserveDrawingBuffer: _preserveDrawingBuffer,
  17164. powerPreference: _powerPreference
  17165. };
  17166. // event listeners must be registered before WebGL context is created, see #12753
  17167. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  17168. _canvas.addEventListener( 'webglcontextrestored', onContextRestore, false );
  17169. _gl = _context || _canvas.getContext( 'webgl', contextAttributes ) || _canvas.getContext( 'experimental-webgl', contextAttributes );
  17170. if ( _gl === null ) {
  17171. if ( _canvas.getContext( 'webgl' ) !== null ) {
  17172. throw new Error( 'Error creating WebGL context with your selected attributes.' );
  17173. } else {
  17174. throw new Error( 'Error creating WebGL context.' );
  17175. }
  17176. }
  17177. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  17178. if ( _gl.getShaderPrecisionFormat === undefined ) {
  17179. _gl.getShaderPrecisionFormat = function () {
  17180. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  17181. };
  17182. }
  17183. } catch ( error ) {
  17184. console.error( 'THREE.WebGLRenderer: ' + error.message );
  17185. }
  17186. var extensions, capabilities, state;
  17187. var properties, textures, attributes, geometries, objects, lights;
  17188. var programCache, renderLists;
  17189. var background, morphtargets, bufferRenderer, indexedBufferRenderer;
  17190. var flareRenderer, spriteRenderer;
  17191. var utils;
  17192. function initGLContext() {
  17193. extensions = new WebGLExtensions( _gl );
  17194. extensions.get( 'WEBGL_depth_texture' );
  17195. extensions.get( 'OES_texture_float' );
  17196. extensions.get( 'OES_texture_float_linear' );
  17197. extensions.get( 'OES_texture_half_float' );
  17198. extensions.get( 'OES_texture_half_float_linear' );
  17199. extensions.get( 'OES_standard_derivatives' );
  17200. extensions.get( 'OES_element_index_uint' );
  17201. extensions.get( 'ANGLE_instanced_arrays' );
  17202. utils = new WebGLUtils( _gl, extensions );
  17203. capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  17204. state = new WebGLState( _gl, extensions, utils );
  17205. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17206. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17207. properties = new WebGLProperties();
  17208. textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, utils, _infoMemory );
  17209. attributes = new WebGLAttributes( _gl );
  17210. geometries = new WebGLGeometries( _gl, attributes, _infoMemory );
  17211. objects = new WebGLObjects( geometries, _infoRender );
  17212. morphtargets = new WebGLMorphtargets( _gl );
  17213. programCache = new WebGLPrograms( _this, extensions, capabilities );
  17214. lights = new WebGLLights();
  17215. renderLists = new WebGLRenderLists();
  17216. background = new WebGLBackground( _this, state, geometries, _premultipliedAlpha );
  17217. bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  17218. indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  17219. flareRenderer = new WebGLFlareRenderer( _this, _gl, state, textures, capabilities );
  17220. spriteRenderer = new WebGLSpriteRenderer( _this, _gl, state, textures, capabilities );
  17221. _this.info.programs = programCache.programs;
  17222. _this.context = _gl;
  17223. _this.capabilities = capabilities;
  17224. _this.extensions = extensions;
  17225. _this.properties = properties;
  17226. _this.renderLists = renderLists;
  17227. _this.state = state;
  17228. }
  17229. initGLContext();
  17230. // vr
  17231. var vr = new WebVRManager( _this );
  17232. this.vr = vr;
  17233. // shadow map
  17234. var shadowMap = new WebGLShadowMap( _this, objects, capabilities.maxTextureSize );
  17235. this.shadowMap = shadowMap;
  17236. // API
  17237. this.getContext = function () {
  17238. return _gl;
  17239. };
  17240. this.getContextAttributes = function () {
  17241. return _gl.getContextAttributes();
  17242. };
  17243. this.forceContextLoss = function () {
  17244. var extension = extensions.get( 'WEBGL_lose_context' );
  17245. if ( extension ) extension.loseContext();
  17246. };
  17247. this.forceContextRestore = function () {
  17248. var extension = extensions.get( 'WEBGL_lose_context' );
  17249. if ( extension ) extension.restoreContext();
  17250. };
  17251. this.getPixelRatio = function () {
  17252. return _pixelRatio;
  17253. };
  17254. this.setPixelRatio = function ( value ) {
  17255. if ( value === undefined ) return;
  17256. _pixelRatio = value;
  17257. this.setSize( _width, _height, false );
  17258. };
  17259. this.getSize = function () {
  17260. return {
  17261. width: _width,
  17262. height: _height
  17263. };
  17264. };
  17265. this.setSize = function ( width, height, updateStyle ) {
  17266. var device = vr.getDevice();
  17267. if ( device && device.isPresenting ) {
  17268. console.warn( 'THREE.WebGLRenderer: Can\'t change size while VR device is presenting.' );
  17269. return;
  17270. }
  17271. _width = width;
  17272. _height = height;
  17273. _canvas.width = width * _pixelRatio;
  17274. _canvas.height = height * _pixelRatio;
  17275. if ( updateStyle !== false ) {
  17276. _canvas.style.width = width + 'px';
  17277. _canvas.style.height = height + 'px';
  17278. }
  17279. this.setViewport( 0, 0, width, height );
  17280. };
  17281. this.getDrawingBufferSize = function () {
  17282. return {
  17283. width: _width * _pixelRatio,
  17284. height: _height * _pixelRatio
  17285. };
  17286. };
  17287. this.setDrawingBufferSize = function ( width, height, pixelRatio ) {
  17288. _width = width;
  17289. _height = height;
  17290. _pixelRatio = pixelRatio;
  17291. _canvas.width = width * pixelRatio;
  17292. _canvas.height = height * pixelRatio;
  17293. this.setViewport( 0, 0, width, height );
  17294. };
  17295. this.setViewport = function ( x, y, width, height ) {
  17296. _viewport.set( x, _height - y - height, width, height );
  17297. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  17298. };
  17299. this.setScissor = function ( x, y, width, height ) {
  17300. _scissor.set( x, _height - y - height, width, height );
  17301. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  17302. };
  17303. this.setScissorTest = function ( boolean ) {
  17304. state.setScissorTest( _scissorTest = boolean );
  17305. };
  17306. // Clearing
  17307. this.getClearColor = function () {
  17308. return background.getClearColor();
  17309. };
  17310. this.setClearColor = function () {
  17311. background.setClearColor.apply( background, arguments );
  17312. };
  17313. this.getClearAlpha = function () {
  17314. return background.getClearAlpha();
  17315. };
  17316. this.setClearAlpha = function () {
  17317. background.setClearAlpha.apply( background, arguments );
  17318. };
  17319. this.clear = function ( color, depth, stencil ) {
  17320. var bits = 0;
  17321. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  17322. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  17323. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  17324. _gl.clear( bits );
  17325. };
  17326. this.clearColor = function () {
  17327. this.clear( true, false, false );
  17328. };
  17329. this.clearDepth = function () {
  17330. this.clear( false, true, false );
  17331. };
  17332. this.clearStencil = function () {
  17333. this.clear( false, false, true );
  17334. };
  17335. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  17336. this.setRenderTarget( renderTarget );
  17337. this.clear( color, depth, stencil );
  17338. };
  17339. //
  17340. this.dispose = function () {
  17341. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  17342. _canvas.removeEventListener( 'webglcontextrestored', onContextRestore, false );
  17343. renderLists.dispose();
  17344. vr.dispose();
  17345. };
  17346. // Events
  17347. function onContextLost( event ) {
  17348. event.preventDefault();
  17349. console.log( 'THREE.WebGLRenderer: Context Lost.' );
  17350. _isContextLost = true;
  17351. }
  17352. function onContextRestore( /* event */ ) {
  17353. console.log( 'THREE.WebGLRenderer: Context Restored.' );
  17354. _isContextLost = false;
  17355. initGLContext();
  17356. }
  17357. function onMaterialDispose( event ) {
  17358. var material = event.target;
  17359. material.removeEventListener( 'dispose', onMaterialDispose );
  17360. deallocateMaterial( material );
  17361. }
  17362. // Buffer deallocation
  17363. function deallocateMaterial( material ) {
  17364. releaseMaterialProgramReference( material );
  17365. properties.remove( material );
  17366. }
  17367. function releaseMaterialProgramReference( material ) {
  17368. var programInfo = properties.get( material ).program;
  17369. material.program = undefined;
  17370. if ( programInfo !== undefined ) {
  17371. programCache.releaseProgram( programInfo );
  17372. }
  17373. }
  17374. // Buffer rendering
  17375. function renderObjectImmediate( object, program, material ) {
  17376. object.render( function ( object ) {
  17377. _this.renderBufferImmediate( object, program, material );
  17378. } );
  17379. }
  17380. this.renderBufferImmediate = function ( object, program, material ) {
  17381. state.initAttributes();
  17382. var buffers = properties.get( object );
  17383. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  17384. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  17385. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  17386. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  17387. var programAttributes = program.getAttributes();
  17388. if ( object.hasPositions ) {
  17389. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  17390. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  17391. state.enableAttribute( programAttributes.position );
  17392. _gl.vertexAttribPointer( programAttributes.position, 3, _gl.FLOAT, false, 0, 0 );
  17393. }
  17394. if ( object.hasNormals ) {
  17395. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  17396. if ( ! material.isMeshPhongMaterial &&
  17397. ! material.isMeshStandardMaterial &&
  17398. ! material.isMeshNormalMaterial &&
  17399. material.flatShading === true ) {
  17400. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  17401. var array = object.normalArray;
  17402. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  17403. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  17404. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  17405. array[ i + 0 ] = nx;
  17406. array[ i + 1 ] = ny;
  17407. array[ i + 2 ] = nz;
  17408. array[ i + 3 ] = nx;
  17409. array[ i + 4 ] = ny;
  17410. array[ i + 5 ] = nz;
  17411. array[ i + 6 ] = nx;
  17412. array[ i + 7 ] = ny;
  17413. array[ i + 8 ] = nz;
  17414. }
  17415. }
  17416. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  17417. state.enableAttribute( programAttributes.normal );
  17418. _gl.vertexAttribPointer( programAttributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  17419. }
  17420. if ( object.hasUvs && material.map ) {
  17421. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  17422. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  17423. state.enableAttribute( programAttributes.uv );
  17424. _gl.vertexAttribPointer( programAttributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  17425. }
  17426. if ( object.hasColors && material.vertexColors !== NoColors ) {
  17427. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  17428. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  17429. state.enableAttribute( programAttributes.color );
  17430. _gl.vertexAttribPointer( programAttributes.color, 3, _gl.FLOAT, false, 0, 0 );
  17431. }
  17432. state.disableUnusedAttributes();
  17433. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  17434. object.count = 0;
  17435. };
  17436. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  17437. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17438. state.setMaterial( material, frontFaceCW );
  17439. var program = setProgram( camera, fog, material, object );
  17440. var geometryProgram = geometry.id + '_' + program.id + '_' + ( material.wireframe === true );
  17441. var updateBuffers = false;
  17442. if ( geometryProgram !== _currentGeometryProgram ) {
  17443. _currentGeometryProgram = geometryProgram;
  17444. updateBuffers = true;
  17445. }
  17446. if ( object.morphTargetInfluences ) {
  17447. morphtargets.update( object, geometry, material, program );
  17448. updateBuffers = true;
  17449. }
  17450. //
  17451. var index = geometry.index;
  17452. var position = geometry.attributes.position;
  17453. var rangeFactor = 1;
  17454. if ( material.wireframe === true ) {
  17455. index = geometries.getWireframeAttribute( geometry );
  17456. rangeFactor = 2;
  17457. }
  17458. var attribute;
  17459. var renderer = bufferRenderer;
  17460. if ( index !== null ) {
  17461. attribute = attributes.get( index );
  17462. renderer = indexedBufferRenderer;
  17463. renderer.setIndex( attribute );
  17464. }
  17465. if ( updateBuffers ) {
  17466. setupVertexAttributes( material, program, geometry );
  17467. if ( index !== null ) {
  17468. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attribute.buffer );
  17469. }
  17470. }
  17471. //
  17472. var dataCount = 0;
  17473. if ( index !== null ) {
  17474. dataCount = index.count;
  17475. } else if ( position !== undefined ) {
  17476. dataCount = position.count;
  17477. }
  17478. var rangeStart = geometry.drawRange.start * rangeFactor;
  17479. var rangeCount = geometry.drawRange.count * rangeFactor;
  17480. var groupStart = group !== null ? group.start * rangeFactor : 0;
  17481. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  17482. var drawStart = Math.max( rangeStart, groupStart );
  17483. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  17484. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  17485. if ( drawCount === 0 ) return;
  17486. //
  17487. if ( object.isMesh ) {
  17488. if ( material.wireframe === true ) {
  17489. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  17490. renderer.setMode( _gl.LINES );
  17491. } else {
  17492. switch ( object.drawMode ) {
  17493. case TrianglesDrawMode:
  17494. renderer.setMode( _gl.TRIANGLES );
  17495. break;
  17496. case TriangleStripDrawMode:
  17497. renderer.setMode( _gl.TRIANGLE_STRIP );
  17498. break;
  17499. case TriangleFanDrawMode:
  17500. renderer.setMode( _gl.TRIANGLE_FAN );
  17501. break;
  17502. }
  17503. }
  17504. } else if ( object.isLine ) {
  17505. var lineWidth = material.linewidth;
  17506. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  17507. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  17508. if ( object.isLineSegments ) {
  17509. renderer.setMode( _gl.LINES );
  17510. } else if ( object.isLineLoop ) {
  17511. renderer.setMode( _gl.LINE_LOOP );
  17512. } else {
  17513. renderer.setMode( _gl.LINE_STRIP );
  17514. }
  17515. } else if ( object.isPoints ) {
  17516. renderer.setMode( _gl.POINTS );
  17517. }
  17518. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17519. if ( geometry.maxInstancedCount > 0 ) {
  17520. renderer.renderInstances( geometry, drawStart, drawCount );
  17521. }
  17522. } else {
  17523. renderer.render( drawStart, drawCount );
  17524. }
  17525. };
  17526. function setupVertexAttributes( material, program, geometry, startIndex ) {
  17527. if ( geometry && geometry.isInstancedBufferGeometry ) {
  17528. if ( extensions.get( 'ANGLE_instanced_arrays' ) === null ) {
  17529. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  17530. return;
  17531. }
  17532. }
  17533. if ( startIndex === undefined ) startIndex = 0;
  17534. state.initAttributes();
  17535. var geometryAttributes = geometry.attributes;
  17536. var programAttributes = program.getAttributes();
  17537. var materialDefaultAttributeValues = material.defaultAttributeValues;
  17538. for ( var name in programAttributes ) {
  17539. var programAttribute = programAttributes[ name ];
  17540. if ( programAttribute >= 0 ) {
  17541. var geometryAttribute = geometryAttributes[ name ];
  17542. if ( geometryAttribute !== undefined ) {
  17543. var normalized = geometryAttribute.normalized;
  17544. var size = geometryAttribute.itemSize;
  17545. var attribute = attributes.get( geometryAttribute );
  17546. // TODO Attribute may not be available on context restore
  17547. if ( attribute === undefined ) continue;
  17548. var buffer = attribute.buffer;
  17549. var type = attribute.type;
  17550. var bytesPerElement = attribute.bytesPerElement;
  17551. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  17552. var data = geometryAttribute.data;
  17553. var stride = data.stride;
  17554. var offset = geometryAttribute.offset;
  17555. if ( data && data.isInstancedInterleavedBuffer ) {
  17556. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute );
  17557. if ( geometry.maxInstancedCount === undefined ) {
  17558. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  17559. }
  17560. } else {
  17561. state.enableAttribute( programAttribute );
  17562. }
  17563. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17564. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  17565. } else {
  17566. if ( geometryAttribute.isInstancedBufferAttribute ) {
  17567. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute );
  17568. if ( geometry.maxInstancedCount === undefined ) {
  17569. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  17570. }
  17571. } else {
  17572. state.enableAttribute( programAttribute );
  17573. }
  17574. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  17575. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  17576. }
  17577. } else if ( materialDefaultAttributeValues !== undefined ) {
  17578. var value = materialDefaultAttributeValues[ name ];
  17579. if ( value !== undefined ) {
  17580. switch ( value.length ) {
  17581. case 2:
  17582. _gl.vertexAttrib2fv( programAttribute, value );
  17583. break;
  17584. case 3:
  17585. _gl.vertexAttrib3fv( programAttribute, value );
  17586. break;
  17587. case 4:
  17588. _gl.vertexAttrib4fv( programAttribute, value );
  17589. break;
  17590. default:
  17591. _gl.vertexAttrib1fv( programAttribute, value );
  17592. }
  17593. }
  17594. }
  17595. }
  17596. }
  17597. state.disableUnusedAttributes();
  17598. }
  17599. // Compile
  17600. this.compile = function ( scene, camera ) {
  17601. lightsArray.length = 0;
  17602. shadowsArray.length = 0;
  17603. scene.traverse( function ( object ) {
  17604. if ( object.isLight ) {
  17605. lightsArray.push( object );
  17606. if ( object.castShadow ) {
  17607. shadowsArray.push( object );
  17608. }
  17609. }
  17610. } );
  17611. lights.setup( lightsArray, shadowsArray, camera );
  17612. scene.traverse( function ( object ) {
  17613. if ( object.material ) {
  17614. if ( Array.isArray( object.material ) ) {
  17615. for ( var i = 0; i < object.material.length; i ++ ) {
  17616. initMaterial( object.material[ i ], scene.fog, object );
  17617. }
  17618. } else {
  17619. initMaterial( object.material, scene.fog, object );
  17620. }
  17621. }
  17622. } );
  17623. };
  17624. // Animation Loop
  17625. var isAnimating = false;
  17626. var onAnimationFrame = null;
  17627. function start() {
  17628. if ( isAnimating ) return;
  17629. var device = vr.getDevice();
  17630. if ( device && device.isPresenting ) {
  17631. device.requestAnimationFrame( loop );
  17632. } else {
  17633. window.requestAnimationFrame( loop );
  17634. }
  17635. isAnimating = true;
  17636. }
  17637. function loop( time ) {
  17638. if ( onAnimationFrame !== null ) onAnimationFrame( time );
  17639. var device = vr.getDevice();
  17640. if ( device && device.isPresenting ) {
  17641. device.requestAnimationFrame( loop );
  17642. } else {
  17643. window.requestAnimationFrame( loop );
  17644. }
  17645. }
  17646. this.animate = function ( callback ) {
  17647. onAnimationFrame = callback;
  17648. start();
  17649. };
  17650. // Rendering
  17651. this.render = function ( scene, camera, renderTarget, forceClear ) {
  17652. if ( ! ( camera && camera.isCamera ) ) {
  17653. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  17654. return;
  17655. }
  17656. if ( _isContextLost ) return;
  17657. // reset caching for this frame
  17658. _currentGeometryProgram = '';
  17659. _currentMaterialId = - 1;
  17660. _currentCamera = null;
  17661. // update scene graph
  17662. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  17663. // update camera matrices and frustum
  17664. if ( camera.parent === null ) camera.updateMatrixWorld();
  17665. if ( vr.enabled ) {
  17666. camera = vr.getCamera( camera );
  17667. }
  17668. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  17669. _frustum.setFromMatrix( _projScreenMatrix );
  17670. lightsArray.length = 0;
  17671. shadowsArray.length = 0;
  17672. spritesArray.length = 0;
  17673. flaresArray.length = 0;
  17674. _localClippingEnabled = this.localClippingEnabled;
  17675. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  17676. currentRenderList = renderLists.get( scene, camera );
  17677. currentRenderList.init();
  17678. projectObject( scene, camera, _this.sortObjects );
  17679. if ( _this.sortObjects === true ) {
  17680. currentRenderList.sort();
  17681. }
  17682. //
  17683. textures.updateVideoTextures();
  17684. //
  17685. if ( _clippingEnabled ) _clipping.beginShadows();
  17686. shadowMap.render( shadowsArray, scene, camera );
  17687. lights.setup( lightsArray, shadowsArray, camera );
  17688. if ( _clippingEnabled ) _clipping.endShadows();
  17689. //
  17690. _infoRender.frame ++;
  17691. _infoRender.calls = 0;
  17692. _infoRender.vertices = 0;
  17693. _infoRender.faces = 0;
  17694. _infoRender.points = 0;
  17695. if ( renderTarget === undefined ) {
  17696. renderTarget = null;
  17697. }
  17698. this.setRenderTarget( renderTarget );
  17699. //
  17700. background.render( currentRenderList, scene, camera, forceClear );
  17701. // render scene
  17702. var opaqueObjects = currentRenderList.opaque;
  17703. var transparentObjects = currentRenderList.transparent;
  17704. if ( scene.overrideMaterial ) {
  17705. var overrideMaterial = scene.overrideMaterial;
  17706. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  17707. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera, overrideMaterial );
  17708. } else {
  17709. // opaque pass (front-to-back order)
  17710. if ( opaqueObjects.length ) renderObjects( opaqueObjects, scene, camera );
  17711. // transparent pass (back-to-front order)
  17712. if ( transparentObjects.length ) renderObjects( transparentObjects, scene, camera );
  17713. }
  17714. // custom renderers
  17715. spriteRenderer.render( spritesArray, scene, camera );
  17716. flareRenderer.render( flaresArray, scene, camera, _currentViewport );
  17717. // Generate mipmap if we're using any kind of mipmap filtering
  17718. if ( renderTarget ) {
  17719. textures.updateRenderTargetMipmap( renderTarget );
  17720. }
  17721. // Ensure depth buffer writing is enabled so it can be cleared on next render
  17722. state.buffers.depth.setTest( true );
  17723. state.buffers.depth.setMask( true );
  17724. state.buffers.color.setMask( true );
  17725. state.setPolygonOffset( false );
  17726. if ( vr.enabled ) {
  17727. vr.submitFrame();
  17728. }
  17729. // _gl.finish();
  17730. };
  17731. /*
  17732. // TODO Duplicated code (Frustum)
  17733. var _sphere = new Sphere();
  17734. function isObjectViewable( object ) {
  17735. var geometry = object.geometry;
  17736. if ( geometry.boundingSphere === null )
  17737. geometry.computeBoundingSphere();
  17738. _sphere.copy( geometry.boundingSphere ).
  17739. applyMatrix4( object.matrixWorld );
  17740. return isSphereViewable( _sphere );
  17741. }
  17742. function isSpriteViewable( sprite ) {
  17743. _sphere.center.set( 0, 0, 0 );
  17744. _sphere.radius = 0.7071067811865476;
  17745. _sphere.applyMatrix4( sprite.matrixWorld );
  17746. return isSphereViewable( _sphere );
  17747. }
  17748. function isSphereViewable( sphere ) {
  17749. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  17750. var numPlanes = _clipping.numPlanes;
  17751. if ( numPlanes === 0 ) return true;
  17752. var planes = _this.clippingPlanes,
  17753. center = sphere.center,
  17754. negRad = - sphere.radius,
  17755. i = 0;
  17756. do {
  17757. // out when deeper than radius in the negative halfspace
  17758. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  17759. } while ( ++ i !== numPlanes );
  17760. return true;
  17761. }
  17762. */
  17763. function projectObject( object, camera, sortObjects ) {
  17764. if ( object.visible === false ) return;
  17765. var visible = object.layers.test( camera.layers );
  17766. if ( visible ) {
  17767. if ( object.isLight ) {
  17768. lightsArray.push( object );
  17769. if ( object.castShadow ) {
  17770. shadowsArray.push( object );
  17771. }
  17772. } else if ( object.isSprite ) {
  17773. if ( ! object.frustumCulled || _frustum.intersectsSprite( object ) ) {
  17774. spritesArray.push( object );
  17775. }
  17776. } else if ( object.isLensFlare ) {
  17777. flaresArray.push( object );
  17778. } else if ( object.isImmediateRenderObject ) {
  17779. if ( sortObjects ) {
  17780. _vector3.setFromMatrixPosition( object.matrixWorld )
  17781. .applyMatrix4( _projScreenMatrix );
  17782. }
  17783. currentRenderList.push( object, null, object.material, _vector3.z, null );
  17784. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  17785. if ( object.isSkinnedMesh ) {
  17786. object.skeleton.update();
  17787. }
  17788. if ( ! object.frustumCulled || _frustum.intersectsObject( object ) ) {
  17789. if ( sortObjects ) {
  17790. _vector3.setFromMatrixPosition( object.matrixWorld )
  17791. .applyMatrix4( _projScreenMatrix );
  17792. }
  17793. var geometry = objects.update( object );
  17794. var material = object.material;
  17795. if ( Array.isArray( material ) ) {
  17796. var groups = geometry.groups;
  17797. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  17798. var group = groups[ i ];
  17799. var groupMaterial = material[ group.materialIndex ];
  17800. if ( groupMaterial && groupMaterial.visible ) {
  17801. currentRenderList.push( object, geometry, groupMaterial, _vector3.z, group );
  17802. }
  17803. }
  17804. } else if ( material.visible ) {
  17805. currentRenderList.push( object, geometry, material, _vector3.z, null );
  17806. }
  17807. }
  17808. }
  17809. }
  17810. var children = object.children;
  17811. for ( var i = 0, l = children.length; i < l; i ++ ) {
  17812. projectObject( children[ i ], camera, sortObjects );
  17813. }
  17814. }
  17815. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  17816. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  17817. var renderItem = renderList[ i ];
  17818. var object = renderItem.object;
  17819. var geometry = renderItem.geometry;
  17820. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  17821. var group = renderItem.group;
  17822. if ( camera.isArrayCamera ) {
  17823. _currentArrayCamera = camera;
  17824. var cameras = camera.cameras;
  17825. for ( var j = 0, jl = cameras.length; j < jl; j ++ ) {
  17826. var camera2 = cameras[ j ];
  17827. if ( object.layers.test( camera2.layers ) ) {
  17828. var bounds = camera2.bounds;
  17829. var x = bounds.x * _width;
  17830. var y = bounds.y * _height;
  17831. var width = bounds.z * _width;
  17832. var height = bounds.w * _height;
  17833. state.viewport( _currentViewport.set( x, y, width, height ).multiplyScalar( _pixelRatio ) );
  17834. renderObject( object, scene, camera2, geometry, material, group );
  17835. }
  17836. }
  17837. } else {
  17838. _currentArrayCamera = null;
  17839. renderObject( object, scene, camera, geometry, material, group );
  17840. }
  17841. }
  17842. }
  17843. function renderObject( object, scene, camera, geometry, material, group ) {
  17844. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  17845. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  17846. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  17847. if ( object.isImmediateRenderObject ) {
  17848. var frontFaceCW = ( object.isMesh && object.matrixWorld.determinant() < 0 );
  17849. state.setMaterial( material, frontFaceCW );
  17850. var program = setProgram( camera, scene.fog, material, object );
  17851. _currentGeometryProgram = '';
  17852. renderObjectImmediate( object, program, material );
  17853. } else {
  17854. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  17855. }
  17856. object.onAfterRender( _this, scene, camera, geometry, material, group );
  17857. }
  17858. function initMaterial( material, fog, object ) {
  17859. var materialProperties = properties.get( material );
  17860. var parameters = programCache.getParameters(
  17861. material, lights.state, shadowsArray, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  17862. var code = programCache.getProgramCode( material, parameters );
  17863. var program = materialProperties.program;
  17864. var programChange = true;
  17865. if ( program === undefined ) {
  17866. // new material
  17867. material.addEventListener( 'dispose', onMaterialDispose );
  17868. } else if ( program.code !== code ) {
  17869. // changed glsl or parameters
  17870. releaseMaterialProgramReference( material );
  17871. } else if ( parameters.shaderID !== undefined ) {
  17872. // same glsl and uniform list
  17873. return;
  17874. } else {
  17875. // only rebuild uniform list
  17876. programChange = false;
  17877. }
  17878. if ( programChange ) {
  17879. if ( parameters.shaderID ) {
  17880. var shader = ShaderLib[ parameters.shaderID ];
  17881. materialProperties.shader = {
  17882. name: material.type,
  17883. uniforms: UniformsUtils.clone( shader.uniforms ),
  17884. vertexShader: shader.vertexShader,
  17885. fragmentShader: shader.fragmentShader
  17886. };
  17887. } else {
  17888. materialProperties.shader = {
  17889. name: material.type,
  17890. uniforms: material.uniforms,
  17891. vertexShader: material.vertexShader,
  17892. fragmentShader: material.fragmentShader
  17893. };
  17894. }
  17895. material.onBeforeCompile( materialProperties.shader );
  17896. program = programCache.acquireProgram( material, materialProperties.shader, parameters, code );
  17897. materialProperties.program = program;
  17898. material.program = program;
  17899. }
  17900. var programAttributes = program.getAttributes();
  17901. if ( material.morphTargets ) {
  17902. material.numSupportedMorphTargets = 0;
  17903. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  17904. if ( programAttributes[ 'morphTarget' + i ] >= 0 ) {
  17905. material.numSupportedMorphTargets ++;
  17906. }
  17907. }
  17908. }
  17909. if ( material.morphNormals ) {
  17910. material.numSupportedMorphNormals = 0;
  17911. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  17912. if ( programAttributes[ 'morphNormal' + i ] >= 0 ) {
  17913. material.numSupportedMorphNormals ++;
  17914. }
  17915. }
  17916. }
  17917. var uniforms = materialProperties.shader.uniforms;
  17918. if ( ! material.isShaderMaterial &&
  17919. ! material.isRawShaderMaterial ||
  17920. material.clipping === true ) {
  17921. materialProperties.numClippingPlanes = _clipping.numPlanes;
  17922. materialProperties.numIntersection = _clipping.numIntersection;
  17923. uniforms.clippingPlanes = _clipping.uniform;
  17924. }
  17925. materialProperties.fog = fog;
  17926. // store the light setup it was created for
  17927. materialProperties.lightsHash = lights.state.hash;
  17928. if ( material.lights ) {
  17929. // wire up the material to this renderer's lighting state
  17930. uniforms.ambientLightColor.value = lights.state.ambient;
  17931. uniforms.directionalLights.value = lights.state.directional;
  17932. uniforms.spotLights.value = lights.state.spot;
  17933. uniforms.rectAreaLights.value = lights.state.rectArea;
  17934. uniforms.pointLights.value = lights.state.point;
  17935. uniforms.hemisphereLights.value = lights.state.hemi;
  17936. uniforms.directionalShadowMap.value = lights.state.directionalShadowMap;
  17937. uniforms.directionalShadowMatrix.value = lights.state.directionalShadowMatrix;
  17938. uniforms.spotShadowMap.value = lights.state.spotShadowMap;
  17939. uniforms.spotShadowMatrix.value = lights.state.spotShadowMatrix;
  17940. uniforms.pointShadowMap.value = lights.state.pointShadowMap;
  17941. uniforms.pointShadowMatrix.value = lights.state.pointShadowMatrix;
  17942. // TODO (abelnation): add area lights shadow info to uniforms
  17943. }
  17944. var progUniforms = materialProperties.program.getUniforms(),
  17945. uniformsList =
  17946. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  17947. materialProperties.uniformsList = uniformsList;
  17948. }
  17949. function setProgram( camera, fog, material, object ) {
  17950. _usedTextureUnits = 0;
  17951. var materialProperties = properties.get( material );
  17952. if ( _clippingEnabled ) {
  17953. if ( _localClippingEnabled || camera !== _currentCamera ) {
  17954. var useCache =
  17955. camera === _currentCamera &&
  17956. material.id === _currentMaterialId;
  17957. // we might want to call this function with some ClippingGroup
  17958. // object instead of the material, once it becomes feasible
  17959. // (#8465, #8379)
  17960. _clipping.setState(
  17961. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  17962. camera, materialProperties, useCache );
  17963. }
  17964. }
  17965. if ( material.needsUpdate === false ) {
  17966. if ( materialProperties.program === undefined ) {
  17967. material.needsUpdate = true;
  17968. } else if ( material.fog && materialProperties.fog !== fog ) {
  17969. material.needsUpdate = true;
  17970. } else if ( material.lights && materialProperties.lightsHash !== lights.state.hash ) {
  17971. material.needsUpdate = true;
  17972. } else if ( materialProperties.numClippingPlanes !== undefined &&
  17973. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  17974. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  17975. material.needsUpdate = true;
  17976. }
  17977. }
  17978. if ( material.needsUpdate ) {
  17979. initMaterial( material, fog, object );
  17980. material.needsUpdate = false;
  17981. }
  17982. var refreshProgram = false;
  17983. var refreshMaterial = false;
  17984. var refreshLights = false;
  17985. var program = materialProperties.program,
  17986. p_uniforms = program.getUniforms(),
  17987. m_uniforms = materialProperties.shader.uniforms;
  17988. if ( state.useProgram( program.program ) ) {
  17989. refreshProgram = true;
  17990. refreshMaterial = true;
  17991. refreshLights = true;
  17992. }
  17993. if ( material.id !== _currentMaterialId ) {
  17994. _currentMaterialId = material.id;
  17995. refreshMaterial = true;
  17996. }
  17997. if ( refreshProgram || camera !== _currentCamera ) {
  17998. p_uniforms.setValue( _gl, 'projectionMatrix', camera.projectionMatrix );
  17999. if ( capabilities.logarithmicDepthBuffer ) {
  18000. p_uniforms.setValue( _gl, 'logDepthBufFC',
  18001. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  18002. }
  18003. // Avoid unneeded uniform updates per ArrayCamera's sub-camera
  18004. if ( _currentCamera !== ( _currentArrayCamera || camera ) ) {
  18005. _currentCamera = ( _currentArrayCamera || camera );
  18006. // lighting uniforms depend on the camera so enforce an update
  18007. // now, in case this material supports lights - or later, when
  18008. // the next material that does gets activated:
  18009. refreshMaterial = true; // set to true on material change
  18010. refreshLights = true; // remains set until update done
  18011. }
  18012. // load material specific uniforms
  18013. // (shader material also gets them for the sake of genericity)
  18014. if ( material.isShaderMaterial ||
  18015. material.isMeshPhongMaterial ||
  18016. material.isMeshStandardMaterial ||
  18017. material.envMap ) {
  18018. var uCamPos = p_uniforms.map.cameraPosition;
  18019. if ( uCamPos !== undefined ) {
  18020. uCamPos.setValue( _gl,
  18021. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  18022. }
  18023. }
  18024. if ( material.isMeshPhongMaterial ||
  18025. material.isMeshLambertMaterial ||
  18026. material.isMeshBasicMaterial ||
  18027. material.isMeshStandardMaterial ||
  18028. material.isShaderMaterial ||
  18029. material.skinning ) {
  18030. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  18031. }
  18032. }
  18033. // skinning uniforms must be set even if material didn't change
  18034. // auto-setting of texture unit for bone texture must go before other textures
  18035. // not sure why, but otherwise weird things happen
  18036. if ( material.skinning ) {
  18037. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  18038. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  18039. var skeleton = object.skeleton;
  18040. if ( skeleton ) {
  18041. var bones = skeleton.bones;
  18042. if ( capabilities.floatVertexTextures ) {
  18043. if ( skeleton.boneTexture === undefined ) {
  18044. // layout (1 matrix = 4 pixels)
  18045. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  18046. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  18047. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  18048. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  18049. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  18050. var size = Math.sqrt( bones.length * 4 ); // 4 pixels needed for 1 matrix
  18051. size = _Math.ceilPowerOfTwo( size );
  18052. size = Math.max( size, 4 );
  18053. var boneMatrices = new Float32Array( size * size * 4 ); // 4 floats per RGBA pixel
  18054. boneMatrices.set( skeleton.boneMatrices ); // copy current values
  18055. var boneTexture = new DataTexture( boneMatrices, size, size, RGBAFormat, FloatType );
  18056. skeleton.boneMatrices = boneMatrices;
  18057. skeleton.boneTexture = boneTexture;
  18058. skeleton.boneTextureSize = size;
  18059. }
  18060. p_uniforms.setValue( _gl, 'boneTexture', skeleton.boneTexture );
  18061. p_uniforms.setValue( _gl, 'boneTextureSize', skeleton.boneTextureSize );
  18062. } else {
  18063. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  18064. }
  18065. }
  18066. }
  18067. if ( refreshMaterial ) {
  18068. p_uniforms.setValue( _gl, 'toneMappingExposure', _this.toneMappingExposure );
  18069. p_uniforms.setValue( _gl, 'toneMappingWhitePoint', _this.toneMappingWhitePoint );
  18070. if ( material.lights ) {
  18071. // the current material requires lighting info
  18072. // note: all lighting uniforms are always set correctly
  18073. // they simply reference the renderer's state for their
  18074. // values
  18075. //
  18076. // use the current material's .needsUpdate flags to set
  18077. // the GL state when required
  18078. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  18079. }
  18080. // refresh uniforms common to several materials
  18081. if ( fog && material.fog ) {
  18082. refreshUniformsFog( m_uniforms, fog );
  18083. }
  18084. if ( material.isMeshBasicMaterial ) {
  18085. refreshUniformsCommon( m_uniforms, material );
  18086. } else if ( material.isMeshLambertMaterial ) {
  18087. refreshUniformsCommon( m_uniforms, material );
  18088. refreshUniformsLambert( m_uniforms, material );
  18089. } else if ( material.isMeshPhongMaterial ) {
  18090. refreshUniformsCommon( m_uniforms, material );
  18091. if ( material.isMeshToonMaterial ) {
  18092. refreshUniformsToon( m_uniforms, material );
  18093. } else {
  18094. refreshUniformsPhong( m_uniforms, material );
  18095. }
  18096. } else if ( material.isMeshStandardMaterial ) {
  18097. refreshUniformsCommon( m_uniforms, material );
  18098. if ( material.isMeshPhysicalMaterial ) {
  18099. refreshUniformsPhysical( m_uniforms, material );
  18100. } else {
  18101. refreshUniformsStandard( m_uniforms, material );
  18102. }
  18103. } else if ( material.isMeshDepthMaterial ) {
  18104. refreshUniformsCommon( m_uniforms, material );
  18105. refreshUniformsDepth( m_uniforms, material );
  18106. } else if ( material.isMeshDistanceMaterial ) {
  18107. refreshUniformsCommon( m_uniforms, material );
  18108. refreshUniformsDistance( m_uniforms, material );
  18109. } else if ( material.isMeshNormalMaterial ) {
  18110. refreshUniformsCommon( m_uniforms, material );
  18111. refreshUniformsNormal( m_uniforms, material );
  18112. } else if ( material.isLineBasicMaterial ) {
  18113. refreshUniformsLine( m_uniforms, material );
  18114. if ( material.isLineDashedMaterial ) {
  18115. refreshUniformsDash( m_uniforms, material );
  18116. }
  18117. } else if ( material.isPointsMaterial ) {
  18118. refreshUniformsPoints( m_uniforms, material );
  18119. } else if ( material.isShadowMaterial ) {
  18120. m_uniforms.color.value = material.color;
  18121. m_uniforms.opacity.value = material.opacity;
  18122. }
  18123. // RectAreaLight Texture
  18124. // TODO (mrdoob): Find a nicer implementation
  18125. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = UniformsLib.LTC_MAT_TEXTURE;
  18126. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = UniformsLib.LTC_MAG_TEXTURE;
  18127. WebGLUniforms.upload(
  18128. _gl, materialProperties.uniformsList, m_uniforms, _this );
  18129. }
  18130. // common matrices
  18131. p_uniforms.setValue( _gl, 'modelViewMatrix', object.modelViewMatrix );
  18132. p_uniforms.setValue( _gl, 'normalMatrix', object.normalMatrix );
  18133. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  18134. return program;
  18135. }
  18136. // Uniforms (refresh uniforms objects)
  18137. function refreshUniformsCommon( uniforms, material ) {
  18138. uniforms.opacity.value = material.opacity;
  18139. if ( material.color ) {
  18140. uniforms.diffuse.value = material.color;
  18141. }
  18142. if ( material.emissive ) {
  18143. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  18144. }
  18145. if ( material.map ) {
  18146. uniforms.map.value = material.map;
  18147. }
  18148. if ( material.alphaMap ) {
  18149. uniforms.alphaMap.value = material.alphaMap;
  18150. }
  18151. if ( material.specularMap ) {
  18152. uniforms.specularMap.value = material.specularMap;
  18153. }
  18154. if ( material.envMap ) {
  18155. uniforms.envMap.value = material.envMap;
  18156. // don't flip CubeTexture envMaps, flip everything else:
  18157. // WebGLRenderTargetCube will be flipped for backwards compatibility
  18158. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  18159. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  18160. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  18161. uniforms.reflectivity.value = material.reflectivity;
  18162. uniforms.refractionRatio.value = material.refractionRatio;
  18163. }
  18164. if ( material.lightMap ) {
  18165. uniforms.lightMap.value = material.lightMap;
  18166. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  18167. }
  18168. if ( material.aoMap ) {
  18169. uniforms.aoMap.value = material.aoMap;
  18170. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  18171. }
  18172. // uv repeat and offset setting priorities
  18173. // 1. color map
  18174. // 2. specular map
  18175. // 3. normal map
  18176. // 4. bump map
  18177. // 5. alpha map
  18178. // 6. emissive map
  18179. var uvScaleMap;
  18180. if ( material.map ) {
  18181. uvScaleMap = material.map;
  18182. } else if ( material.specularMap ) {
  18183. uvScaleMap = material.specularMap;
  18184. } else if ( material.displacementMap ) {
  18185. uvScaleMap = material.displacementMap;
  18186. } else if ( material.normalMap ) {
  18187. uvScaleMap = material.normalMap;
  18188. } else if ( material.bumpMap ) {
  18189. uvScaleMap = material.bumpMap;
  18190. } else if ( material.roughnessMap ) {
  18191. uvScaleMap = material.roughnessMap;
  18192. } else if ( material.metalnessMap ) {
  18193. uvScaleMap = material.metalnessMap;
  18194. } else if ( material.alphaMap ) {
  18195. uvScaleMap = material.alphaMap;
  18196. } else if ( material.emissiveMap ) {
  18197. uvScaleMap = material.emissiveMap;
  18198. }
  18199. if ( uvScaleMap !== undefined ) {
  18200. // backwards compatibility
  18201. if ( uvScaleMap.isWebGLRenderTarget ) {
  18202. uvScaleMap = uvScaleMap.texture;
  18203. }
  18204. if ( uvScaleMap.matrixAutoUpdate === true ) {
  18205. var offset = uvScaleMap.offset;
  18206. var repeat = uvScaleMap.repeat;
  18207. var rotation = uvScaleMap.rotation;
  18208. var center = uvScaleMap.center;
  18209. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  18210. }
  18211. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  18212. }
  18213. }
  18214. function refreshUniformsLine( uniforms, material ) {
  18215. uniforms.diffuse.value = material.color;
  18216. uniforms.opacity.value = material.opacity;
  18217. }
  18218. function refreshUniformsDash( uniforms, material ) {
  18219. uniforms.dashSize.value = material.dashSize;
  18220. uniforms.totalSize.value = material.dashSize + material.gapSize;
  18221. uniforms.scale.value = material.scale;
  18222. }
  18223. function refreshUniformsPoints( uniforms, material ) {
  18224. uniforms.diffuse.value = material.color;
  18225. uniforms.opacity.value = material.opacity;
  18226. uniforms.size.value = material.size * _pixelRatio;
  18227. uniforms.scale.value = _height * 0.5;
  18228. uniforms.map.value = material.map;
  18229. if ( material.map !== null ) {
  18230. if ( material.map.matrixAutoUpdate === true ) {
  18231. var offset = material.map.offset;
  18232. var repeat = material.map.repeat;
  18233. var rotation = material.map.rotation;
  18234. var center = material.map.center;
  18235. material.map.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  18236. }
  18237. uniforms.uvTransform.value.copy( material.map.matrix );
  18238. }
  18239. }
  18240. function refreshUniformsFog( uniforms, fog ) {
  18241. uniforms.fogColor.value = fog.color;
  18242. if ( fog.isFog ) {
  18243. uniforms.fogNear.value = fog.near;
  18244. uniforms.fogFar.value = fog.far;
  18245. } else if ( fog.isFogExp2 ) {
  18246. uniforms.fogDensity.value = fog.density;
  18247. }
  18248. }
  18249. function refreshUniformsLambert( uniforms, material ) {
  18250. if ( material.emissiveMap ) {
  18251. uniforms.emissiveMap.value = material.emissiveMap;
  18252. }
  18253. }
  18254. function refreshUniformsPhong( uniforms, material ) {
  18255. uniforms.specular.value = material.specular;
  18256. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  18257. if ( material.emissiveMap ) {
  18258. uniforms.emissiveMap.value = material.emissiveMap;
  18259. }
  18260. if ( material.bumpMap ) {
  18261. uniforms.bumpMap.value = material.bumpMap;
  18262. uniforms.bumpScale.value = material.bumpScale;
  18263. }
  18264. if ( material.normalMap ) {
  18265. uniforms.normalMap.value = material.normalMap;
  18266. uniforms.normalScale.value.copy( material.normalScale );
  18267. }
  18268. if ( material.displacementMap ) {
  18269. uniforms.displacementMap.value = material.displacementMap;
  18270. uniforms.displacementScale.value = material.displacementScale;
  18271. uniforms.displacementBias.value = material.displacementBias;
  18272. }
  18273. }
  18274. function refreshUniformsToon( uniforms, material ) {
  18275. refreshUniformsPhong( uniforms, material );
  18276. if ( material.gradientMap ) {
  18277. uniforms.gradientMap.value = material.gradientMap;
  18278. }
  18279. }
  18280. function refreshUniformsStandard( uniforms, material ) {
  18281. uniforms.roughness.value = material.roughness;
  18282. uniforms.metalness.value = material.metalness;
  18283. if ( material.roughnessMap ) {
  18284. uniforms.roughnessMap.value = material.roughnessMap;
  18285. }
  18286. if ( material.metalnessMap ) {
  18287. uniforms.metalnessMap.value = material.metalnessMap;
  18288. }
  18289. if ( material.emissiveMap ) {
  18290. uniforms.emissiveMap.value = material.emissiveMap;
  18291. }
  18292. if ( material.bumpMap ) {
  18293. uniforms.bumpMap.value = material.bumpMap;
  18294. uniforms.bumpScale.value = material.bumpScale;
  18295. }
  18296. if ( material.normalMap ) {
  18297. uniforms.normalMap.value = material.normalMap;
  18298. uniforms.normalScale.value.copy( material.normalScale );
  18299. }
  18300. if ( material.displacementMap ) {
  18301. uniforms.displacementMap.value = material.displacementMap;
  18302. uniforms.displacementScale.value = material.displacementScale;
  18303. uniforms.displacementBias.value = material.displacementBias;
  18304. }
  18305. if ( material.envMap ) {
  18306. //uniforms.envMap.value = material.envMap; // part of uniforms common
  18307. uniforms.envMapIntensity.value = material.envMapIntensity;
  18308. }
  18309. }
  18310. function refreshUniformsPhysical( uniforms, material ) {
  18311. uniforms.clearCoat.value = material.clearCoat;
  18312. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  18313. refreshUniformsStandard( uniforms, material );
  18314. }
  18315. function refreshUniformsDepth( uniforms, material ) {
  18316. if ( material.displacementMap ) {
  18317. uniforms.displacementMap.value = material.displacementMap;
  18318. uniforms.displacementScale.value = material.displacementScale;
  18319. uniforms.displacementBias.value = material.displacementBias;
  18320. }
  18321. }
  18322. function refreshUniformsDistance( uniforms, material ) {
  18323. if ( material.displacementMap ) {
  18324. uniforms.displacementMap.value = material.displacementMap;
  18325. uniforms.displacementScale.value = material.displacementScale;
  18326. uniforms.displacementBias.value = material.displacementBias;
  18327. }
  18328. uniforms.referencePosition.value.copy( material.referencePosition );
  18329. uniforms.nearDistance.value = material.nearDistance;
  18330. uniforms.farDistance.value = material.farDistance;
  18331. }
  18332. function refreshUniformsNormal( uniforms, material ) {
  18333. if ( material.bumpMap ) {
  18334. uniforms.bumpMap.value = material.bumpMap;
  18335. uniforms.bumpScale.value = material.bumpScale;
  18336. }
  18337. if ( material.normalMap ) {
  18338. uniforms.normalMap.value = material.normalMap;
  18339. uniforms.normalScale.value.copy( material.normalScale );
  18340. }
  18341. if ( material.displacementMap ) {
  18342. uniforms.displacementMap.value = material.displacementMap;
  18343. uniforms.displacementScale.value = material.displacementScale;
  18344. uniforms.displacementBias.value = material.displacementBias;
  18345. }
  18346. }
  18347. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  18348. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  18349. uniforms.ambientLightColor.needsUpdate = value;
  18350. uniforms.directionalLights.needsUpdate = value;
  18351. uniforms.pointLights.needsUpdate = value;
  18352. uniforms.spotLights.needsUpdate = value;
  18353. uniforms.rectAreaLights.needsUpdate = value;
  18354. uniforms.hemisphereLights.needsUpdate = value;
  18355. }
  18356. // GL state setting
  18357. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  18358. state.setCullFace( cullFace );
  18359. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  18360. };
  18361. // Textures
  18362. function allocTextureUnit() {
  18363. var textureUnit = _usedTextureUnits;
  18364. if ( textureUnit >= capabilities.maxTextures ) {
  18365. console.warn( 'THREE.WebGLRenderer: Trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  18366. }
  18367. _usedTextureUnits += 1;
  18368. return textureUnit;
  18369. }
  18370. this.allocTextureUnit = allocTextureUnit;
  18371. // this.setTexture2D = setTexture2D;
  18372. this.setTexture2D = ( function () {
  18373. var warned = false;
  18374. // backwards compatibility: peel texture.texture
  18375. return function setTexture2D( texture, slot ) {
  18376. if ( texture && texture.isWebGLRenderTarget ) {
  18377. if ( ! warned ) {
  18378. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  18379. warned = true;
  18380. }
  18381. texture = texture.texture;
  18382. }
  18383. textures.setTexture2D( texture, slot );
  18384. };
  18385. }() );
  18386. this.setTexture = ( function () {
  18387. var warned = false;
  18388. return function setTexture( texture, slot ) {
  18389. if ( ! warned ) {
  18390. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  18391. warned = true;
  18392. }
  18393. textures.setTexture2D( texture, slot );
  18394. };
  18395. }() );
  18396. this.setTextureCube = ( function () {
  18397. var warned = false;
  18398. return function setTextureCube( texture, slot ) {
  18399. // backwards compatibility: peel texture.texture
  18400. if ( texture && texture.isWebGLRenderTargetCube ) {
  18401. if ( ! warned ) {
  18402. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  18403. warned = true;
  18404. }
  18405. texture = texture.texture;
  18406. }
  18407. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  18408. // TODO: unify these code paths
  18409. if ( ( texture && texture.isCubeTexture ) ||
  18410. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  18411. // CompressedTexture can have Array in image :/
  18412. // this function alone should take care of cube textures
  18413. textures.setTextureCube( texture, slot );
  18414. } else {
  18415. // assumed: texture property of THREE.WebGLRenderTargetCube
  18416. textures.setTextureCubeDynamic( texture, slot );
  18417. }
  18418. };
  18419. }() );
  18420. this.getRenderTarget = function () {
  18421. return _currentRenderTarget;
  18422. };
  18423. this.setRenderTarget = function ( renderTarget ) {
  18424. _currentRenderTarget = renderTarget;
  18425. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  18426. textures.setupRenderTarget( renderTarget );
  18427. }
  18428. var framebuffer = null;
  18429. var isCube = false;
  18430. if ( renderTarget ) {
  18431. var __webglFramebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18432. if ( renderTarget.isWebGLRenderTargetCube ) {
  18433. framebuffer = __webglFramebuffer[ renderTarget.activeCubeFace ];
  18434. isCube = true;
  18435. } else {
  18436. framebuffer = __webglFramebuffer;
  18437. }
  18438. _currentViewport.copy( renderTarget.viewport );
  18439. _currentScissor.copy( renderTarget.scissor );
  18440. _currentScissorTest = renderTarget.scissorTest;
  18441. } else {
  18442. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  18443. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  18444. _currentScissorTest = _scissorTest;
  18445. }
  18446. if ( _currentFramebuffer !== framebuffer ) {
  18447. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18448. _currentFramebuffer = framebuffer;
  18449. }
  18450. state.viewport( _currentViewport );
  18451. state.scissor( _currentScissor );
  18452. state.setScissorTest( _currentScissorTest );
  18453. if ( isCube ) {
  18454. var textureProperties = properties.get( renderTarget.texture );
  18455. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  18456. }
  18457. };
  18458. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  18459. if ( ! ( renderTarget && renderTarget.isWebGLRenderTarget ) ) {
  18460. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  18461. return;
  18462. }
  18463. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  18464. if ( framebuffer ) {
  18465. var restore = false;
  18466. if ( framebuffer !== _currentFramebuffer ) {
  18467. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  18468. restore = true;
  18469. }
  18470. try {
  18471. var texture = renderTarget.texture;
  18472. var textureFormat = texture.format;
  18473. var textureType = texture.type;
  18474. if ( textureFormat !== RGBAFormat && utils.convert( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  18475. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  18476. return;
  18477. }
  18478. if ( textureType !== UnsignedByteType && utils.convert( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  18479. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  18480. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  18481. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  18482. return;
  18483. }
  18484. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  18485. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  18486. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  18487. _gl.readPixels( x, y, width, height, utils.convert( textureFormat ), utils.convert( textureType ), buffer );
  18488. }
  18489. } else {
  18490. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  18491. }
  18492. } finally {
  18493. if ( restore ) {
  18494. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  18495. }
  18496. }
  18497. }
  18498. };
  18499. }
  18500. /**
  18501. * @author mrdoob / http://mrdoob.com/
  18502. * @author alteredq / http://alteredqualia.com/
  18503. */
  18504. function FogExp2( color, density ) {
  18505. this.name = '';
  18506. this.color = new Color( color );
  18507. this.density = ( density !== undefined ) ? density : 0.00025;
  18508. }
  18509. FogExp2.prototype.isFogExp2 = true;
  18510. FogExp2.prototype.clone = function () {
  18511. return new FogExp2( this.color.getHex(), this.density );
  18512. };
  18513. FogExp2.prototype.toJSON = function ( /* meta */ ) {
  18514. return {
  18515. type: 'FogExp2',
  18516. color: this.color.getHex(),
  18517. density: this.density
  18518. };
  18519. };
  18520. /**
  18521. * @author mrdoob / http://mrdoob.com/
  18522. * @author alteredq / http://alteredqualia.com/
  18523. */
  18524. function Fog( color, near, far ) {
  18525. this.name = '';
  18526. this.color = new Color( color );
  18527. this.near = ( near !== undefined ) ? near : 1;
  18528. this.far = ( far !== undefined ) ? far : 1000;
  18529. }
  18530. Fog.prototype.isFog = true;
  18531. Fog.prototype.clone = function () {
  18532. return new Fog( this.color.getHex(), this.near, this.far );
  18533. };
  18534. Fog.prototype.toJSON = function ( /* meta */ ) {
  18535. return {
  18536. type: 'Fog',
  18537. color: this.color.getHex(),
  18538. near: this.near,
  18539. far: this.far
  18540. };
  18541. };
  18542. /**
  18543. * @author mrdoob / http://mrdoob.com/
  18544. */
  18545. function Scene() {
  18546. Object3D.call( this );
  18547. this.type = 'Scene';
  18548. this.background = null;
  18549. this.fog = null;
  18550. this.overrideMaterial = null;
  18551. this.autoUpdate = true; // checked by the renderer
  18552. }
  18553. Scene.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18554. constructor: Scene,
  18555. copy: function ( source, recursive ) {
  18556. Object3D.prototype.copy.call( this, source, recursive );
  18557. if ( source.background !== null ) this.background = source.background.clone();
  18558. if ( source.fog !== null ) this.fog = source.fog.clone();
  18559. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  18560. this.autoUpdate = source.autoUpdate;
  18561. this.matrixAutoUpdate = source.matrixAutoUpdate;
  18562. return this;
  18563. },
  18564. toJSON: function ( meta ) {
  18565. var data = Object3D.prototype.toJSON.call( this, meta );
  18566. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  18567. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  18568. return data;
  18569. }
  18570. } );
  18571. /**
  18572. * @author mikael emtinger / http://gomo.se/
  18573. * @author alteredq / http://alteredqualia.com/
  18574. */
  18575. function LensFlare( texture, size, distance, blending, color ) {
  18576. Object3D.call( this );
  18577. this.lensFlares = [];
  18578. this.positionScreen = new Vector3();
  18579. this.customUpdateCallback = undefined;
  18580. if ( texture !== undefined ) {
  18581. this.add( texture, size, distance, blending, color );
  18582. }
  18583. }
  18584. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18585. constructor: LensFlare,
  18586. isLensFlare: true,
  18587. copy: function ( source ) {
  18588. Object3D.prototype.copy.call( this, source );
  18589. this.positionScreen.copy( source.positionScreen );
  18590. this.customUpdateCallback = source.customUpdateCallback;
  18591. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  18592. this.lensFlares.push( source.lensFlares[ i ] );
  18593. }
  18594. return this;
  18595. },
  18596. add: function ( texture, size, distance, blending, color, opacity ) {
  18597. if ( size === undefined ) size = - 1;
  18598. if ( distance === undefined ) distance = 0;
  18599. if ( opacity === undefined ) opacity = 1;
  18600. if ( color === undefined ) color = new Color( 0xffffff );
  18601. if ( blending === undefined ) blending = NormalBlending;
  18602. distance = Math.min( distance, Math.max( 0, distance ) );
  18603. this.lensFlares.push( {
  18604. texture: texture, // THREE.Texture
  18605. size: size, // size in pixels (-1 = use texture.width)
  18606. distance: distance, // distance (0-1) from light source (0=at light source)
  18607. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  18608. scale: 1, // scale
  18609. rotation: 0, // rotation
  18610. opacity: opacity, // opacity
  18611. color: color, // color
  18612. blending: blending // blending
  18613. } );
  18614. },
  18615. /*
  18616. * Update lens flares update positions on all flares based on the screen position
  18617. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  18618. */
  18619. updateLensFlares: function () {
  18620. var f, fl = this.lensFlares.length;
  18621. var flare;
  18622. var vecX = - this.positionScreen.x * 2;
  18623. var vecY = - this.positionScreen.y * 2;
  18624. for ( f = 0; f < fl; f ++ ) {
  18625. flare = this.lensFlares[ f ];
  18626. flare.x = this.positionScreen.x + vecX * flare.distance;
  18627. flare.y = this.positionScreen.y + vecY * flare.distance;
  18628. flare.wantedRotation = flare.x * Math.PI * 0.25;
  18629. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  18630. }
  18631. }
  18632. } );
  18633. /**
  18634. * @author alteredq / http://alteredqualia.com/
  18635. *
  18636. * parameters = {
  18637. * color: <hex>,
  18638. * opacity: <float>,
  18639. * map: new THREE.Texture( <Image> ),
  18640. *
  18641. * uvOffset: new THREE.Vector2(),
  18642. * uvScale: new THREE.Vector2()
  18643. * }
  18644. */
  18645. function SpriteMaterial( parameters ) {
  18646. Material.call( this );
  18647. this.type = 'SpriteMaterial';
  18648. this.color = new Color( 0xffffff );
  18649. this.map = null;
  18650. this.rotation = 0;
  18651. this.fog = false;
  18652. this.lights = false;
  18653. this.setValues( parameters );
  18654. }
  18655. SpriteMaterial.prototype = Object.create( Material.prototype );
  18656. SpriteMaterial.prototype.constructor = SpriteMaterial;
  18657. SpriteMaterial.prototype.isSpriteMaterial = true;
  18658. SpriteMaterial.prototype.copy = function ( source ) {
  18659. Material.prototype.copy.call( this, source );
  18660. this.color.copy( source.color );
  18661. this.map = source.map;
  18662. this.rotation = source.rotation;
  18663. return this;
  18664. };
  18665. /**
  18666. * @author mikael emtinger / http://gomo.se/
  18667. * @author alteredq / http://alteredqualia.com/
  18668. */
  18669. function Sprite( material ) {
  18670. Object3D.call( this );
  18671. this.type = 'Sprite';
  18672. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  18673. }
  18674. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18675. constructor: Sprite,
  18676. isSprite: true,
  18677. raycast: ( function () {
  18678. var intersectPoint = new Vector3();
  18679. var worldPosition = new Vector3();
  18680. var worldScale = new Vector3();
  18681. return function raycast( raycaster, intersects ) {
  18682. worldPosition.setFromMatrixPosition( this.matrixWorld );
  18683. raycaster.ray.closestPointToPoint( worldPosition, intersectPoint );
  18684. worldScale.setFromMatrixScale( this.matrixWorld );
  18685. var guessSizeSq = worldScale.x * worldScale.y / 4;
  18686. if ( worldPosition.distanceToSquared( intersectPoint ) > guessSizeSq ) return;
  18687. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18688. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18689. intersects.push( {
  18690. distance: distance,
  18691. point: intersectPoint.clone(),
  18692. face: null,
  18693. object: this
  18694. } );
  18695. };
  18696. }() ),
  18697. clone: function () {
  18698. return new this.constructor( this.material ).copy( this );
  18699. }
  18700. } );
  18701. /**
  18702. * @author mikael emtinger / http://gomo.se/
  18703. * @author alteredq / http://alteredqualia.com/
  18704. * @author mrdoob / http://mrdoob.com/
  18705. */
  18706. function LOD() {
  18707. Object3D.call( this );
  18708. this.type = 'LOD';
  18709. Object.defineProperties( this, {
  18710. levels: {
  18711. enumerable: true,
  18712. value: []
  18713. }
  18714. } );
  18715. }
  18716. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18717. constructor: LOD,
  18718. copy: function ( source ) {
  18719. Object3D.prototype.copy.call( this, source, false );
  18720. var levels = source.levels;
  18721. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18722. var level = levels[ i ];
  18723. this.addLevel( level.object.clone(), level.distance );
  18724. }
  18725. return this;
  18726. },
  18727. addLevel: function ( object, distance ) {
  18728. if ( distance === undefined ) distance = 0;
  18729. distance = Math.abs( distance );
  18730. var levels = this.levels;
  18731. for ( var l = 0; l < levels.length; l ++ ) {
  18732. if ( distance < levels[ l ].distance ) {
  18733. break;
  18734. }
  18735. }
  18736. levels.splice( l, 0, { distance: distance, object: object } );
  18737. this.add( object );
  18738. },
  18739. getObjectForDistance: function ( distance ) {
  18740. var levels = this.levels;
  18741. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18742. if ( distance < levels[ i ].distance ) {
  18743. break;
  18744. }
  18745. }
  18746. return levels[ i - 1 ].object;
  18747. },
  18748. raycast: ( function () {
  18749. var matrixPosition = new Vector3();
  18750. return function raycast( raycaster, intersects ) {
  18751. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  18752. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  18753. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  18754. };
  18755. }() ),
  18756. update: function () {
  18757. var v1 = new Vector3();
  18758. var v2 = new Vector3();
  18759. return function update( camera ) {
  18760. var levels = this.levels;
  18761. if ( levels.length > 1 ) {
  18762. v1.setFromMatrixPosition( camera.matrixWorld );
  18763. v2.setFromMatrixPosition( this.matrixWorld );
  18764. var distance = v1.distanceTo( v2 );
  18765. levels[ 0 ].object.visible = true;
  18766. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  18767. if ( distance >= levels[ i ].distance ) {
  18768. levels[ i - 1 ].object.visible = false;
  18769. levels[ i ].object.visible = true;
  18770. } else {
  18771. break;
  18772. }
  18773. }
  18774. for ( ; i < l; i ++ ) {
  18775. levels[ i ].object.visible = false;
  18776. }
  18777. }
  18778. };
  18779. }(),
  18780. toJSON: function ( meta ) {
  18781. var data = Object3D.prototype.toJSON.call( this, meta );
  18782. data.object.levels = [];
  18783. var levels = this.levels;
  18784. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  18785. var level = levels[ i ];
  18786. data.object.levels.push( {
  18787. object: level.object.uuid,
  18788. distance: level.distance
  18789. } );
  18790. }
  18791. return data;
  18792. }
  18793. } );
  18794. /**
  18795. * @author mikael emtinger / http://gomo.se/
  18796. * @author alteredq / http://alteredqualia.com/
  18797. * @author michael guerrero / http://realitymeltdown.com
  18798. * @author ikerr / http://verold.com
  18799. */
  18800. function Skeleton( bones, boneInverses ) {
  18801. // copy the bone array
  18802. bones = bones || [];
  18803. this.bones = bones.slice( 0 );
  18804. this.boneMatrices = new Float32Array( this.bones.length * 16 );
  18805. // use the supplied bone inverses or calculate the inverses
  18806. if ( boneInverses === undefined ) {
  18807. this.calculateInverses();
  18808. } else {
  18809. if ( this.bones.length === boneInverses.length ) {
  18810. this.boneInverses = boneInverses.slice( 0 );
  18811. } else {
  18812. console.warn( 'THREE.Skeleton boneInverses is the wrong length.' );
  18813. this.boneInverses = [];
  18814. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18815. this.boneInverses.push( new Matrix4() );
  18816. }
  18817. }
  18818. }
  18819. }
  18820. Object.assign( Skeleton.prototype, {
  18821. calculateInverses: function () {
  18822. this.boneInverses = [];
  18823. for ( var i = 0, il = this.bones.length; i < il; i ++ ) {
  18824. var inverse = new Matrix4();
  18825. if ( this.bones[ i ] ) {
  18826. inverse.getInverse( this.bones[ i ].matrixWorld );
  18827. }
  18828. this.boneInverses.push( inverse );
  18829. }
  18830. },
  18831. pose: function () {
  18832. var bone, i, il;
  18833. // recover the bind-time world matrices
  18834. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18835. bone = this.bones[ i ];
  18836. if ( bone ) {
  18837. bone.matrixWorld.getInverse( this.boneInverses[ i ] );
  18838. }
  18839. }
  18840. // compute the local matrices, positions, rotations and scales
  18841. for ( i = 0, il = this.bones.length; i < il; i ++ ) {
  18842. bone = this.bones[ i ];
  18843. if ( bone ) {
  18844. if ( bone.parent && bone.parent.isBone ) {
  18845. bone.matrix.getInverse( bone.parent.matrixWorld );
  18846. bone.matrix.multiply( bone.matrixWorld );
  18847. } else {
  18848. bone.matrix.copy( bone.matrixWorld );
  18849. }
  18850. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  18851. }
  18852. }
  18853. },
  18854. update: ( function () {
  18855. var offsetMatrix = new Matrix4();
  18856. var identityMatrix = new Matrix4();
  18857. return function update() {
  18858. var bones = this.bones;
  18859. var boneInverses = this.boneInverses;
  18860. var boneMatrices = this.boneMatrices;
  18861. var boneTexture = this.boneTexture;
  18862. // flatten bone matrices to array
  18863. for ( var i = 0, il = bones.length; i < il; i ++ ) {
  18864. // compute the offset between the current and the original transform
  18865. var matrix = bones[ i ] ? bones[ i ].matrixWorld : identityMatrix;
  18866. offsetMatrix.multiplyMatrices( matrix, boneInverses[ i ] );
  18867. offsetMatrix.toArray( boneMatrices, i * 16 );
  18868. }
  18869. if ( boneTexture !== undefined ) {
  18870. boneTexture.needsUpdate = true;
  18871. }
  18872. };
  18873. } )(),
  18874. clone: function () {
  18875. return new Skeleton( this.bones, this.boneInverses );
  18876. }
  18877. } );
  18878. /**
  18879. * @author mikael emtinger / http://gomo.se/
  18880. * @author alteredq / http://alteredqualia.com/
  18881. * @author ikerr / http://verold.com
  18882. */
  18883. function Bone() {
  18884. Object3D.call( this );
  18885. this.type = 'Bone';
  18886. }
  18887. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18888. constructor: Bone,
  18889. isBone: true
  18890. } );
  18891. /**
  18892. * @author mikael emtinger / http://gomo.se/
  18893. * @author alteredq / http://alteredqualia.com/
  18894. * @author ikerr / http://verold.com
  18895. */
  18896. function SkinnedMesh( geometry, material ) {
  18897. Mesh.call( this, geometry, material );
  18898. this.type = 'SkinnedMesh';
  18899. this.bindMode = 'attached';
  18900. this.bindMatrix = new Matrix4();
  18901. this.bindMatrixInverse = new Matrix4();
  18902. var bones = this.initBones();
  18903. var skeleton = new Skeleton( bones );
  18904. this.bind( skeleton, this.matrixWorld );
  18905. this.normalizeSkinWeights();
  18906. }
  18907. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18908. constructor: SkinnedMesh,
  18909. isSkinnedMesh: true,
  18910. initBones: function () {
  18911. var bones = [], bone, gbone;
  18912. var i, il;
  18913. if ( this.geometry && this.geometry.bones !== undefined ) {
  18914. // first, create array of 'Bone' objects from geometry data
  18915. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18916. gbone = this.geometry.bones[ i ];
  18917. // create new 'Bone' object
  18918. bone = new Bone();
  18919. bones.push( bone );
  18920. // apply values
  18921. bone.name = gbone.name;
  18922. bone.position.fromArray( gbone.pos );
  18923. bone.quaternion.fromArray( gbone.rotq );
  18924. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  18925. }
  18926. // second, create bone hierarchy
  18927. for ( i = 0, il = this.geometry.bones.length; i < il; i ++ ) {
  18928. gbone = this.geometry.bones[ i ];
  18929. if ( ( gbone.parent !== - 1 ) && ( gbone.parent !== null ) && ( bones[ gbone.parent ] !== undefined ) ) {
  18930. // subsequent bones in the hierarchy
  18931. bones[ gbone.parent ].add( bones[ i ] );
  18932. } else {
  18933. // topmost bone, immediate child of the skinned mesh
  18934. this.add( bones[ i ] );
  18935. }
  18936. }
  18937. }
  18938. // now the bones are part of the scene graph and children of the skinned mesh.
  18939. // let's update the corresponding matrices
  18940. this.updateMatrixWorld( true );
  18941. return bones;
  18942. },
  18943. bind: function ( skeleton, bindMatrix ) {
  18944. this.skeleton = skeleton;
  18945. if ( bindMatrix === undefined ) {
  18946. this.updateMatrixWorld( true );
  18947. this.skeleton.calculateInverses();
  18948. bindMatrix = this.matrixWorld;
  18949. }
  18950. this.bindMatrix.copy( bindMatrix );
  18951. this.bindMatrixInverse.getInverse( bindMatrix );
  18952. },
  18953. pose: function () {
  18954. this.skeleton.pose();
  18955. },
  18956. normalizeSkinWeights: function () {
  18957. var scale, i;
  18958. if ( this.geometry && this.geometry.isGeometry ) {
  18959. for ( i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18960. var sw = this.geometry.skinWeights[ i ];
  18961. scale = 1.0 / sw.manhattanLength();
  18962. if ( scale !== Infinity ) {
  18963. sw.multiplyScalar( scale );
  18964. } else {
  18965. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18966. }
  18967. }
  18968. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18969. var vec = new Vector4();
  18970. var skinWeight = this.geometry.attributes.skinWeight;
  18971. for ( i = 0; i < skinWeight.count; i ++ ) {
  18972. vec.x = skinWeight.getX( i );
  18973. vec.y = skinWeight.getY( i );
  18974. vec.z = skinWeight.getZ( i );
  18975. vec.w = skinWeight.getW( i );
  18976. scale = 1.0 / vec.manhattanLength();
  18977. if ( scale !== Infinity ) {
  18978. vec.multiplyScalar( scale );
  18979. } else {
  18980. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18981. }
  18982. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18983. }
  18984. }
  18985. },
  18986. updateMatrixWorld: function ( force ) {
  18987. Mesh.prototype.updateMatrixWorld.call( this, force );
  18988. if ( this.bindMode === 'attached' ) {
  18989. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18990. } else if ( this.bindMode === 'detached' ) {
  18991. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18992. } else {
  18993. console.warn( 'THREE.SkinnedMesh: Unrecognized bindMode: ' + this.bindMode );
  18994. }
  18995. },
  18996. clone: function () {
  18997. return new this.constructor( this.geometry, this.material ).copy( this );
  18998. }
  18999. } );
  19000. /**
  19001. * @author mrdoob / http://mrdoob.com/
  19002. * @author alteredq / http://alteredqualia.com/
  19003. *
  19004. * parameters = {
  19005. * color: <hex>,
  19006. * opacity: <float>,
  19007. *
  19008. * linewidth: <float>,
  19009. * linecap: "round",
  19010. * linejoin: "round"
  19011. * }
  19012. */
  19013. function LineBasicMaterial( parameters ) {
  19014. Material.call( this );
  19015. this.type = 'LineBasicMaterial';
  19016. this.color = new Color( 0xffffff );
  19017. this.linewidth = 1;
  19018. this.linecap = 'round';
  19019. this.linejoin = 'round';
  19020. this.lights = false;
  19021. this.setValues( parameters );
  19022. }
  19023. LineBasicMaterial.prototype = Object.create( Material.prototype );
  19024. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  19025. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  19026. LineBasicMaterial.prototype.copy = function ( source ) {
  19027. Material.prototype.copy.call( this, source );
  19028. this.color.copy( source.color );
  19029. this.linewidth = source.linewidth;
  19030. this.linecap = source.linecap;
  19031. this.linejoin = source.linejoin;
  19032. return this;
  19033. };
  19034. /**
  19035. * @author mrdoob / http://mrdoob.com/
  19036. */
  19037. function Line( geometry, material, mode ) {
  19038. if ( mode === 1 ) {
  19039. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  19040. return new LineSegments( geometry, material );
  19041. }
  19042. Object3D.call( this );
  19043. this.type = 'Line';
  19044. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19045. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  19046. }
  19047. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19048. constructor: Line,
  19049. isLine: true,
  19050. raycast: ( function () {
  19051. var inverseMatrix = new Matrix4();
  19052. var ray = new Ray();
  19053. var sphere = new Sphere();
  19054. return function raycast( raycaster, intersects ) {
  19055. var precision = raycaster.linePrecision;
  19056. var precisionSq = precision * precision;
  19057. var geometry = this.geometry;
  19058. var matrixWorld = this.matrixWorld;
  19059. // Checking boundingSphere distance to ray
  19060. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19061. sphere.copy( geometry.boundingSphere );
  19062. sphere.applyMatrix4( matrixWorld );
  19063. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19064. //
  19065. inverseMatrix.getInverse( matrixWorld );
  19066. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19067. var vStart = new Vector3();
  19068. var vEnd = new Vector3();
  19069. var interSegment = new Vector3();
  19070. var interRay = new Vector3();
  19071. var step = ( this && this.isLineSegments ) ? 2 : 1;
  19072. if ( geometry.isBufferGeometry ) {
  19073. var index = geometry.index;
  19074. var attributes = geometry.attributes;
  19075. var positions = attributes.position.array;
  19076. if ( index !== null ) {
  19077. var indices = index.array;
  19078. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  19079. var a = indices[ i ];
  19080. var b = indices[ i + 1 ];
  19081. vStart.fromArray( positions, a * 3 );
  19082. vEnd.fromArray( positions, b * 3 );
  19083. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19084. if ( distSq > precisionSq ) continue;
  19085. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19086. var distance = raycaster.ray.origin.distanceTo( interRay );
  19087. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19088. intersects.push( {
  19089. distance: distance,
  19090. // What do we want? intersection point on the ray or on the segment??
  19091. // point: raycaster.ray.at( distance ),
  19092. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19093. index: i,
  19094. face: null,
  19095. faceIndex: null,
  19096. object: this
  19097. } );
  19098. }
  19099. } else {
  19100. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  19101. vStart.fromArray( positions, 3 * i );
  19102. vEnd.fromArray( positions, 3 * i + 3 );
  19103. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  19104. if ( distSq > precisionSq ) continue;
  19105. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19106. var distance = raycaster.ray.origin.distanceTo( interRay );
  19107. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19108. intersects.push( {
  19109. distance: distance,
  19110. // What do we want? intersection point on the ray or on the segment??
  19111. // point: raycaster.ray.at( distance ),
  19112. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19113. index: i,
  19114. face: null,
  19115. faceIndex: null,
  19116. object: this
  19117. } );
  19118. }
  19119. }
  19120. } else if ( geometry.isGeometry ) {
  19121. var vertices = geometry.vertices;
  19122. var nbVertices = vertices.length;
  19123. for ( var i = 0; i < nbVertices - 1; i += step ) {
  19124. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  19125. if ( distSq > precisionSq ) continue;
  19126. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  19127. var distance = raycaster.ray.origin.distanceTo( interRay );
  19128. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  19129. intersects.push( {
  19130. distance: distance,
  19131. // What do we want? intersection point on the ray or on the segment??
  19132. // point: raycaster.ray.at( distance ),
  19133. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  19134. index: i,
  19135. face: null,
  19136. faceIndex: null,
  19137. object: this
  19138. } );
  19139. }
  19140. }
  19141. };
  19142. }() ),
  19143. clone: function () {
  19144. return new this.constructor( this.geometry, this.material ).copy( this );
  19145. }
  19146. } );
  19147. /**
  19148. * @author mrdoob / http://mrdoob.com/
  19149. */
  19150. function LineSegments( geometry, material ) {
  19151. Line.call( this, geometry, material );
  19152. this.type = 'LineSegments';
  19153. }
  19154. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  19155. constructor: LineSegments,
  19156. isLineSegments: true
  19157. } );
  19158. /**
  19159. * @author mgreter / http://github.com/mgreter
  19160. */
  19161. function LineLoop( geometry, material ) {
  19162. Line.call( this, geometry, material );
  19163. this.type = 'LineLoop';
  19164. }
  19165. LineLoop.prototype = Object.assign( Object.create( Line.prototype ), {
  19166. constructor: LineLoop,
  19167. isLineLoop: true,
  19168. } );
  19169. /**
  19170. * @author mrdoob / http://mrdoob.com/
  19171. * @author alteredq / http://alteredqualia.com/
  19172. *
  19173. * parameters = {
  19174. * color: <hex>,
  19175. * opacity: <float>,
  19176. * map: new THREE.Texture( <Image> ),
  19177. *
  19178. * size: <float>,
  19179. * sizeAttenuation: <bool>
  19180. * }
  19181. */
  19182. function PointsMaterial( parameters ) {
  19183. Material.call( this );
  19184. this.type = 'PointsMaterial';
  19185. this.color = new Color( 0xffffff );
  19186. this.map = null;
  19187. this.size = 1;
  19188. this.sizeAttenuation = true;
  19189. this.lights = false;
  19190. this.setValues( parameters );
  19191. }
  19192. PointsMaterial.prototype = Object.create( Material.prototype );
  19193. PointsMaterial.prototype.constructor = PointsMaterial;
  19194. PointsMaterial.prototype.isPointsMaterial = true;
  19195. PointsMaterial.prototype.copy = function ( source ) {
  19196. Material.prototype.copy.call( this, source );
  19197. this.color.copy( source.color );
  19198. this.map = source.map;
  19199. this.size = source.size;
  19200. this.sizeAttenuation = source.sizeAttenuation;
  19201. return this;
  19202. };
  19203. /**
  19204. * @author alteredq / http://alteredqualia.com/
  19205. */
  19206. function Points( geometry, material ) {
  19207. Object3D.call( this );
  19208. this.type = 'Points';
  19209. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  19210. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  19211. }
  19212. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19213. constructor: Points,
  19214. isPoints: true,
  19215. raycast: ( function () {
  19216. var inverseMatrix = new Matrix4();
  19217. var ray = new Ray();
  19218. var sphere = new Sphere();
  19219. return function raycast( raycaster, intersects ) {
  19220. var object = this;
  19221. var geometry = this.geometry;
  19222. var matrixWorld = this.matrixWorld;
  19223. var threshold = raycaster.params.Points.threshold;
  19224. // Checking boundingSphere distance to ray
  19225. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  19226. sphere.copy( geometry.boundingSphere );
  19227. sphere.applyMatrix4( matrixWorld );
  19228. sphere.radius += threshold;
  19229. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  19230. //
  19231. inverseMatrix.getInverse( matrixWorld );
  19232. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  19233. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  19234. var localThresholdSq = localThreshold * localThreshold;
  19235. var position = new Vector3();
  19236. function testPoint( point, index ) {
  19237. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  19238. if ( rayPointDistanceSq < localThresholdSq ) {
  19239. var intersectPoint = ray.closestPointToPoint( point );
  19240. intersectPoint.applyMatrix4( matrixWorld );
  19241. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  19242. if ( distance < raycaster.near || distance > raycaster.far ) return;
  19243. intersects.push( {
  19244. distance: distance,
  19245. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  19246. point: intersectPoint.clone(),
  19247. index: index,
  19248. face: null,
  19249. object: object
  19250. } );
  19251. }
  19252. }
  19253. if ( geometry.isBufferGeometry ) {
  19254. var index = geometry.index;
  19255. var attributes = geometry.attributes;
  19256. var positions = attributes.position.array;
  19257. if ( index !== null ) {
  19258. var indices = index.array;
  19259. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  19260. var a = indices[ i ];
  19261. position.fromArray( positions, a * 3 );
  19262. testPoint( position, a );
  19263. }
  19264. } else {
  19265. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  19266. position.fromArray( positions, i * 3 );
  19267. testPoint( position, i );
  19268. }
  19269. }
  19270. } else {
  19271. var vertices = geometry.vertices;
  19272. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19273. testPoint( vertices[ i ], i );
  19274. }
  19275. }
  19276. };
  19277. }() ),
  19278. clone: function () {
  19279. return new this.constructor( this.geometry, this.material ).copy( this );
  19280. }
  19281. } );
  19282. /**
  19283. * @author mrdoob / http://mrdoob.com/
  19284. */
  19285. function Group() {
  19286. Object3D.call( this );
  19287. this.type = 'Group';
  19288. }
  19289. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  19290. constructor: Group,
  19291. isGroup: true
  19292. } );
  19293. /**
  19294. * @author mrdoob / http://mrdoob.com/
  19295. */
  19296. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  19297. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19298. this.generateMipmaps = false;
  19299. // Set needsUpdate when first frame is ready
  19300. var scope = this;
  19301. function onLoaded() {
  19302. video.removeEventListener( 'loadeddata', onLoaded, false );
  19303. scope.needsUpdate = true;
  19304. }
  19305. video.addEventListener( 'loadeddata', onLoaded, false );
  19306. }
  19307. VideoTexture.prototype = Object.assign( Object.create( Texture.prototype ), {
  19308. constructor: VideoTexture,
  19309. isVideoTexture: true,
  19310. update: function () {
  19311. var video = this.image;
  19312. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  19313. this.needsUpdate = true;
  19314. }
  19315. }
  19316. } );
  19317. /**
  19318. * @author alteredq / http://alteredqualia.com/
  19319. */
  19320. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  19321. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  19322. this.image = { width: width, height: height };
  19323. this.mipmaps = mipmaps;
  19324. // no flipping for cube textures
  19325. // (also flipping doesn't work for compressed textures )
  19326. this.flipY = false;
  19327. // can't generate mipmaps for compressed textures
  19328. // mips must be embedded in DDS files
  19329. this.generateMipmaps = false;
  19330. }
  19331. CompressedTexture.prototype = Object.create( Texture.prototype );
  19332. CompressedTexture.prototype.constructor = CompressedTexture;
  19333. CompressedTexture.prototype.isCompressedTexture = true;
  19334. /**
  19335. * @author Matt DesLauriers / @mattdesl
  19336. * @author atix / arthursilber.de
  19337. */
  19338. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  19339. format = format !== undefined ? format : DepthFormat;
  19340. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  19341. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' );
  19342. }
  19343. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  19344. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  19345. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  19346. this.image = { width: width, height: height };
  19347. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  19348. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  19349. this.flipY = false;
  19350. this.generateMipmaps = false;
  19351. }
  19352. DepthTexture.prototype = Object.create( Texture.prototype );
  19353. DepthTexture.prototype.constructor = DepthTexture;
  19354. DepthTexture.prototype.isDepthTexture = true;
  19355. /**
  19356. * @author mrdoob / http://mrdoob.com/
  19357. * @author Mugen87 / https://github.com/Mugen87
  19358. */
  19359. function WireframeGeometry( geometry ) {
  19360. BufferGeometry.call( this );
  19361. this.type = 'WireframeGeometry';
  19362. // buffer
  19363. var vertices = [];
  19364. // helper variables
  19365. var i, j, l, o, ol;
  19366. var edge = [ 0, 0 ], edges = {}, e, edge1, edge2;
  19367. var key, keys = [ 'a', 'b', 'c' ];
  19368. var vertex;
  19369. // different logic for Geometry and BufferGeometry
  19370. if ( geometry && geometry.isGeometry ) {
  19371. // create a data structure that contains all edges without duplicates
  19372. var faces = geometry.faces;
  19373. for ( i = 0, l = faces.length; i < l; i ++ ) {
  19374. var face = faces[ i ];
  19375. for ( j = 0; j < 3; j ++ ) {
  19376. edge1 = face[ keys[ j ] ];
  19377. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  19378. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19379. edge[ 1 ] = Math.max( edge1, edge2 );
  19380. key = edge[ 0 ] + ',' + edge[ 1 ];
  19381. if ( edges[ key ] === undefined ) {
  19382. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19383. }
  19384. }
  19385. }
  19386. // generate vertices
  19387. for ( key in edges ) {
  19388. e = edges[ key ];
  19389. vertex = geometry.vertices[ e.index1 ];
  19390. vertices.push( vertex.x, vertex.y, vertex.z );
  19391. vertex = geometry.vertices[ e.index2 ];
  19392. vertices.push( vertex.x, vertex.y, vertex.z );
  19393. }
  19394. } else if ( geometry && geometry.isBufferGeometry ) {
  19395. var position, indices, groups;
  19396. var group, start, count;
  19397. var index1, index2;
  19398. vertex = new Vector3();
  19399. if ( geometry.index !== null ) {
  19400. // indexed BufferGeometry
  19401. position = geometry.attributes.position;
  19402. indices = geometry.index;
  19403. groups = geometry.groups;
  19404. if ( groups.length === 0 ) {
  19405. groups = [ { start: 0, count: indices.count, materialIndex: 0 } ];
  19406. }
  19407. // create a data structure that contains all eges without duplicates
  19408. for ( o = 0, ol = groups.length; o < ol; ++ o ) {
  19409. group = groups[ o ];
  19410. start = group.start;
  19411. count = group.count;
  19412. for ( i = start, l = ( start + count ); i < l; i += 3 ) {
  19413. for ( j = 0; j < 3; j ++ ) {
  19414. edge1 = indices.getX( i + j );
  19415. edge2 = indices.getX( i + ( j + 1 ) % 3 );
  19416. edge[ 0 ] = Math.min( edge1, edge2 ); // sorting prevents duplicates
  19417. edge[ 1 ] = Math.max( edge1, edge2 );
  19418. key = edge[ 0 ] + ',' + edge[ 1 ];
  19419. if ( edges[ key ] === undefined ) {
  19420. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ] };
  19421. }
  19422. }
  19423. }
  19424. }
  19425. // generate vertices
  19426. for ( key in edges ) {
  19427. e = edges[ key ];
  19428. vertex.fromBufferAttribute( position, e.index1 );
  19429. vertices.push( vertex.x, vertex.y, vertex.z );
  19430. vertex.fromBufferAttribute( position, e.index2 );
  19431. vertices.push( vertex.x, vertex.y, vertex.z );
  19432. }
  19433. } else {
  19434. // non-indexed BufferGeometry
  19435. position = geometry.attributes.position;
  19436. for ( i = 0, l = ( position.count / 3 ); i < l; i ++ ) {
  19437. for ( j = 0; j < 3; j ++ ) {
  19438. // three edges per triangle, an edge is represented as (index1, index2)
  19439. // e.g. the first triangle has the following edges: (0,1),(1,2),(2,0)
  19440. index1 = 3 * i + j;
  19441. vertex.fromBufferAttribute( position, index1 );
  19442. vertices.push( vertex.x, vertex.y, vertex.z );
  19443. index2 = 3 * i + ( ( j + 1 ) % 3 );
  19444. vertex.fromBufferAttribute( position, index2 );
  19445. vertices.push( vertex.x, vertex.y, vertex.z );
  19446. }
  19447. }
  19448. }
  19449. }
  19450. // build geometry
  19451. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19452. }
  19453. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  19454. WireframeGeometry.prototype.constructor = WireframeGeometry;
  19455. /**
  19456. * @author zz85 / https://github.com/zz85
  19457. * @author Mugen87 / https://github.com/Mugen87
  19458. *
  19459. * Parametric Surfaces Geometry
  19460. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19461. */
  19462. // ParametricGeometry
  19463. function ParametricGeometry( func, slices, stacks ) {
  19464. Geometry.call( this );
  19465. this.type = 'ParametricGeometry';
  19466. this.parameters = {
  19467. func: func,
  19468. slices: slices,
  19469. stacks: stacks
  19470. };
  19471. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  19472. this.mergeVertices();
  19473. }
  19474. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  19475. ParametricGeometry.prototype.constructor = ParametricGeometry;
  19476. // ParametricBufferGeometry
  19477. function ParametricBufferGeometry( func, slices, stacks ) {
  19478. BufferGeometry.call( this );
  19479. this.type = 'ParametricBufferGeometry';
  19480. this.parameters = {
  19481. func: func,
  19482. slices: slices,
  19483. stacks: stacks
  19484. };
  19485. // buffers
  19486. var indices = [];
  19487. var vertices = [];
  19488. var normals = [];
  19489. var uvs = [];
  19490. var EPS = 0.00001;
  19491. var normal = new Vector3();
  19492. var p0 = new Vector3(), p1 = new Vector3();
  19493. var pu = new Vector3(), pv = new Vector3();
  19494. var i, j;
  19495. // generate vertices, normals and uvs
  19496. var sliceCount = slices + 1;
  19497. for ( i = 0; i <= stacks; i ++ ) {
  19498. var v = i / stacks;
  19499. for ( j = 0; j <= slices; j ++ ) {
  19500. var u = j / slices;
  19501. // vertex
  19502. p0 = func( u, v, p0 );
  19503. vertices.push( p0.x, p0.y, p0.z );
  19504. // normal
  19505. // approximate tangent vectors via finite differences
  19506. if ( u - EPS >= 0 ) {
  19507. p1 = func( u - EPS, v, p1 );
  19508. pu.subVectors( p0, p1 );
  19509. } else {
  19510. p1 = func( u + EPS, v, p1 );
  19511. pu.subVectors( p1, p0 );
  19512. }
  19513. if ( v - EPS >= 0 ) {
  19514. p1 = func( u, v - EPS, p1 );
  19515. pv.subVectors( p0, p1 );
  19516. } else {
  19517. p1 = func( u, v + EPS, p1 );
  19518. pv.subVectors( p1, p0 );
  19519. }
  19520. // cross product of tangent vectors returns surface normal
  19521. normal.crossVectors( pu, pv ).normalize();
  19522. normals.push( normal.x, normal.y, normal.z );
  19523. // uv
  19524. uvs.push( u, v );
  19525. }
  19526. }
  19527. // generate indices
  19528. for ( i = 0; i < stacks; i ++ ) {
  19529. for ( j = 0; j < slices; j ++ ) {
  19530. var a = i * sliceCount + j;
  19531. var b = i * sliceCount + j + 1;
  19532. var c = ( i + 1 ) * sliceCount + j + 1;
  19533. var d = ( i + 1 ) * sliceCount + j;
  19534. // faces one and two
  19535. indices.push( a, b, d );
  19536. indices.push( b, c, d );
  19537. }
  19538. }
  19539. // build geometry
  19540. this.setIndex( indices );
  19541. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19542. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19543. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19544. }
  19545. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19546. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  19547. /**
  19548. * @author clockworkgeek / https://github.com/clockworkgeek
  19549. * @author timothypratley / https://github.com/timothypratley
  19550. * @author WestLangley / http://github.com/WestLangley
  19551. * @author Mugen87 / https://github.com/Mugen87
  19552. */
  19553. // PolyhedronGeometry
  19554. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  19555. Geometry.call( this );
  19556. this.type = 'PolyhedronGeometry';
  19557. this.parameters = {
  19558. vertices: vertices,
  19559. indices: indices,
  19560. radius: radius,
  19561. detail: detail
  19562. };
  19563. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  19564. this.mergeVertices();
  19565. }
  19566. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  19567. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  19568. // PolyhedronBufferGeometry
  19569. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  19570. BufferGeometry.call( this );
  19571. this.type = 'PolyhedronBufferGeometry';
  19572. this.parameters = {
  19573. vertices: vertices,
  19574. indices: indices,
  19575. radius: radius,
  19576. detail: detail
  19577. };
  19578. radius = radius || 1;
  19579. detail = detail || 0;
  19580. // default buffer data
  19581. var vertexBuffer = [];
  19582. var uvBuffer = [];
  19583. // the subdivision creates the vertex buffer data
  19584. subdivide( detail );
  19585. // all vertices should lie on a conceptual sphere with a given radius
  19586. appplyRadius( radius );
  19587. // finally, create the uv data
  19588. generateUVs();
  19589. // build non-indexed geometry
  19590. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  19591. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  19592. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  19593. if ( detail === 0 ) {
  19594. this.computeVertexNormals(); // flat normals
  19595. } else {
  19596. this.normalizeNormals(); // smooth normals
  19597. }
  19598. // helper functions
  19599. function subdivide( detail ) {
  19600. var a = new Vector3();
  19601. var b = new Vector3();
  19602. var c = new Vector3();
  19603. // iterate over all faces and apply a subdivison with the given detail value
  19604. for ( var i = 0; i < indices.length; i += 3 ) {
  19605. // get the vertices of the face
  19606. getVertexByIndex( indices[ i + 0 ], a );
  19607. getVertexByIndex( indices[ i + 1 ], b );
  19608. getVertexByIndex( indices[ i + 2 ], c );
  19609. // perform subdivision
  19610. subdivideFace( a, b, c, detail );
  19611. }
  19612. }
  19613. function subdivideFace( a, b, c, detail ) {
  19614. var cols = Math.pow( 2, detail );
  19615. // we use this multidimensional array as a data structure for creating the subdivision
  19616. var v = [];
  19617. var i, j;
  19618. // construct all of the vertices for this subdivision
  19619. for ( i = 0; i <= cols; i ++ ) {
  19620. v[ i ] = [];
  19621. var aj = a.clone().lerp( c, i / cols );
  19622. var bj = b.clone().lerp( c, i / cols );
  19623. var rows = cols - i;
  19624. for ( j = 0; j <= rows; j ++ ) {
  19625. if ( j === 0 && i === cols ) {
  19626. v[ i ][ j ] = aj;
  19627. } else {
  19628. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  19629. }
  19630. }
  19631. }
  19632. // construct all of the faces
  19633. for ( i = 0; i < cols; i ++ ) {
  19634. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  19635. var k = Math.floor( j / 2 );
  19636. if ( j % 2 === 0 ) {
  19637. pushVertex( v[ i ][ k + 1 ] );
  19638. pushVertex( v[ i + 1 ][ k ] );
  19639. pushVertex( v[ i ][ k ] );
  19640. } else {
  19641. pushVertex( v[ i ][ k + 1 ] );
  19642. pushVertex( v[ i + 1 ][ k + 1 ] );
  19643. pushVertex( v[ i + 1 ][ k ] );
  19644. }
  19645. }
  19646. }
  19647. }
  19648. function appplyRadius( radius ) {
  19649. var vertex = new Vector3();
  19650. // iterate over the entire buffer and apply the radius to each vertex
  19651. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19652. vertex.x = vertexBuffer[ i + 0 ];
  19653. vertex.y = vertexBuffer[ i + 1 ];
  19654. vertex.z = vertexBuffer[ i + 2 ];
  19655. vertex.normalize().multiplyScalar( radius );
  19656. vertexBuffer[ i + 0 ] = vertex.x;
  19657. vertexBuffer[ i + 1 ] = vertex.y;
  19658. vertexBuffer[ i + 2 ] = vertex.z;
  19659. }
  19660. }
  19661. function generateUVs() {
  19662. var vertex = new Vector3();
  19663. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  19664. vertex.x = vertexBuffer[ i + 0 ];
  19665. vertex.y = vertexBuffer[ i + 1 ];
  19666. vertex.z = vertexBuffer[ i + 2 ];
  19667. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  19668. var v = inclination( vertex ) / Math.PI + 0.5;
  19669. uvBuffer.push( u, 1 - v );
  19670. }
  19671. correctUVs();
  19672. correctSeam();
  19673. }
  19674. function correctSeam() {
  19675. // handle case when face straddles the seam, see #3269
  19676. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  19677. // uv data of a single face
  19678. var x0 = uvBuffer[ i + 0 ];
  19679. var x1 = uvBuffer[ i + 2 ];
  19680. var x2 = uvBuffer[ i + 4 ];
  19681. var max = Math.max( x0, x1, x2 );
  19682. var min = Math.min( x0, x1, x2 );
  19683. // 0.9 is somewhat arbitrary
  19684. if ( max > 0.9 && min < 0.1 ) {
  19685. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  19686. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  19687. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  19688. }
  19689. }
  19690. }
  19691. function pushVertex( vertex ) {
  19692. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  19693. }
  19694. function getVertexByIndex( index, vertex ) {
  19695. var stride = index * 3;
  19696. vertex.x = vertices[ stride + 0 ];
  19697. vertex.y = vertices[ stride + 1 ];
  19698. vertex.z = vertices[ stride + 2 ];
  19699. }
  19700. function correctUVs() {
  19701. var a = new Vector3();
  19702. var b = new Vector3();
  19703. var c = new Vector3();
  19704. var centroid = new Vector3();
  19705. var uvA = new Vector2();
  19706. var uvB = new Vector2();
  19707. var uvC = new Vector2();
  19708. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  19709. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  19710. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  19711. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  19712. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  19713. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  19714. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  19715. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  19716. var azi = azimuth( centroid );
  19717. correctUV( uvA, j + 0, a, azi );
  19718. correctUV( uvB, j + 2, b, azi );
  19719. correctUV( uvC, j + 4, c, azi );
  19720. }
  19721. }
  19722. function correctUV( uv, stride, vector, azimuth ) {
  19723. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  19724. uvBuffer[ stride ] = uv.x - 1;
  19725. }
  19726. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  19727. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  19728. }
  19729. }
  19730. // Angle around the Y axis, counter-clockwise when looking from above.
  19731. function azimuth( vector ) {
  19732. return Math.atan2( vector.z, - vector.x );
  19733. }
  19734. // Angle above the XZ plane.
  19735. function inclination( vector ) {
  19736. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19737. }
  19738. }
  19739. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19740. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  19741. /**
  19742. * @author timothypratley / https://github.com/timothypratley
  19743. * @author Mugen87 / https://github.com/Mugen87
  19744. */
  19745. // TetrahedronGeometry
  19746. function TetrahedronGeometry( radius, detail ) {
  19747. Geometry.call( this );
  19748. this.type = 'TetrahedronGeometry';
  19749. this.parameters = {
  19750. radius: radius,
  19751. detail: detail
  19752. };
  19753. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  19754. this.mergeVertices();
  19755. }
  19756. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  19757. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  19758. // TetrahedronBufferGeometry
  19759. function TetrahedronBufferGeometry( radius, detail ) {
  19760. var vertices = [
  19761. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  19762. ];
  19763. var indices = [
  19764. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  19765. ];
  19766. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19767. this.type = 'TetrahedronBufferGeometry';
  19768. this.parameters = {
  19769. radius: radius,
  19770. detail: detail
  19771. };
  19772. }
  19773. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19774. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  19775. /**
  19776. * @author timothypratley / https://github.com/timothypratley
  19777. * @author Mugen87 / https://github.com/Mugen87
  19778. */
  19779. // OctahedronGeometry
  19780. function OctahedronGeometry( radius, detail ) {
  19781. Geometry.call( this );
  19782. this.type = 'OctahedronGeometry';
  19783. this.parameters = {
  19784. radius: radius,
  19785. detail: detail
  19786. };
  19787. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  19788. this.mergeVertices();
  19789. }
  19790. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  19791. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  19792. // OctahedronBufferGeometry
  19793. function OctahedronBufferGeometry( radius, detail ) {
  19794. var vertices = [
  19795. 1, 0, 0, - 1, 0, 0, 0, 1, 0,
  19796. 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  19797. ];
  19798. var indices = [
  19799. 0, 2, 4, 0, 4, 3, 0, 3, 5,
  19800. 0, 5, 2, 1, 2, 5, 1, 5, 3,
  19801. 1, 3, 4, 1, 4, 2
  19802. ];
  19803. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19804. this.type = 'OctahedronBufferGeometry';
  19805. this.parameters = {
  19806. radius: radius,
  19807. detail: detail
  19808. };
  19809. }
  19810. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19811. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  19812. /**
  19813. * @author timothypratley / https://github.com/timothypratley
  19814. * @author Mugen87 / https://github.com/Mugen87
  19815. */
  19816. // IcosahedronGeometry
  19817. function IcosahedronGeometry( radius, detail ) {
  19818. Geometry.call( this );
  19819. this.type = 'IcosahedronGeometry';
  19820. this.parameters = {
  19821. radius: radius,
  19822. detail: detail
  19823. };
  19824. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  19825. this.mergeVertices();
  19826. }
  19827. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  19828. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  19829. // IcosahedronBufferGeometry
  19830. function IcosahedronBufferGeometry( radius, detail ) {
  19831. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19832. var vertices = [
  19833. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  19834. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  19835. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  19836. ];
  19837. var indices = [
  19838. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  19839. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  19840. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  19841. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  19842. ];
  19843. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19844. this.type = 'IcosahedronBufferGeometry';
  19845. this.parameters = {
  19846. radius: radius,
  19847. detail: detail
  19848. };
  19849. }
  19850. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19851. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  19852. /**
  19853. * @author Abe Pazos / https://hamoid.com
  19854. * @author Mugen87 / https://github.com/Mugen87
  19855. */
  19856. // DodecahedronGeometry
  19857. function DodecahedronGeometry( radius, detail ) {
  19858. Geometry.call( this );
  19859. this.type = 'DodecahedronGeometry';
  19860. this.parameters = {
  19861. radius: radius,
  19862. detail: detail
  19863. };
  19864. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  19865. this.mergeVertices();
  19866. }
  19867. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  19868. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  19869. // DodecahedronBufferGeometry
  19870. function DodecahedronBufferGeometry( radius, detail ) {
  19871. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19872. var r = 1 / t;
  19873. var vertices = [
  19874. // (±1, ±1, ±1)
  19875. - 1, - 1, - 1, - 1, - 1, 1,
  19876. - 1, 1, - 1, - 1, 1, 1,
  19877. 1, - 1, - 1, 1, - 1, 1,
  19878. 1, 1, - 1, 1, 1, 1,
  19879. // (0, ±1/φ, ±φ)
  19880. 0, - r, - t, 0, - r, t,
  19881. 0, r, - t, 0, r, t,
  19882. // (±1/φ, ±φ, 0)
  19883. - r, - t, 0, - r, t, 0,
  19884. r, - t, 0, r, t, 0,
  19885. // (±φ, 0, ±1/φ)
  19886. - t, 0, - r, t, 0, - r,
  19887. - t, 0, r, t, 0, r
  19888. ];
  19889. var indices = [
  19890. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  19891. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  19892. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  19893. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  19894. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  19895. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  19896. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  19897. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  19898. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  19899. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  19900. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  19901. 1, 12, 14, 1, 14, 5, 1, 5, 9
  19902. ];
  19903. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  19904. this.type = 'DodecahedronBufferGeometry';
  19905. this.parameters = {
  19906. radius: radius,
  19907. detail: detail
  19908. };
  19909. }
  19910. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  19911. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  19912. /**
  19913. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19914. * @author WestLangley / https://github.com/WestLangley
  19915. * @author zz85 / https://github.com/zz85
  19916. * @author miningold / https://github.com/miningold
  19917. * @author jonobr1 / https://github.com/jonobr1
  19918. * @author Mugen87 / https://github.com/Mugen87
  19919. *
  19920. */
  19921. // TubeGeometry
  19922. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19923. Geometry.call( this );
  19924. this.type = 'TubeGeometry';
  19925. this.parameters = {
  19926. path: path,
  19927. tubularSegments: tubularSegments,
  19928. radius: radius,
  19929. radialSegments: radialSegments,
  19930. closed: closed
  19931. };
  19932. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19933. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19934. // expose internals
  19935. this.tangents = bufferGeometry.tangents;
  19936. this.normals = bufferGeometry.normals;
  19937. this.binormals = bufferGeometry.binormals;
  19938. // create geometry
  19939. this.fromBufferGeometry( bufferGeometry );
  19940. this.mergeVertices();
  19941. }
  19942. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19943. TubeGeometry.prototype.constructor = TubeGeometry;
  19944. // TubeBufferGeometry
  19945. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  19946. BufferGeometry.call( this );
  19947. this.type = 'TubeBufferGeometry';
  19948. this.parameters = {
  19949. path: path,
  19950. tubularSegments: tubularSegments,
  19951. radius: radius,
  19952. radialSegments: radialSegments,
  19953. closed: closed
  19954. };
  19955. tubularSegments = tubularSegments || 64;
  19956. radius = radius || 1;
  19957. radialSegments = radialSegments || 8;
  19958. closed = closed || false;
  19959. var frames = path.computeFrenetFrames( tubularSegments, closed );
  19960. // expose internals
  19961. this.tangents = frames.tangents;
  19962. this.normals = frames.normals;
  19963. this.binormals = frames.binormals;
  19964. // helper variables
  19965. var vertex = new Vector3();
  19966. var normal = new Vector3();
  19967. var uv = new Vector2();
  19968. var P = new Vector3();
  19969. var i, j;
  19970. // buffer
  19971. var vertices = [];
  19972. var normals = [];
  19973. var uvs = [];
  19974. var indices = [];
  19975. // create buffer data
  19976. generateBufferData();
  19977. // build geometry
  19978. this.setIndex( indices );
  19979. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  19980. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  19981. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  19982. // functions
  19983. function generateBufferData() {
  19984. for ( i = 0; i < tubularSegments; i ++ ) {
  19985. generateSegment( i );
  19986. }
  19987. // if the geometry is not closed, generate the last row of vertices and normals
  19988. // at the regular position on the given path
  19989. //
  19990. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  19991. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  19992. // uvs are generated in a separate function.
  19993. // this makes it easy compute correct values for closed geometries
  19994. generateUVs();
  19995. // finally create faces
  19996. generateIndices();
  19997. }
  19998. function generateSegment( i ) {
  19999. // we use getPointAt to sample evenly distributed points from the given path
  20000. P = path.getPointAt( i / tubularSegments, P );
  20001. // retrieve corresponding normal and binormal
  20002. var N = frames.normals[ i ];
  20003. var B = frames.binormals[ i ];
  20004. // generate normals and vertices for the current segment
  20005. for ( j = 0; j <= radialSegments; j ++ ) {
  20006. var v = j / radialSegments * Math.PI * 2;
  20007. var sin = Math.sin( v );
  20008. var cos = - Math.cos( v );
  20009. // normal
  20010. normal.x = ( cos * N.x + sin * B.x );
  20011. normal.y = ( cos * N.y + sin * B.y );
  20012. normal.z = ( cos * N.z + sin * B.z );
  20013. normal.normalize();
  20014. normals.push( normal.x, normal.y, normal.z );
  20015. // vertex
  20016. vertex.x = P.x + radius * normal.x;
  20017. vertex.y = P.y + radius * normal.y;
  20018. vertex.z = P.z + radius * normal.z;
  20019. vertices.push( vertex.x, vertex.y, vertex.z );
  20020. }
  20021. }
  20022. function generateIndices() {
  20023. for ( j = 1; j <= tubularSegments; j ++ ) {
  20024. for ( i = 1; i <= radialSegments; i ++ ) {
  20025. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20026. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20027. var c = ( radialSegments + 1 ) * j + i;
  20028. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20029. // faces
  20030. indices.push( a, b, d );
  20031. indices.push( b, c, d );
  20032. }
  20033. }
  20034. }
  20035. function generateUVs() {
  20036. for ( i = 0; i <= tubularSegments; i ++ ) {
  20037. for ( j = 0; j <= radialSegments; j ++ ) {
  20038. uv.x = i / tubularSegments;
  20039. uv.y = j / radialSegments;
  20040. uvs.push( uv.x, uv.y );
  20041. }
  20042. }
  20043. }
  20044. }
  20045. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20046. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  20047. /**
  20048. * @author oosmoxiecode
  20049. * @author Mugen87 / https://github.com/Mugen87
  20050. *
  20051. * based on http://www.blackpawn.com/texts/pqtorus/
  20052. */
  20053. // TorusKnotGeometry
  20054. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  20055. Geometry.call( this );
  20056. this.type = 'TorusKnotGeometry';
  20057. this.parameters = {
  20058. radius: radius,
  20059. tube: tube,
  20060. tubularSegments: tubularSegments,
  20061. radialSegments: radialSegments,
  20062. p: p,
  20063. q: q
  20064. };
  20065. if ( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  20066. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  20067. this.mergeVertices();
  20068. }
  20069. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  20070. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  20071. // TorusKnotBufferGeometry
  20072. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  20073. BufferGeometry.call( this );
  20074. this.type = 'TorusKnotBufferGeometry';
  20075. this.parameters = {
  20076. radius: radius,
  20077. tube: tube,
  20078. tubularSegments: tubularSegments,
  20079. radialSegments: radialSegments,
  20080. p: p,
  20081. q: q
  20082. };
  20083. radius = radius || 1;
  20084. tube = tube || 0.4;
  20085. tubularSegments = Math.floor( tubularSegments ) || 64;
  20086. radialSegments = Math.floor( radialSegments ) || 8;
  20087. p = p || 2;
  20088. q = q || 3;
  20089. // buffers
  20090. var indices = [];
  20091. var vertices = [];
  20092. var normals = [];
  20093. var uvs = [];
  20094. // helper variables
  20095. var i, j;
  20096. var vertex = new Vector3();
  20097. var normal = new Vector3();
  20098. var P1 = new Vector3();
  20099. var P2 = new Vector3();
  20100. var B = new Vector3();
  20101. var T = new Vector3();
  20102. var N = new Vector3();
  20103. // generate vertices, normals and uvs
  20104. for ( i = 0; i <= tubularSegments; ++ i ) {
  20105. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  20106. var u = i / tubularSegments * p * Math.PI * 2;
  20107. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  20108. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  20109. calculatePositionOnCurve( u, p, q, radius, P1 );
  20110. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  20111. // calculate orthonormal basis
  20112. T.subVectors( P2, P1 );
  20113. N.addVectors( P2, P1 );
  20114. B.crossVectors( T, N );
  20115. N.crossVectors( B, T );
  20116. // normalize B, N. T can be ignored, we don't use it
  20117. B.normalize();
  20118. N.normalize();
  20119. for ( j = 0; j <= radialSegments; ++ j ) {
  20120. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  20121. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  20122. var v = j / radialSegments * Math.PI * 2;
  20123. var cx = - tube * Math.cos( v );
  20124. var cy = tube * Math.sin( v );
  20125. // now calculate the final vertex position.
  20126. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  20127. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  20128. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  20129. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  20130. vertices.push( vertex.x, vertex.y, vertex.z );
  20131. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  20132. normal.subVectors( vertex, P1 ).normalize();
  20133. normals.push( normal.x, normal.y, normal.z );
  20134. // uv
  20135. uvs.push( i / tubularSegments );
  20136. uvs.push( j / radialSegments );
  20137. }
  20138. }
  20139. // generate indices
  20140. for ( j = 1; j <= tubularSegments; j ++ ) {
  20141. for ( i = 1; i <= radialSegments; i ++ ) {
  20142. // indices
  20143. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  20144. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  20145. var c = ( radialSegments + 1 ) * j + i;
  20146. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  20147. // faces
  20148. indices.push( a, b, d );
  20149. indices.push( b, c, d );
  20150. }
  20151. }
  20152. // build geometry
  20153. this.setIndex( indices );
  20154. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20155. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20156. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20157. // this function calculates the current position on the torus curve
  20158. function calculatePositionOnCurve( u, p, q, radius, position ) {
  20159. var cu = Math.cos( u );
  20160. var su = Math.sin( u );
  20161. var quOverP = q / p * u;
  20162. var cs = Math.cos( quOverP );
  20163. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  20164. position.y = radius * ( 2 + cs ) * su * 0.5;
  20165. position.z = radius * Math.sin( quOverP ) * 0.5;
  20166. }
  20167. }
  20168. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20169. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  20170. /**
  20171. * @author oosmoxiecode
  20172. * @author mrdoob / http://mrdoob.com/
  20173. * @author Mugen87 / https://github.com/Mugen87
  20174. */
  20175. // TorusGeometry
  20176. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20177. Geometry.call( this );
  20178. this.type = 'TorusGeometry';
  20179. this.parameters = {
  20180. radius: radius,
  20181. tube: tube,
  20182. radialSegments: radialSegments,
  20183. tubularSegments: tubularSegments,
  20184. arc: arc
  20185. };
  20186. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  20187. this.mergeVertices();
  20188. }
  20189. TorusGeometry.prototype = Object.create( Geometry.prototype );
  20190. TorusGeometry.prototype.constructor = TorusGeometry;
  20191. // TorusBufferGeometry
  20192. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  20193. BufferGeometry.call( this );
  20194. this.type = 'TorusBufferGeometry';
  20195. this.parameters = {
  20196. radius: radius,
  20197. tube: tube,
  20198. radialSegments: radialSegments,
  20199. tubularSegments: tubularSegments,
  20200. arc: arc
  20201. };
  20202. radius = radius || 1;
  20203. tube = tube || 0.4;
  20204. radialSegments = Math.floor( radialSegments ) || 8;
  20205. tubularSegments = Math.floor( tubularSegments ) || 6;
  20206. arc = arc || Math.PI * 2;
  20207. // buffers
  20208. var indices = [];
  20209. var vertices = [];
  20210. var normals = [];
  20211. var uvs = [];
  20212. // helper variables
  20213. var center = new Vector3();
  20214. var vertex = new Vector3();
  20215. var normal = new Vector3();
  20216. var j, i;
  20217. // generate vertices, normals and uvs
  20218. for ( j = 0; j <= radialSegments; j ++ ) {
  20219. for ( i = 0; i <= tubularSegments; i ++ ) {
  20220. var u = i / tubularSegments * arc;
  20221. var v = j / radialSegments * Math.PI * 2;
  20222. // vertex
  20223. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20224. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20225. vertex.z = tube * Math.sin( v );
  20226. vertices.push( vertex.x, vertex.y, vertex.z );
  20227. // normal
  20228. center.x = radius * Math.cos( u );
  20229. center.y = radius * Math.sin( u );
  20230. normal.subVectors( vertex, center ).normalize();
  20231. normals.push( normal.x, normal.y, normal.z );
  20232. // uv
  20233. uvs.push( i / tubularSegments );
  20234. uvs.push( j / radialSegments );
  20235. }
  20236. }
  20237. // generate indices
  20238. for ( j = 1; j <= radialSegments; j ++ ) {
  20239. for ( i = 1; i <= tubularSegments; i ++ ) {
  20240. // indices
  20241. var a = ( tubularSegments + 1 ) * j + i - 1;
  20242. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20243. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20244. var d = ( tubularSegments + 1 ) * j + i;
  20245. // faces
  20246. indices.push( a, b, d );
  20247. indices.push( b, c, d );
  20248. }
  20249. }
  20250. // build geometry
  20251. this.setIndex( indices );
  20252. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20253. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20254. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20255. }
  20256. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20257. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  20258. /**
  20259. * @author Mugen87 / https://github.com/Mugen87
  20260. * Port from https://github.com/mapbox/earcut (v2.1.2)
  20261. */
  20262. var Earcut = {
  20263. triangulate: function ( data, holeIndices, dim ) {
  20264. dim = dim || 2;
  20265. var hasHoles = holeIndices && holeIndices.length,
  20266. outerLen = hasHoles ? holeIndices[ 0 ] * dim : data.length,
  20267. outerNode = linkedList( data, 0, outerLen, dim, true ),
  20268. triangles = [];
  20269. if ( ! outerNode ) return triangles;
  20270. var minX, minY, maxX, maxY, x, y, invSize;
  20271. if ( hasHoles ) outerNode = eliminateHoles( data, holeIndices, outerNode, dim );
  20272. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  20273. if ( data.length > 80 * dim ) {
  20274. minX = maxX = data[ 0 ];
  20275. minY = maxY = data[ 1 ];
  20276. for ( var i = dim; i < outerLen; i += dim ) {
  20277. x = data[ i ];
  20278. y = data[ i + 1 ];
  20279. if ( x < minX ) minX = x;
  20280. if ( y < minY ) minY = y;
  20281. if ( x > maxX ) maxX = x;
  20282. if ( y > maxY ) maxY = y;
  20283. }
  20284. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  20285. invSize = Math.max( maxX - minX, maxY - minY );
  20286. invSize = invSize !== 0 ? 1 / invSize : 0;
  20287. }
  20288. earcutLinked( outerNode, triangles, dim, minX, minY, invSize );
  20289. return triangles;
  20290. }
  20291. };
  20292. // create a circular doubly linked list from polygon points in the specified winding order
  20293. function linkedList( data, start, end, dim, clockwise ) {
  20294. var i, last;
  20295. if ( clockwise === ( signedArea( data, start, end, dim ) > 0 ) ) {
  20296. for ( i = start; i < end; i += dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20297. } else {
  20298. for ( i = end - dim; i >= start; i -= dim ) last = insertNode( i, data[ i ], data[ i + 1 ], last );
  20299. }
  20300. if ( last && equals( last, last.next ) ) {
  20301. removeNode( last );
  20302. last = last.next;
  20303. }
  20304. return last;
  20305. }
  20306. // eliminate colinear or duplicate points
  20307. function filterPoints( start, end ) {
  20308. if ( ! start ) return start;
  20309. if ( ! end ) end = start;
  20310. var p = start, again;
  20311. do {
  20312. again = false;
  20313. if ( ! p.steiner && ( equals( p, p.next ) || area( p.prev, p, p.next ) === 0 ) ) {
  20314. removeNode( p );
  20315. p = end = p.prev;
  20316. if ( p === p.next ) break;
  20317. again = true;
  20318. } else {
  20319. p = p.next;
  20320. }
  20321. } while ( again || p !== end );
  20322. return end;
  20323. }
  20324. // main ear slicing loop which triangulates a polygon (given as a linked list)
  20325. function earcutLinked( ear, triangles, dim, minX, minY, invSize, pass ) {
  20326. if ( ! ear ) return;
  20327. // interlink polygon nodes in z-order
  20328. if ( ! pass && invSize ) indexCurve( ear, minX, minY, invSize );
  20329. var stop = ear, prev, next;
  20330. // iterate through ears, slicing them one by one
  20331. while ( ear.prev !== ear.next ) {
  20332. prev = ear.prev;
  20333. next = ear.next;
  20334. if ( invSize ? isEarHashed( ear, minX, minY, invSize ) : isEar( ear ) ) {
  20335. // cut off the triangle
  20336. triangles.push( prev.i / dim );
  20337. triangles.push( ear.i / dim );
  20338. triangles.push( next.i / dim );
  20339. removeNode( ear );
  20340. // skipping the next vertice leads to less sliver triangles
  20341. ear = next.next;
  20342. stop = next.next;
  20343. continue;
  20344. }
  20345. ear = next;
  20346. // if we looped through the whole remaining polygon and can't find any more ears
  20347. if ( ear === stop ) {
  20348. // try filtering points and slicing again
  20349. if ( ! pass ) {
  20350. earcutLinked( filterPoints( ear ), triangles, dim, minX, minY, invSize, 1 );
  20351. // if this didn't work, try curing all small self-intersections locally
  20352. } else if ( pass === 1 ) {
  20353. ear = cureLocalIntersections( ear, triangles, dim );
  20354. earcutLinked( ear, triangles, dim, minX, minY, invSize, 2 );
  20355. // as a last resort, try splitting the remaining polygon into two
  20356. } else if ( pass === 2 ) {
  20357. splitEarcut( ear, triangles, dim, minX, minY, invSize );
  20358. }
  20359. break;
  20360. }
  20361. }
  20362. }
  20363. // check whether a polygon node forms a valid ear with adjacent nodes
  20364. function isEar( ear ) {
  20365. var a = ear.prev,
  20366. b = ear,
  20367. c = ear.next;
  20368. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20369. // now make sure we don't have other points inside the potential ear
  20370. var p = ear.next.next;
  20371. while ( p !== ear.prev ) {
  20372. 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 ) {
  20373. return false;
  20374. }
  20375. p = p.next;
  20376. }
  20377. return true;
  20378. }
  20379. function isEarHashed( ear, minX, minY, invSize ) {
  20380. var a = ear.prev,
  20381. b = ear,
  20382. c = ear.next;
  20383. if ( area( a, b, c ) >= 0 ) return false; // reflex, can't be an ear
  20384. // triangle bbox; min & max are calculated like this for speed
  20385. var minTX = a.x < b.x ? ( a.x < c.x ? a.x : c.x ) : ( b.x < c.x ? b.x : c.x ),
  20386. minTY = a.y < b.y ? ( a.y < c.y ? a.y : c.y ) : ( b.y < c.y ? b.y : c.y ),
  20387. maxTX = a.x > b.x ? ( a.x > c.x ? a.x : c.x ) : ( b.x > c.x ? b.x : c.x ),
  20388. maxTY = a.y > b.y ? ( a.y > c.y ? a.y : c.y ) : ( b.y > c.y ? b.y : c.y );
  20389. // z-order range for the current triangle bbox;
  20390. var minZ = zOrder( minTX, minTY, minX, minY, invSize ),
  20391. maxZ = zOrder( maxTX, maxTY, minX, minY, invSize );
  20392. // first look for points inside the triangle in increasing z-order
  20393. var p = ear.nextZ;
  20394. while ( p && p.z <= maxZ ) {
  20395. if ( p !== ear.prev && p !== ear.next &&
  20396. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20397. area( p.prev, p, p.next ) >= 0 ) return false;
  20398. p = p.nextZ;
  20399. }
  20400. // then look for points in decreasing z-order
  20401. p = ear.prevZ;
  20402. while ( p && p.z >= minZ ) {
  20403. if ( p !== ear.prev && p !== ear.next &&
  20404. pointInTriangle( a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y ) &&
  20405. area( p.prev, p, p.next ) >= 0 ) return false;
  20406. p = p.prevZ;
  20407. }
  20408. return true;
  20409. }
  20410. // go through all polygon nodes and cure small local self-intersections
  20411. function cureLocalIntersections( start, triangles, dim ) {
  20412. var p = start;
  20413. do {
  20414. var a = p.prev, b = p.next.next;
  20415. if ( ! equals( a, b ) && intersects( a, p, p.next, b ) && locallyInside( a, b ) && locallyInside( b, a ) ) {
  20416. triangles.push( a.i / dim );
  20417. triangles.push( p.i / dim );
  20418. triangles.push( b.i / dim );
  20419. // remove two nodes involved
  20420. removeNode( p );
  20421. removeNode( p.next );
  20422. p = start = b;
  20423. }
  20424. p = p.next;
  20425. } while ( p !== start );
  20426. return p;
  20427. }
  20428. // try splitting polygon into two and triangulate them independently
  20429. function splitEarcut( start, triangles, dim, minX, minY, invSize ) {
  20430. // look for a valid diagonal that divides the polygon into two
  20431. var a = start;
  20432. do {
  20433. var b = a.next.next;
  20434. while ( b !== a.prev ) {
  20435. if ( a.i !== b.i && isValidDiagonal( a, b ) ) {
  20436. // split the polygon in two by the diagonal
  20437. var c = splitPolygon( a, b );
  20438. // filter colinear points around the cuts
  20439. a = filterPoints( a, a.next );
  20440. c = filterPoints( c, c.next );
  20441. // run earcut on each half
  20442. earcutLinked( a, triangles, dim, minX, minY, invSize );
  20443. earcutLinked( c, triangles, dim, minX, minY, invSize );
  20444. return;
  20445. }
  20446. b = b.next;
  20447. }
  20448. a = a.next;
  20449. } while ( a !== start );
  20450. }
  20451. // link every hole into the outer loop, producing a single-ring polygon without holes
  20452. function eliminateHoles( data, holeIndices, outerNode, dim ) {
  20453. var queue = [], i, len, start, end, list;
  20454. for ( i = 0, len = holeIndices.length; i < len; i ++ ) {
  20455. start = holeIndices[ i ] * dim;
  20456. end = i < len - 1 ? holeIndices[ i + 1 ] * dim : data.length;
  20457. list = linkedList( data, start, end, dim, false );
  20458. if ( list === list.next ) list.steiner = true;
  20459. queue.push( getLeftmost( list ) );
  20460. }
  20461. queue.sort( compareX );
  20462. // process holes from left to right
  20463. for ( i = 0; i < queue.length; i ++ ) {
  20464. eliminateHole( queue[ i ], outerNode );
  20465. outerNode = filterPoints( outerNode, outerNode.next );
  20466. }
  20467. return outerNode;
  20468. }
  20469. function compareX( a, b ) {
  20470. return a.x - b.x;
  20471. }
  20472. // find a bridge between vertices that connects hole with an outer ring and and link it
  20473. function eliminateHole( hole, outerNode ) {
  20474. outerNode = findHoleBridge( hole, outerNode );
  20475. if ( outerNode ) {
  20476. var b = splitPolygon( outerNode, hole );
  20477. filterPoints( b, b.next );
  20478. }
  20479. }
  20480. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  20481. function findHoleBridge( hole, outerNode ) {
  20482. var p = outerNode,
  20483. hx = hole.x,
  20484. hy = hole.y,
  20485. qx = - Infinity,
  20486. m;
  20487. // find a segment intersected by a ray from the hole's leftmost point to the left;
  20488. // segment's endpoint with lesser x will be potential connection point
  20489. do {
  20490. if ( hy <= p.y && hy >= p.next.y && p.next.y !== p.y ) {
  20491. var x = p.x + ( hy - p.y ) * ( p.next.x - p.x ) / ( p.next.y - p.y );
  20492. if ( x <= hx && x > qx ) {
  20493. qx = x;
  20494. if ( x === hx ) {
  20495. if ( hy === p.y ) return p;
  20496. if ( hy === p.next.y ) return p.next;
  20497. }
  20498. m = p.x < p.next.x ? p : p.next;
  20499. }
  20500. }
  20501. p = p.next;
  20502. } while ( p !== outerNode );
  20503. if ( ! m ) return null;
  20504. if ( hx === qx ) return m.prev; // hole touches outer segment; pick lower endpoint
  20505. // look for points inside the triangle of hole point, segment intersection and endpoint;
  20506. // if there are no points found, we have a valid connection;
  20507. // otherwise choose the point of the minimum angle with the ray as connection point
  20508. var stop = m,
  20509. mx = m.x,
  20510. my = m.y,
  20511. tanMin = Infinity,
  20512. tan;
  20513. p = m.next;
  20514. while ( p !== stop ) {
  20515. if ( hx >= p.x && p.x >= mx && hx !== p.x &&
  20516. pointInTriangle( hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y ) ) {
  20517. tan = Math.abs( hy - p.y ) / ( hx - p.x ); // tangential
  20518. if ( ( tan < tanMin || ( tan === tanMin && p.x > m.x ) ) && locallyInside( p, hole ) ) {
  20519. m = p;
  20520. tanMin = tan;
  20521. }
  20522. }
  20523. p = p.next;
  20524. }
  20525. return m;
  20526. }
  20527. // interlink polygon nodes in z-order
  20528. function indexCurve( start, minX, minY, invSize ) {
  20529. var p = start;
  20530. do {
  20531. if ( p.z === null ) p.z = zOrder( p.x, p.y, minX, minY, invSize );
  20532. p.prevZ = p.prev;
  20533. p.nextZ = p.next;
  20534. p = p.next;
  20535. } while ( p !== start );
  20536. p.prevZ.nextZ = null;
  20537. p.prevZ = null;
  20538. sortLinked( p );
  20539. }
  20540. // Simon Tatham's linked list merge sort algorithm
  20541. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  20542. function sortLinked( list ) {
  20543. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  20544. do {
  20545. p = list;
  20546. list = null;
  20547. tail = null;
  20548. numMerges = 0;
  20549. while ( p ) {
  20550. numMerges ++;
  20551. q = p;
  20552. pSize = 0;
  20553. for ( i = 0; i < inSize; i ++ ) {
  20554. pSize ++;
  20555. q = q.nextZ;
  20556. if ( ! q ) break;
  20557. }
  20558. qSize = inSize;
  20559. while ( pSize > 0 || ( qSize > 0 && q ) ) {
  20560. if ( pSize !== 0 && ( qSize === 0 || ! q || p.z <= q.z ) ) {
  20561. e = p;
  20562. p = p.nextZ;
  20563. pSize --;
  20564. } else {
  20565. e = q;
  20566. q = q.nextZ;
  20567. qSize --;
  20568. }
  20569. if ( tail ) tail.nextZ = e;
  20570. else list = e;
  20571. e.prevZ = tail;
  20572. tail = e;
  20573. }
  20574. p = q;
  20575. }
  20576. tail.nextZ = null;
  20577. inSize *= 2;
  20578. } while ( numMerges > 1 );
  20579. return list;
  20580. }
  20581. // z-order of a point given coords and inverse of the longer side of data bbox
  20582. function zOrder( x, y, minX, minY, invSize ) {
  20583. // coords are transformed into non-negative 15-bit integer range
  20584. x = 32767 * ( x - minX ) * invSize;
  20585. y = 32767 * ( y - minY ) * invSize;
  20586. x = ( x | ( x << 8 ) ) & 0x00FF00FF;
  20587. x = ( x | ( x << 4 ) ) & 0x0F0F0F0F;
  20588. x = ( x | ( x << 2 ) ) & 0x33333333;
  20589. x = ( x | ( x << 1 ) ) & 0x55555555;
  20590. y = ( y | ( y << 8 ) ) & 0x00FF00FF;
  20591. y = ( y | ( y << 4 ) ) & 0x0F0F0F0F;
  20592. y = ( y | ( y << 2 ) ) & 0x33333333;
  20593. y = ( y | ( y << 1 ) ) & 0x55555555;
  20594. return x | ( y << 1 );
  20595. }
  20596. // find the leftmost node of a polygon ring
  20597. function getLeftmost( start ) {
  20598. var p = start, leftmost = start;
  20599. do {
  20600. if ( p.x < leftmost.x ) leftmost = p;
  20601. p = p.next;
  20602. } while ( p !== start );
  20603. return leftmost;
  20604. }
  20605. // check if a point lies within a convex triangle
  20606. function pointInTriangle( ax, ay, bx, by, cx, cy, px, py ) {
  20607. return ( cx - px ) * ( ay - py ) - ( ax - px ) * ( cy - py ) >= 0 &&
  20608. ( ax - px ) * ( by - py ) - ( bx - px ) * ( ay - py ) >= 0 &&
  20609. ( bx - px ) * ( cy - py ) - ( cx - px ) * ( by - py ) >= 0;
  20610. }
  20611. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  20612. function isValidDiagonal( a, b ) {
  20613. return a.next.i !== b.i && a.prev.i !== b.i && ! intersectsPolygon( a, b ) &&
  20614. locallyInside( a, b ) && locallyInside( b, a ) && middleInside( a, b );
  20615. }
  20616. // signed area of a triangle
  20617. function area( p, q, r ) {
  20618. return ( q.y - p.y ) * ( r.x - q.x ) - ( q.x - p.x ) * ( r.y - q.y );
  20619. }
  20620. // check if two points are equal
  20621. function equals( p1, p2 ) {
  20622. return p1.x === p2.x && p1.y === p2.y;
  20623. }
  20624. // check if two segments intersect
  20625. function intersects( p1, q1, p2, q2 ) {
  20626. if ( ( equals( p1, q1 ) && equals( p2, q2 ) ) ||
  20627. ( equals( p1, q2 ) && equals( p2, q1 ) ) ) return true;
  20628. return area( p1, q1, p2 ) > 0 !== area( p1, q1, q2 ) > 0 &&
  20629. area( p2, q2, p1 ) > 0 !== area( p2, q2, q1 ) > 0;
  20630. }
  20631. // check if a polygon diagonal intersects any polygon segments
  20632. function intersectsPolygon( a, b ) {
  20633. var p = a;
  20634. do {
  20635. if ( p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  20636. intersects( p, p.next, a, b ) ) {
  20637. return true;
  20638. }
  20639. p = p.next;
  20640. } while ( p !== a );
  20641. return false;
  20642. }
  20643. // check if a polygon diagonal is locally inside the polygon
  20644. function locallyInside( a, b ) {
  20645. return area( a.prev, a, a.next ) < 0 ?
  20646. area( a, b, a.next ) >= 0 && area( a, a.prev, b ) >= 0 :
  20647. area( a, b, a.prev ) < 0 || area( a, a.next, b ) < 0;
  20648. }
  20649. // check if the middle point of a polygon diagonal is inside the polygon
  20650. function middleInside( a, b ) {
  20651. var p = a,
  20652. inside = false,
  20653. px = ( a.x + b.x ) / 2,
  20654. py = ( a.y + b.y ) / 2;
  20655. do {
  20656. if ( ( ( p.y > py ) !== ( p.next.y > py ) ) && p.next.y !== p.y &&
  20657. ( px < ( p.next.x - p.x ) * ( py - p.y ) / ( p.next.y - p.y ) + p.x ) ) {
  20658. inside = ! inside;
  20659. }
  20660. p = p.next;
  20661. } while ( p !== a );
  20662. return inside;
  20663. }
  20664. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  20665. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  20666. function splitPolygon( a, b ) {
  20667. var a2 = new Node( a.i, a.x, a.y ),
  20668. b2 = new Node( b.i, b.x, b.y ),
  20669. an = a.next,
  20670. bp = b.prev;
  20671. a.next = b;
  20672. b.prev = a;
  20673. a2.next = an;
  20674. an.prev = a2;
  20675. b2.next = a2;
  20676. a2.prev = b2;
  20677. bp.next = b2;
  20678. b2.prev = bp;
  20679. return b2;
  20680. }
  20681. // create a node and optionally link it with previous one (in a circular doubly linked list)
  20682. function insertNode( i, x, y, last ) {
  20683. var p = new Node( i, x, y );
  20684. if ( ! last ) {
  20685. p.prev = p;
  20686. p.next = p;
  20687. } else {
  20688. p.next = last.next;
  20689. p.prev = last;
  20690. last.next.prev = p;
  20691. last.next = p;
  20692. }
  20693. return p;
  20694. }
  20695. function removeNode( p ) {
  20696. p.next.prev = p.prev;
  20697. p.prev.next = p.next;
  20698. if ( p.prevZ ) p.prevZ.nextZ = p.nextZ;
  20699. if ( p.nextZ ) p.nextZ.prevZ = p.prevZ;
  20700. }
  20701. function Node( i, x, y ) {
  20702. // vertice index in coordinates array
  20703. this.i = i;
  20704. // vertex coordinates
  20705. this.x = x;
  20706. this.y = y;
  20707. // previous and next vertice nodes in a polygon ring
  20708. this.prev = null;
  20709. this.next = null;
  20710. // z-order curve value
  20711. this.z = null;
  20712. // previous and next nodes in z-order
  20713. this.prevZ = null;
  20714. this.nextZ = null;
  20715. // indicates whether this is a steiner point
  20716. this.steiner = false;
  20717. }
  20718. function signedArea( data, start, end, dim ) {
  20719. var sum = 0;
  20720. for ( var i = start, j = end - dim; i < end; i += dim ) {
  20721. sum += ( data[ j ] - data[ i ] ) * ( data[ i + 1 ] + data[ j + 1 ] );
  20722. j = i;
  20723. }
  20724. return sum;
  20725. }
  20726. /**
  20727. * @author zz85 / http://www.lab4games.net/zz85/blog
  20728. */
  20729. var ShapeUtils = {
  20730. // calculate area of the contour polygon
  20731. area: function ( contour ) {
  20732. var n = contour.length;
  20733. var a = 0.0;
  20734. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  20735. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  20736. }
  20737. return a * 0.5;
  20738. },
  20739. isClockWise: function ( pts ) {
  20740. return ShapeUtils.area( pts ) < 0;
  20741. },
  20742. triangulateShape: function ( contour, holes ) {
  20743. function removeDupEndPts( points ) {
  20744. var l = points.length;
  20745. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  20746. points.pop();
  20747. }
  20748. }
  20749. function addContour( vertices, contour ) {
  20750. for ( var i = 0; i < contour.length; i ++ ) {
  20751. vertices.push( contour[ i ].x );
  20752. vertices.push( contour[ i ].y );
  20753. }
  20754. }
  20755. var vertices = []; // flat array of vertices like [ x0,y0, x1,y1, x2,y2, ... ]
  20756. var holeIndices = []; // array of hole indices
  20757. var faces = []; // final array of vertex indices like [ [ a,b,d ], [ b,c,d ] ]
  20758. removeDupEndPts( contour );
  20759. addContour( vertices, contour );
  20760. //
  20761. var holeIndex = contour.length;
  20762. holes.forEach( removeDupEndPts );
  20763. for ( i = 0; i < holes.length; i ++ ) {
  20764. holeIndices.push( holeIndex );
  20765. holeIndex += holes[ i ].length;
  20766. addContour( vertices, holes[ i ] );
  20767. }
  20768. //
  20769. var triangles = Earcut.triangulate( vertices, holeIndices );
  20770. //
  20771. for ( var i = 0; i < triangles.length; i += 3 ) {
  20772. faces.push( triangles.slice( i, i + 3 ) );
  20773. }
  20774. return faces;
  20775. }
  20776. };
  20777. /**
  20778. * @author zz85 / http://www.lab4games.net/zz85/blog
  20779. *
  20780. * Creates extruded geometry from a path shape.
  20781. *
  20782. * parameters = {
  20783. *
  20784. * curveSegments: <int>, // number of points on the curves
  20785. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  20786. * amount: <int>, // Depth to extrude the shape
  20787. *
  20788. * bevelEnabled: <bool>, // turn on bevel
  20789. * bevelThickness: <float>, // how deep into the original shape bevel goes
  20790. * bevelSize: <float>, // how far from shape outline is bevel
  20791. * bevelSegments: <int>, // number of bevel layers
  20792. *
  20793. * extrudePath: <THREE.Curve> // curve to extrude shape along
  20794. * frames: <Object> // containing arrays of tangents, normals, binormals
  20795. *
  20796. * UVGenerator: <Object> // object that provides UV generator functions
  20797. *
  20798. * }
  20799. */
  20800. // ExtrudeGeometry
  20801. function ExtrudeGeometry( shapes, options ) {
  20802. Geometry.call( this );
  20803. this.type = 'ExtrudeGeometry';
  20804. this.parameters = {
  20805. shapes: shapes,
  20806. options: options
  20807. };
  20808. this.fromBufferGeometry( new ExtrudeBufferGeometry( shapes, options ) );
  20809. this.mergeVertices();
  20810. }
  20811. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  20812. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  20813. // ExtrudeBufferGeometry
  20814. function ExtrudeBufferGeometry( shapes, options ) {
  20815. if ( typeof ( shapes ) === "undefined" ) {
  20816. return;
  20817. }
  20818. BufferGeometry.call( this );
  20819. this.type = 'ExtrudeBufferGeometry';
  20820. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  20821. this.addShapeList( shapes, options );
  20822. this.computeVertexNormals();
  20823. // can't really use automatic vertex normals
  20824. // as then front and back sides get smoothed too
  20825. // should do separate smoothing just for sides
  20826. //this.computeVertexNormals();
  20827. //console.log( "took", ( Date.now() - startTime ) );
  20828. }
  20829. ExtrudeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20830. ExtrudeBufferGeometry.prototype.constructor = ExtrudeBufferGeometry;
  20831. ExtrudeBufferGeometry.prototype.getArrays = function () {
  20832. var positionAttribute = this.getAttribute( "position" );
  20833. var verticesArray = positionAttribute ? Array.prototype.slice.call( positionAttribute.array ) : [];
  20834. var uvAttribute = this.getAttribute( "uv" );
  20835. var uvArray = uvAttribute ? Array.prototype.slice.call( uvAttribute.array ) : [];
  20836. var IndexAttribute = this.index;
  20837. var indicesArray = IndexAttribute ? Array.prototype.slice.call( IndexAttribute.array ) : [];
  20838. return {
  20839. position: verticesArray,
  20840. uv: uvArray,
  20841. index: indicesArray
  20842. };
  20843. };
  20844. ExtrudeBufferGeometry.prototype.addShapeList = function ( shapes, options ) {
  20845. var sl = shapes.length;
  20846. options.arrays = this.getArrays();
  20847. for ( var s = 0; s < sl; s ++ ) {
  20848. var shape = shapes[ s ];
  20849. this.addShape( shape, options );
  20850. }
  20851. this.setIndex( options.arrays.index );
  20852. this.addAttribute( 'position', new Float32BufferAttribute( options.arrays.position, 3 ) );
  20853. this.addAttribute( 'uv', new Float32BufferAttribute( options.arrays.uv, 2 ) );
  20854. };
  20855. ExtrudeBufferGeometry.prototype.addShape = function ( shape, options ) {
  20856. var arrays = options.arrays ? options.arrays : this.getArrays();
  20857. var verticesArray = arrays.position;
  20858. var indicesArray = arrays.index;
  20859. var uvArray = arrays.uv;
  20860. var placeholder = [];
  20861. var amount = options.amount !== undefined ? options.amount : 100;
  20862. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  20863. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  20864. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  20865. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  20866. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20867. var steps = options.steps !== undefined ? options.steps : 1;
  20868. var extrudePath = options.extrudePath;
  20869. var extrudePts, extrudeByPath = false;
  20870. // Use default WorldUVGenerator if no UV generators are specified.
  20871. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  20872. var splineTube, binormal, normal, position2;
  20873. if ( extrudePath ) {
  20874. extrudePts = extrudePath.getSpacedPoints( steps );
  20875. extrudeByPath = true;
  20876. bevelEnabled = false; // bevels not supported for path extrusion
  20877. // SETUP TNB variables
  20878. // TODO1 - have a .isClosed in spline?
  20879. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  20880. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  20881. binormal = new Vector3();
  20882. normal = new Vector3();
  20883. position2 = new Vector3();
  20884. }
  20885. // Safeguards if bevels are not enabled
  20886. if ( ! bevelEnabled ) {
  20887. bevelSegments = 0;
  20888. bevelThickness = 0;
  20889. bevelSize = 0;
  20890. }
  20891. // Variables initialization
  20892. var ahole, h, hl; // looping of holes
  20893. var scope = this;
  20894. var shapePoints = shape.extractPoints( curveSegments );
  20895. var vertices = shapePoints.shape;
  20896. var holes = shapePoints.holes;
  20897. var reverse = ! ShapeUtils.isClockWise( vertices );
  20898. if ( reverse ) {
  20899. vertices = vertices.reverse();
  20900. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  20901. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20902. ahole = holes[ h ];
  20903. if ( ShapeUtils.isClockWise( ahole ) ) {
  20904. holes[ h ] = ahole.reverse();
  20905. }
  20906. }
  20907. }
  20908. var faces = ShapeUtils.triangulateShape( vertices, holes );
  20909. /* Vertices */
  20910. var contour = vertices; // vertices has all points but contour has only points of circumference
  20911. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20912. ahole = holes[ h ];
  20913. vertices = vertices.concat( ahole );
  20914. }
  20915. function scalePt2( pt, vec, size ) {
  20916. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  20917. return vec.clone().multiplyScalar( size ).add( pt );
  20918. }
  20919. var b, bs, t, z,
  20920. vert, vlen = vertices.length,
  20921. face, flen = faces.length;
  20922. // Find directions for point movement
  20923. function getBevelVec( inPt, inPrev, inNext ) {
  20924. // computes for inPt the corresponding point inPt' on a new contour
  20925. // shifted by 1 unit (length of normalized vector) to the left
  20926. // if we walk along contour clockwise, this new contour is outside the old one
  20927. //
  20928. // inPt' is the intersection of the two lines parallel to the two
  20929. // adjacent edges of inPt at a distance of 1 unit on the left side.
  20930. var v_trans_x, v_trans_y, shrink_by; // resulting translation vector for inPt
  20931. // good reading for geometry algorithms (here: line-line intersection)
  20932. // http://geomalgorithms.com/a05-_intersect-1.html
  20933. var v_prev_x = inPt.x - inPrev.x,
  20934. v_prev_y = inPt.y - inPrev.y;
  20935. var v_next_x = inNext.x - inPt.x,
  20936. v_next_y = inNext.y - inPt.y;
  20937. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  20938. // check for collinear edges
  20939. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20940. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  20941. // not collinear
  20942. // length of vectors for normalizing
  20943. var v_prev_len = Math.sqrt( v_prev_lensq );
  20944. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  20945. // shift adjacent points by unit vectors to the left
  20946. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  20947. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  20948. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  20949. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  20950. // scaling factor for v_prev to intersection point
  20951. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  20952. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  20953. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  20954. // vector from inPt to intersection point
  20955. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  20956. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  20957. // Don't normalize!, otherwise sharp corners become ugly
  20958. // but prevent crazy spikes
  20959. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  20960. if ( v_trans_lensq <= 2 ) {
  20961. return new Vector2( v_trans_x, v_trans_y );
  20962. } else {
  20963. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  20964. }
  20965. } else {
  20966. // handle special case of collinear edges
  20967. var direction_eq = false; // assumes: opposite
  20968. if ( v_prev_x > Number.EPSILON ) {
  20969. if ( v_next_x > Number.EPSILON ) {
  20970. direction_eq = true;
  20971. }
  20972. } else {
  20973. if ( v_prev_x < - Number.EPSILON ) {
  20974. if ( v_next_x < - Number.EPSILON ) {
  20975. direction_eq = true;
  20976. }
  20977. } else {
  20978. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  20979. direction_eq = true;
  20980. }
  20981. }
  20982. }
  20983. if ( direction_eq ) {
  20984. // console.log("Warning: lines are a straight sequence");
  20985. v_trans_x = - v_prev_y;
  20986. v_trans_y = v_prev_x;
  20987. shrink_by = Math.sqrt( v_prev_lensq );
  20988. } else {
  20989. // console.log("Warning: lines are a straight spike");
  20990. v_trans_x = v_prev_x;
  20991. v_trans_y = v_prev_y;
  20992. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  20993. }
  20994. }
  20995. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  20996. }
  20997. var contourMovements = [];
  20998. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  20999. if ( j === il ) j = 0;
  21000. if ( k === il ) k = 0;
  21001. // (j)---(i)---(k)
  21002. // console.log('i,j,k', i, j , k)
  21003. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  21004. }
  21005. var holesMovements = [],
  21006. oneHoleMovements, verticesMovements = contourMovements.concat();
  21007. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21008. ahole = holes[ h ];
  21009. oneHoleMovements = [];
  21010. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  21011. if ( j === il ) j = 0;
  21012. if ( k === il ) k = 0;
  21013. // (j)---(i)---(k)
  21014. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  21015. }
  21016. holesMovements.push( oneHoleMovements );
  21017. verticesMovements = verticesMovements.concat( oneHoleMovements );
  21018. }
  21019. // Loop bevelSegments, 1 for the front, 1 for the back
  21020. for ( b = 0; b < bevelSegments; b ++ ) {
  21021. //for ( b = bevelSegments; b > 0; b -- ) {
  21022. t = b / bevelSegments;
  21023. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21024. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21025. // contract shape
  21026. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21027. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21028. v( vert.x, vert.y, - z );
  21029. }
  21030. // expand holes
  21031. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21032. ahole = holes[ h ];
  21033. oneHoleMovements = holesMovements[ h ];
  21034. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21035. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21036. v( vert.x, vert.y, - z );
  21037. }
  21038. }
  21039. }
  21040. bs = bevelSize;
  21041. // Back facing vertices
  21042. for ( i = 0; i < vlen; i ++ ) {
  21043. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21044. if ( ! extrudeByPath ) {
  21045. v( vert.x, vert.y, 0 );
  21046. } else {
  21047. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  21048. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  21049. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  21050. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  21051. v( position2.x, position2.y, position2.z );
  21052. }
  21053. }
  21054. // Add stepped vertices...
  21055. // Including front facing vertices
  21056. var s;
  21057. for ( s = 1; s <= steps; s ++ ) {
  21058. for ( i = 0; i < vlen; i ++ ) {
  21059. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  21060. if ( ! extrudeByPath ) {
  21061. v( vert.x, vert.y, amount / steps * s );
  21062. } else {
  21063. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  21064. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  21065. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  21066. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  21067. v( position2.x, position2.y, position2.z );
  21068. }
  21069. }
  21070. }
  21071. // Add bevel segments planes
  21072. //for ( b = 1; b <= bevelSegments; b ++ ) {
  21073. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  21074. t = b / bevelSegments;
  21075. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  21076. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  21077. // contract shape
  21078. for ( i = 0, il = contour.length; i < il; i ++ ) {
  21079. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  21080. v( vert.x, vert.y, amount + z );
  21081. }
  21082. // expand holes
  21083. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21084. ahole = holes[ h ];
  21085. oneHoleMovements = holesMovements[ h ];
  21086. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  21087. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  21088. if ( ! extrudeByPath ) {
  21089. v( vert.x, vert.y, amount + z );
  21090. } else {
  21091. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  21092. }
  21093. }
  21094. }
  21095. }
  21096. /* Faces */
  21097. // Top and bottom faces
  21098. buildLidFaces();
  21099. // Sides faces
  21100. buildSideFaces();
  21101. ///// Internal functions
  21102. function buildLidFaces() {
  21103. var start = verticesArray.length / 3;
  21104. if ( bevelEnabled ) {
  21105. var layer = 0; // steps + 1
  21106. var offset = vlen * layer;
  21107. // Bottom faces
  21108. for ( i = 0; i < flen; i ++ ) {
  21109. face = faces[ i ];
  21110. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  21111. }
  21112. layer = steps + bevelSegments * 2;
  21113. offset = vlen * layer;
  21114. // Top faces
  21115. for ( i = 0; i < flen; i ++ ) {
  21116. face = faces[ i ];
  21117. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  21118. }
  21119. } else {
  21120. // Bottom faces
  21121. for ( i = 0; i < flen; i ++ ) {
  21122. face = faces[ i ];
  21123. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  21124. }
  21125. // Top faces
  21126. for ( i = 0; i < flen; i ++ ) {
  21127. face = faces[ i ];
  21128. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  21129. }
  21130. }
  21131. scope.addGroup( start, verticesArray.length / 3 - start, options.material !== undefined ? options.material : 0 );
  21132. }
  21133. // Create faces for the z-sides of the shape
  21134. function buildSideFaces() {
  21135. var start = verticesArray.length / 3;
  21136. var layeroffset = 0;
  21137. sidewalls( contour, layeroffset );
  21138. layeroffset += contour.length;
  21139. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  21140. ahole = holes[ h ];
  21141. sidewalls( ahole, layeroffset );
  21142. //, true
  21143. layeroffset += ahole.length;
  21144. }
  21145. scope.addGroup( start, verticesArray.length / 3 - start, options.extrudeMaterial !== undefined ? options.extrudeMaterial : 1 );
  21146. }
  21147. function sidewalls( contour, layeroffset ) {
  21148. var j, k;
  21149. i = contour.length;
  21150. while ( -- i >= 0 ) {
  21151. j = i;
  21152. k = i - 1;
  21153. if ( k < 0 ) k = contour.length - 1;
  21154. //console.log('b', i,j, i-1, k,vertices.length);
  21155. var s = 0,
  21156. sl = steps + bevelSegments * 2;
  21157. for ( s = 0; s < sl; s ++ ) {
  21158. var slen1 = vlen * s;
  21159. var slen2 = vlen * ( s + 1 );
  21160. var a = layeroffset + j + slen1,
  21161. b = layeroffset + k + slen1,
  21162. c = layeroffset + k + slen2,
  21163. d = layeroffset + j + slen2;
  21164. f4( a, b, c, d );
  21165. }
  21166. }
  21167. }
  21168. function v( x, y, z ) {
  21169. placeholder.push( x );
  21170. placeholder.push( y );
  21171. placeholder.push( z );
  21172. }
  21173. function f3( a, b, c ) {
  21174. addVertex( a );
  21175. addVertex( b );
  21176. addVertex( c );
  21177. var nextIndex = verticesArray.length / 3;
  21178. var uvs = uvgen.generateTopUV( scope, verticesArray, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21179. addUV( uvs[ 0 ] );
  21180. addUV( uvs[ 1 ] );
  21181. addUV( uvs[ 2 ] );
  21182. }
  21183. function f4( a, b, c, d ) {
  21184. addVertex( a );
  21185. addVertex( b );
  21186. addVertex( d );
  21187. addVertex( b );
  21188. addVertex( c );
  21189. addVertex( d );
  21190. var nextIndex = verticesArray.length / 3;
  21191. var uvs = uvgen.generateSideWallUV( scope, verticesArray, nextIndex - 6, nextIndex - 3, nextIndex - 2, nextIndex - 1 );
  21192. addUV( uvs[ 0 ] );
  21193. addUV( uvs[ 1 ] );
  21194. addUV( uvs[ 3 ] );
  21195. addUV( uvs[ 1 ] );
  21196. addUV( uvs[ 2 ] );
  21197. addUV( uvs[ 3 ] );
  21198. }
  21199. function addVertex( index ) {
  21200. indicesArray.push( verticesArray.length / 3 );
  21201. verticesArray.push( placeholder[ index * 3 + 0 ] );
  21202. verticesArray.push( placeholder[ index * 3 + 1 ] );
  21203. verticesArray.push( placeholder[ index * 3 + 2 ] );
  21204. }
  21205. function addUV( vector2 ) {
  21206. uvArray.push( vector2.x );
  21207. uvArray.push( vector2.y );
  21208. }
  21209. if ( ! options.arrays ) {
  21210. this.setIndex( indicesArray );
  21211. this.addAttribute( 'position', new Float32BufferAttribute( verticesArray, 3 ) );
  21212. this.addAttribute( 'uv', new Float32BufferAttribute( uvArray, 2 ) );
  21213. }
  21214. };
  21215. ExtrudeGeometry.WorldUVGenerator = {
  21216. generateTopUV: function ( geometry, vertices, indexA, indexB, indexC ) {
  21217. var a_x = vertices[ indexA * 3 ];
  21218. var a_y = vertices[ indexA * 3 + 1 ];
  21219. var b_x = vertices[ indexB * 3 ];
  21220. var b_y = vertices[ indexB * 3 + 1 ];
  21221. var c_x = vertices[ indexC * 3 ];
  21222. var c_y = vertices[ indexC * 3 + 1 ];
  21223. return [
  21224. new Vector2( a_x, a_y ),
  21225. new Vector2( b_x, b_y ),
  21226. new Vector2( c_x, c_y )
  21227. ];
  21228. },
  21229. generateSideWallUV: function ( geometry, vertices, indexA, indexB, indexC, indexD ) {
  21230. var a_x = vertices[ indexA * 3 ];
  21231. var a_y = vertices[ indexA * 3 + 1 ];
  21232. var a_z = vertices[ indexA * 3 + 2 ];
  21233. var b_x = vertices[ indexB * 3 ];
  21234. var b_y = vertices[ indexB * 3 + 1 ];
  21235. var b_z = vertices[ indexB * 3 + 2 ];
  21236. var c_x = vertices[ indexC * 3 ];
  21237. var c_y = vertices[ indexC * 3 + 1 ];
  21238. var c_z = vertices[ indexC * 3 + 2 ];
  21239. var d_x = vertices[ indexD * 3 ];
  21240. var d_y = vertices[ indexD * 3 + 1 ];
  21241. var d_z = vertices[ indexD * 3 + 2 ];
  21242. if ( Math.abs( a_y - b_y ) < 0.01 ) {
  21243. return [
  21244. new Vector2( a_x, 1 - a_z ),
  21245. new Vector2( b_x, 1 - b_z ),
  21246. new Vector2( c_x, 1 - c_z ),
  21247. new Vector2( d_x, 1 - d_z )
  21248. ];
  21249. } else {
  21250. return [
  21251. new Vector2( a_y, 1 - a_z ),
  21252. new Vector2( b_y, 1 - b_z ),
  21253. new Vector2( c_y, 1 - c_z ),
  21254. new Vector2( d_y, 1 - d_z )
  21255. ];
  21256. }
  21257. }
  21258. };
  21259. /**
  21260. * @author zz85 / http://www.lab4games.net/zz85/blog
  21261. * @author alteredq / http://alteredqualia.com/
  21262. *
  21263. * Text = 3D Text
  21264. *
  21265. * parameters = {
  21266. * font: <THREE.Font>, // font
  21267. *
  21268. * size: <float>, // size of the text
  21269. * height: <float>, // thickness to extrude text
  21270. * curveSegments: <int>, // number of points on the curves
  21271. *
  21272. * bevelEnabled: <bool>, // turn on bevel
  21273. * bevelThickness: <float>, // how deep into text bevel goes
  21274. * bevelSize: <float> // how far from text outline is bevel
  21275. * }
  21276. */
  21277. // TextGeometry
  21278. function TextGeometry( text, parameters ) {
  21279. Geometry.call( this );
  21280. this.type = 'TextGeometry';
  21281. this.parameters = {
  21282. text: text,
  21283. parameters: parameters
  21284. };
  21285. this.fromBufferGeometry( new TextBufferGeometry( text, parameters ) );
  21286. this.mergeVertices();
  21287. }
  21288. TextGeometry.prototype = Object.create( Geometry.prototype );
  21289. TextGeometry.prototype.constructor = TextGeometry;
  21290. // TextBufferGeometry
  21291. function TextBufferGeometry( text, parameters ) {
  21292. parameters = parameters || {};
  21293. var font = parameters.font;
  21294. if ( ! ( font && font.isFont ) ) {
  21295. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  21296. return new Geometry();
  21297. }
  21298. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  21299. // translate parameters to ExtrudeGeometry API
  21300. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  21301. // defaults
  21302. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  21303. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  21304. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  21305. ExtrudeBufferGeometry.call( this, shapes, parameters );
  21306. this.type = 'TextBufferGeometry';
  21307. }
  21308. TextBufferGeometry.prototype = Object.create( ExtrudeBufferGeometry.prototype );
  21309. TextBufferGeometry.prototype.constructor = TextBufferGeometry;
  21310. /**
  21311. * @author mrdoob / http://mrdoob.com/
  21312. * @author benaadams / https://twitter.com/ben_a_adams
  21313. * @author Mugen87 / https://github.com/Mugen87
  21314. */
  21315. // SphereGeometry
  21316. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21317. Geometry.call( this );
  21318. this.type = 'SphereGeometry';
  21319. this.parameters = {
  21320. radius: radius,
  21321. widthSegments: widthSegments,
  21322. heightSegments: heightSegments,
  21323. phiStart: phiStart,
  21324. phiLength: phiLength,
  21325. thetaStart: thetaStart,
  21326. thetaLength: thetaLength
  21327. };
  21328. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  21329. this.mergeVertices();
  21330. }
  21331. SphereGeometry.prototype = Object.create( Geometry.prototype );
  21332. SphereGeometry.prototype.constructor = SphereGeometry;
  21333. // SphereBufferGeometry
  21334. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  21335. BufferGeometry.call( this );
  21336. this.type = 'SphereBufferGeometry';
  21337. this.parameters = {
  21338. radius: radius,
  21339. widthSegments: widthSegments,
  21340. heightSegments: heightSegments,
  21341. phiStart: phiStart,
  21342. phiLength: phiLength,
  21343. thetaStart: thetaStart,
  21344. thetaLength: thetaLength
  21345. };
  21346. radius = radius || 1;
  21347. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  21348. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  21349. phiStart = phiStart !== undefined ? phiStart : 0;
  21350. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  21351. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21352. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  21353. var thetaEnd = thetaStart + thetaLength;
  21354. var ix, iy;
  21355. var index = 0;
  21356. var grid = [];
  21357. var vertex = new Vector3();
  21358. var normal = new Vector3();
  21359. // buffers
  21360. var indices = [];
  21361. var vertices = [];
  21362. var normals = [];
  21363. var uvs = [];
  21364. // generate vertices, normals and uvs
  21365. for ( iy = 0; iy <= heightSegments; iy ++ ) {
  21366. var verticesRow = [];
  21367. var v = iy / heightSegments;
  21368. for ( ix = 0; ix <= widthSegments; ix ++ ) {
  21369. var u = ix / widthSegments;
  21370. // vertex
  21371. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21372. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  21373. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  21374. vertices.push( vertex.x, vertex.y, vertex.z );
  21375. // normal
  21376. normal.set( vertex.x, vertex.y, vertex.z ).normalize();
  21377. normals.push( normal.x, normal.y, normal.z );
  21378. // uv
  21379. uvs.push( u, 1 - v );
  21380. verticesRow.push( index ++ );
  21381. }
  21382. grid.push( verticesRow );
  21383. }
  21384. // indices
  21385. for ( iy = 0; iy < heightSegments; iy ++ ) {
  21386. for ( ix = 0; ix < widthSegments; ix ++ ) {
  21387. var a = grid[ iy ][ ix + 1 ];
  21388. var b = grid[ iy ][ ix ];
  21389. var c = grid[ iy + 1 ][ ix ];
  21390. var d = grid[ iy + 1 ][ ix + 1 ];
  21391. if ( iy !== 0 || thetaStart > 0 ) indices.push( a, b, d );
  21392. if ( iy !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( b, c, d );
  21393. }
  21394. }
  21395. // build geometry
  21396. this.setIndex( indices );
  21397. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21398. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21399. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21400. }
  21401. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21402. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  21403. /**
  21404. * @author Kaleb Murphy
  21405. * @author Mugen87 / https://github.com/Mugen87
  21406. */
  21407. // RingGeometry
  21408. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21409. Geometry.call( this );
  21410. this.type = 'RingGeometry';
  21411. this.parameters = {
  21412. innerRadius: innerRadius,
  21413. outerRadius: outerRadius,
  21414. thetaSegments: thetaSegments,
  21415. phiSegments: phiSegments,
  21416. thetaStart: thetaStart,
  21417. thetaLength: thetaLength
  21418. };
  21419. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  21420. this.mergeVertices();
  21421. }
  21422. RingGeometry.prototype = Object.create( Geometry.prototype );
  21423. RingGeometry.prototype.constructor = RingGeometry;
  21424. // RingBufferGeometry
  21425. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  21426. BufferGeometry.call( this );
  21427. this.type = 'RingBufferGeometry';
  21428. this.parameters = {
  21429. innerRadius: innerRadius,
  21430. outerRadius: outerRadius,
  21431. thetaSegments: thetaSegments,
  21432. phiSegments: phiSegments,
  21433. thetaStart: thetaStart,
  21434. thetaLength: thetaLength
  21435. };
  21436. innerRadius = innerRadius || 0.5;
  21437. outerRadius = outerRadius || 1;
  21438. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21439. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21440. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  21441. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  21442. // buffers
  21443. var indices = [];
  21444. var vertices = [];
  21445. var normals = [];
  21446. var uvs = [];
  21447. // some helper variables
  21448. var segment;
  21449. var radius = innerRadius;
  21450. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  21451. var vertex = new Vector3();
  21452. var uv = new Vector2();
  21453. var j, i;
  21454. // generate vertices, normals and uvs
  21455. for ( j = 0; j <= phiSegments; j ++ ) {
  21456. for ( i = 0; i <= thetaSegments; i ++ ) {
  21457. // values are generate from the inside of the ring to the outside
  21458. segment = thetaStart + i / thetaSegments * thetaLength;
  21459. // vertex
  21460. vertex.x = radius * Math.cos( segment );
  21461. vertex.y = radius * Math.sin( segment );
  21462. vertices.push( vertex.x, vertex.y, vertex.z );
  21463. // normal
  21464. normals.push( 0, 0, 1 );
  21465. // uv
  21466. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  21467. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  21468. uvs.push( uv.x, uv.y );
  21469. }
  21470. // increase the radius for next row of vertices
  21471. radius += radiusStep;
  21472. }
  21473. // indices
  21474. for ( j = 0; j < phiSegments; j ++ ) {
  21475. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  21476. for ( i = 0; i < thetaSegments; i ++ ) {
  21477. segment = i + thetaSegmentLevel;
  21478. var a = segment;
  21479. var b = segment + thetaSegments + 1;
  21480. var c = segment + thetaSegments + 2;
  21481. var d = segment + 1;
  21482. // faces
  21483. indices.push( a, b, d );
  21484. indices.push( b, c, d );
  21485. }
  21486. }
  21487. // build geometry
  21488. this.setIndex( indices );
  21489. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21490. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21491. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21492. }
  21493. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21494. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  21495. /**
  21496. * @author astrodud / http://astrodud.isgreat.org/
  21497. * @author zz85 / https://github.com/zz85
  21498. * @author bhouston / http://clara.io
  21499. * @author Mugen87 / https://github.com/Mugen87
  21500. */
  21501. // LatheGeometry
  21502. function LatheGeometry( points, segments, phiStart, phiLength ) {
  21503. Geometry.call( this );
  21504. this.type = 'LatheGeometry';
  21505. this.parameters = {
  21506. points: points,
  21507. segments: segments,
  21508. phiStart: phiStart,
  21509. phiLength: phiLength
  21510. };
  21511. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  21512. this.mergeVertices();
  21513. }
  21514. LatheGeometry.prototype = Object.create( Geometry.prototype );
  21515. LatheGeometry.prototype.constructor = LatheGeometry;
  21516. // LatheBufferGeometry
  21517. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  21518. BufferGeometry.call( this );
  21519. this.type = 'LatheBufferGeometry';
  21520. this.parameters = {
  21521. points: points,
  21522. segments: segments,
  21523. phiStart: phiStart,
  21524. phiLength: phiLength
  21525. };
  21526. segments = Math.floor( segments ) || 12;
  21527. phiStart = phiStart || 0;
  21528. phiLength = phiLength || Math.PI * 2;
  21529. // clamp phiLength so it's in range of [ 0, 2PI ]
  21530. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  21531. // buffers
  21532. var indices = [];
  21533. var vertices = [];
  21534. var uvs = [];
  21535. // helper variables
  21536. var base;
  21537. var inverseSegments = 1.0 / segments;
  21538. var vertex = new Vector3();
  21539. var uv = new Vector2();
  21540. var i, j;
  21541. // generate vertices and uvs
  21542. for ( i = 0; i <= segments; i ++ ) {
  21543. var phi = phiStart + i * inverseSegments * phiLength;
  21544. var sin = Math.sin( phi );
  21545. var cos = Math.cos( phi );
  21546. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  21547. // vertex
  21548. vertex.x = points[ j ].x * sin;
  21549. vertex.y = points[ j ].y;
  21550. vertex.z = points[ j ].x * cos;
  21551. vertices.push( vertex.x, vertex.y, vertex.z );
  21552. // uv
  21553. uv.x = i / segments;
  21554. uv.y = j / ( points.length - 1 );
  21555. uvs.push( uv.x, uv.y );
  21556. }
  21557. }
  21558. // indices
  21559. for ( i = 0; i < segments; i ++ ) {
  21560. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  21561. base = j + i * points.length;
  21562. var a = base;
  21563. var b = base + points.length;
  21564. var c = base + points.length + 1;
  21565. var d = base + 1;
  21566. // faces
  21567. indices.push( a, b, d );
  21568. indices.push( b, c, d );
  21569. }
  21570. }
  21571. // build geometry
  21572. this.setIndex( indices );
  21573. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21574. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21575. // generate normals
  21576. this.computeVertexNormals();
  21577. // if the geometry is closed, we need to average the normals along the seam.
  21578. // because the corresponding vertices are identical (but still have different UVs).
  21579. if ( phiLength === Math.PI * 2 ) {
  21580. var normals = this.attributes.normal.array;
  21581. var n1 = new Vector3();
  21582. var n2 = new Vector3();
  21583. var n = new Vector3();
  21584. // this is the buffer offset for the last line of vertices
  21585. base = segments * points.length * 3;
  21586. for ( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  21587. // select the normal of the vertex in the first line
  21588. n1.x = normals[ j + 0 ];
  21589. n1.y = normals[ j + 1 ];
  21590. n1.z = normals[ j + 2 ];
  21591. // select the normal of the vertex in the last line
  21592. n2.x = normals[ base + j + 0 ];
  21593. n2.y = normals[ base + j + 1 ];
  21594. n2.z = normals[ base + j + 2 ];
  21595. // average normals
  21596. n.addVectors( n1, n2 ).normalize();
  21597. // assign the new values to both normals
  21598. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  21599. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  21600. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  21601. }
  21602. }
  21603. }
  21604. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21605. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  21606. /**
  21607. * @author jonobr1 / http://jonobr1.com
  21608. * @author Mugen87 / https://github.com/Mugen87
  21609. */
  21610. // ShapeGeometry
  21611. function ShapeGeometry( shapes, curveSegments ) {
  21612. Geometry.call( this );
  21613. this.type = 'ShapeGeometry';
  21614. if ( typeof curveSegments === 'object' ) {
  21615. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  21616. curveSegments = curveSegments.curveSegments;
  21617. }
  21618. this.parameters = {
  21619. shapes: shapes,
  21620. curveSegments: curveSegments
  21621. };
  21622. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  21623. this.mergeVertices();
  21624. }
  21625. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  21626. ShapeGeometry.prototype.constructor = ShapeGeometry;
  21627. ShapeGeometry.prototype.toJSON = function () {
  21628. var data = Geometry.prototype.toJSON.call( this );
  21629. var shapes = this.parameters.shapes;
  21630. return toJSON( shapes, data );
  21631. };
  21632. // ShapeBufferGeometry
  21633. function ShapeBufferGeometry( shapes, curveSegments ) {
  21634. BufferGeometry.call( this );
  21635. this.type = 'ShapeBufferGeometry';
  21636. this.parameters = {
  21637. shapes: shapes,
  21638. curveSegments: curveSegments
  21639. };
  21640. curveSegments = curveSegments || 12;
  21641. // buffers
  21642. var indices = [];
  21643. var vertices = [];
  21644. var normals = [];
  21645. var uvs = [];
  21646. // helper variables
  21647. var groupStart = 0;
  21648. var groupCount = 0;
  21649. // allow single and array values for "shapes" parameter
  21650. if ( Array.isArray( shapes ) === false ) {
  21651. addShape( shapes );
  21652. } else {
  21653. for ( var i = 0; i < shapes.length; i ++ ) {
  21654. addShape( shapes[ i ] );
  21655. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  21656. groupStart += groupCount;
  21657. groupCount = 0;
  21658. }
  21659. }
  21660. // build geometry
  21661. this.setIndex( indices );
  21662. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21663. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21664. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21665. // helper functions
  21666. function addShape( shape ) {
  21667. var i, l, shapeHole;
  21668. var indexOffset = vertices.length / 3;
  21669. var points = shape.extractPoints( curveSegments );
  21670. var shapeVertices = points.shape;
  21671. var shapeHoles = points.holes;
  21672. // check direction of vertices
  21673. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  21674. shapeVertices = shapeVertices.reverse();
  21675. // also check if holes are in the opposite direction
  21676. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21677. shapeHole = shapeHoles[ i ];
  21678. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  21679. shapeHoles[ i ] = shapeHole.reverse();
  21680. }
  21681. }
  21682. }
  21683. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  21684. // join vertices of inner and outer paths to a single array
  21685. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  21686. shapeHole = shapeHoles[ i ];
  21687. shapeVertices = shapeVertices.concat( shapeHole );
  21688. }
  21689. // vertices, normals, uvs
  21690. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  21691. var vertex = shapeVertices[ i ];
  21692. vertices.push( vertex.x, vertex.y, 0 );
  21693. normals.push( 0, 0, 1 );
  21694. uvs.push( vertex.x, vertex.y ); // world uvs
  21695. }
  21696. // incides
  21697. for ( i = 0, l = faces.length; i < l; i ++ ) {
  21698. var face = faces[ i ];
  21699. var a = face[ 0 ] + indexOffset;
  21700. var b = face[ 1 ] + indexOffset;
  21701. var c = face[ 2 ] + indexOffset;
  21702. indices.push( a, b, c );
  21703. groupCount += 3;
  21704. }
  21705. }
  21706. }
  21707. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21708. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  21709. ShapeBufferGeometry.prototype.toJSON = function () {
  21710. var data = BufferGeometry.prototype.toJSON.call( this );
  21711. var shapes = this.parameters.shapes;
  21712. return toJSON( shapes, data );
  21713. };
  21714. //
  21715. function toJSON( shapes, data ) {
  21716. data.shapes = [];
  21717. if ( Array.isArray( shapes ) ) {
  21718. for ( var i = 0, l = shapes.length; i < l; i ++ ) {
  21719. var shape = shapes[ i ];
  21720. data.shapes.push( shape.uuid );
  21721. }
  21722. } else {
  21723. data.shapes.push( shapes.uuid );
  21724. }
  21725. return data;
  21726. }
  21727. /**
  21728. * @author WestLangley / http://github.com/WestLangley
  21729. * @author Mugen87 / https://github.com/Mugen87
  21730. */
  21731. function EdgesGeometry( geometry, thresholdAngle ) {
  21732. BufferGeometry.call( this );
  21733. this.type = 'EdgesGeometry';
  21734. this.parameters = {
  21735. thresholdAngle: thresholdAngle
  21736. };
  21737. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  21738. // buffer
  21739. var vertices = [];
  21740. // helper variables
  21741. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  21742. var edge = [ 0, 0 ], edges = {}, edge1, edge2;
  21743. var key, keys = [ 'a', 'b', 'c' ];
  21744. // prepare source geometry
  21745. var geometry2;
  21746. if ( geometry.isBufferGeometry ) {
  21747. geometry2 = new Geometry();
  21748. geometry2.fromBufferGeometry( geometry );
  21749. } else {
  21750. geometry2 = geometry.clone();
  21751. }
  21752. geometry2.mergeVertices();
  21753. geometry2.computeFaceNormals();
  21754. var sourceVertices = geometry2.vertices;
  21755. var faces = geometry2.faces;
  21756. // now create a data structure where each entry represents an edge with its adjoining faces
  21757. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21758. var face = faces[ i ];
  21759. for ( var j = 0; j < 3; j ++ ) {
  21760. edge1 = face[ keys[ j ] ];
  21761. edge2 = face[ keys[ ( j + 1 ) % 3 ] ];
  21762. edge[ 0 ] = Math.min( edge1, edge2 );
  21763. edge[ 1 ] = Math.max( edge1, edge2 );
  21764. key = edge[ 0 ] + ',' + edge[ 1 ];
  21765. if ( edges[ key ] === undefined ) {
  21766. edges[ key ] = { index1: edge[ 0 ], index2: edge[ 1 ], face1: i, face2: undefined };
  21767. } else {
  21768. edges[ key ].face2 = i;
  21769. }
  21770. }
  21771. }
  21772. // generate vertices
  21773. for ( key in edges ) {
  21774. var e = edges[ key ];
  21775. // an edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  21776. if ( e.face2 === undefined || faces[ e.face1 ].normal.dot( faces[ e.face2 ].normal ) <= thresholdDot ) {
  21777. var vertex = sourceVertices[ e.index1 ];
  21778. vertices.push( vertex.x, vertex.y, vertex.z );
  21779. vertex = sourceVertices[ e.index2 ];
  21780. vertices.push( vertex.x, vertex.y, vertex.z );
  21781. }
  21782. }
  21783. // build geometry
  21784. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21785. }
  21786. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  21787. EdgesGeometry.prototype.constructor = EdgesGeometry;
  21788. /**
  21789. * @author mrdoob / http://mrdoob.com/
  21790. * @author Mugen87 / https://github.com/Mugen87
  21791. */
  21792. // CylinderGeometry
  21793. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21794. Geometry.call( this );
  21795. this.type = 'CylinderGeometry';
  21796. this.parameters = {
  21797. radiusTop: radiusTop,
  21798. radiusBottom: radiusBottom,
  21799. height: height,
  21800. radialSegments: radialSegments,
  21801. heightSegments: heightSegments,
  21802. openEnded: openEnded,
  21803. thetaStart: thetaStart,
  21804. thetaLength: thetaLength
  21805. };
  21806. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  21807. this.mergeVertices();
  21808. }
  21809. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  21810. CylinderGeometry.prototype.constructor = CylinderGeometry;
  21811. // CylinderBufferGeometry
  21812. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21813. BufferGeometry.call( this );
  21814. this.type = 'CylinderBufferGeometry';
  21815. this.parameters = {
  21816. radiusTop: radiusTop,
  21817. radiusBottom: radiusBottom,
  21818. height: height,
  21819. radialSegments: radialSegments,
  21820. heightSegments: heightSegments,
  21821. openEnded: openEnded,
  21822. thetaStart: thetaStart,
  21823. thetaLength: thetaLength
  21824. };
  21825. var scope = this;
  21826. radiusTop = radiusTop !== undefined ? radiusTop : 1;
  21827. radiusBottom = radiusBottom !== undefined ? radiusBottom : 1;
  21828. height = height || 1;
  21829. radialSegments = Math.floor( radialSegments ) || 8;
  21830. heightSegments = Math.floor( heightSegments ) || 1;
  21831. openEnded = openEnded !== undefined ? openEnded : false;
  21832. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  21833. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21834. // buffers
  21835. var indices = [];
  21836. var vertices = [];
  21837. var normals = [];
  21838. var uvs = [];
  21839. // helper variables
  21840. var index = 0;
  21841. var indexArray = [];
  21842. var halfHeight = height / 2;
  21843. var groupStart = 0;
  21844. // generate geometry
  21845. generateTorso();
  21846. if ( openEnded === false ) {
  21847. if ( radiusTop > 0 ) generateCap( true );
  21848. if ( radiusBottom > 0 ) generateCap( false );
  21849. }
  21850. // build geometry
  21851. this.setIndex( indices );
  21852. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  21853. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  21854. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  21855. function generateTorso() {
  21856. var x, y;
  21857. var normal = new Vector3();
  21858. var vertex = new Vector3();
  21859. var groupCount = 0;
  21860. // this will be used to calculate the normal
  21861. var slope = ( radiusBottom - radiusTop ) / height;
  21862. // generate vertices, normals and uvs
  21863. for ( y = 0; y <= heightSegments; y ++ ) {
  21864. var indexRow = [];
  21865. var v = y / heightSegments;
  21866. // calculate the radius of the current row
  21867. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  21868. for ( x = 0; x <= radialSegments; x ++ ) {
  21869. var u = x / radialSegments;
  21870. var theta = u * thetaLength + thetaStart;
  21871. var sinTheta = Math.sin( theta );
  21872. var cosTheta = Math.cos( theta );
  21873. // vertex
  21874. vertex.x = radius * sinTheta;
  21875. vertex.y = - v * height + halfHeight;
  21876. vertex.z = radius * cosTheta;
  21877. vertices.push( vertex.x, vertex.y, vertex.z );
  21878. // normal
  21879. normal.set( sinTheta, slope, cosTheta ).normalize();
  21880. normals.push( normal.x, normal.y, normal.z );
  21881. // uv
  21882. uvs.push( u, 1 - v );
  21883. // save index of vertex in respective row
  21884. indexRow.push( index ++ );
  21885. }
  21886. // now save vertices of the row in our index array
  21887. indexArray.push( indexRow );
  21888. }
  21889. // generate indices
  21890. for ( x = 0; x < radialSegments; x ++ ) {
  21891. for ( y = 0; y < heightSegments; y ++ ) {
  21892. // we use the index array to access the correct indices
  21893. var a = indexArray[ y ][ x ];
  21894. var b = indexArray[ y + 1 ][ x ];
  21895. var c = indexArray[ y + 1 ][ x + 1 ];
  21896. var d = indexArray[ y ][ x + 1 ];
  21897. // faces
  21898. indices.push( a, b, d );
  21899. indices.push( b, c, d );
  21900. // update group counter
  21901. groupCount += 6;
  21902. }
  21903. }
  21904. // add a group to the geometry. this will ensure multi material support
  21905. scope.addGroup( groupStart, groupCount, 0 );
  21906. // calculate new start value for groups
  21907. groupStart += groupCount;
  21908. }
  21909. function generateCap( top ) {
  21910. var x, centerIndexStart, centerIndexEnd;
  21911. var uv = new Vector2();
  21912. var vertex = new Vector3();
  21913. var groupCount = 0;
  21914. var radius = ( top === true ) ? radiusTop : radiusBottom;
  21915. var sign = ( top === true ) ? 1 : - 1;
  21916. // save the index of the first center vertex
  21917. centerIndexStart = index;
  21918. // first we generate the center vertex data of the cap.
  21919. // because the geometry needs one set of uvs per face,
  21920. // we must generate a center vertex per face/segment
  21921. for ( x = 1; x <= radialSegments; x ++ ) {
  21922. // vertex
  21923. vertices.push( 0, halfHeight * sign, 0 );
  21924. // normal
  21925. normals.push( 0, sign, 0 );
  21926. // uv
  21927. uvs.push( 0.5, 0.5 );
  21928. // increase index
  21929. index ++;
  21930. }
  21931. // save the index of the last center vertex
  21932. centerIndexEnd = index;
  21933. // now we generate the surrounding vertices, normals and uvs
  21934. for ( x = 0; x <= radialSegments; x ++ ) {
  21935. var u = x / radialSegments;
  21936. var theta = u * thetaLength + thetaStart;
  21937. var cosTheta = Math.cos( theta );
  21938. var sinTheta = Math.sin( theta );
  21939. // vertex
  21940. vertex.x = radius * sinTheta;
  21941. vertex.y = halfHeight * sign;
  21942. vertex.z = radius * cosTheta;
  21943. vertices.push( vertex.x, vertex.y, vertex.z );
  21944. // normal
  21945. normals.push( 0, sign, 0 );
  21946. // uv
  21947. uv.x = ( cosTheta * 0.5 ) + 0.5;
  21948. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  21949. uvs.push( uv.x, uv.y );
  21950. // increase index
  21951. index ++;
  21952. }
  21953. // generate indices
  21954. for ( x = 0; x < radialSegments; x ++ ) {
  21955. var c = centerIndexStart + x;
  21956. var i = centerIndexEnd + x;
  21957. if ( top === true ) {
  21958. // face top
  21959. indices.push( i, i + 1, c );
  21960. } else {
  21961. // face bottom
  21962. indices.push( i + 1, i, c );
  21963. }
  21964. groupCount += 3;
  21965. }
  21966. // add a group to the geometry. this will ensure multi material support
  21967. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  21968. // calculate new start value for groups
  21969. groupStart += groupCount;
  21970. }
  21971. }
  21972. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21973. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  21974. /**
  21975. * @author abelnation / http://github.com/abelnation
  21976. */
  21977. // ConeGeometry
  21978. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21979. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21980. this.type = 'ConeGeometry';
  21981. this.parameters = {
  21982. radius: radius,
  21983. height: height,
  21984. radialSegments: radialSegments,
  21985. heightSegments: heightSegments,
  21986. openEnded: openEnded,
  21987. thetaStart: thetaStart,
  21988. thetaLength: thetaLength
  21989. };
  21990. }
  21991. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  21992. ConeGeometry.prototype.constructor = ConeGeometry;
  21993. // ConeBufferGeometry
  21994. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  21995. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  21996. this.type = 'ConeBufferGeometry';
  21997. this.parameters = {
  21998. radius: radius,
  21999. height: height,
  22000. radialSegments: radialSegments,
  22001. heightSegments: heightSegments,
  22002. openEnded: openEnded,
  22003. thetaStart: thetaStart,
  22004. thetaLength: thetaLength
  22005. };
  22006. }
  22007. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  22008. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  22009. /**
  22010. * @author benaadams / https://twitter.com/ben_a_adams
  22011. * @author Mugen87 / https://github.com/Mugen87
  22012. * @author hughes
  22013. */
  22014. // CircleGeometry
  22015. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  22016. Geometry.call( this );
  22017. this.type = 'CircleGeometry';
  22018. this.parameters = {
  22019. radius: radius,
  22020. segments: segments,
  22021. thetaStart: thetaStart,
  22022. thetaLength: thetaLength
  22023. };
  22024. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  22025. this.mergeVertices();
  22026. }
  22027. CircleGeometry.prototype = Object.create( Geometry.prototype );
  22028. CircleGeometry.prototype.constructor = CircleGeometry;
  22029. // CircleBufferGeometry
  22030. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  22031. BufferGeometry.call( this );
  22032. this.type = 'CircleBufferGeometry';
  22033. this.parameters = {
  22034. radius: radius,
  22035. segments: segments,
  22036. thetaStart: thetaStart,
  22037. thetaLength: thetaLength
  22038. };
  22039. radius = radius || 1;
  22040. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  22041. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  22042. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  22043. // buffers
  22044. var indices = [];
  22045. var vertices = [];
  22046. var normals = [];
  22047. var uvs = [];
  22048. // helper variables
  22049. var i, s;
  22050. var vertex = new Vector3();
  22051. var uv = new Vector2();
  22052. // center point
  22053. vertices.push( 0, 0, 0 );
  22054. normals.push( 0, 0, 1 );
  22055. uvs.push( 0.5, 0.5 );
  22056. for ( s = 0, i = 3; s <= segments; s ++, i += 3 ) {
  22057. var segment = thetaStart + s / segments * thetaLength;
  22058. // vertex
  22059. vertex.x = radius * Math.cos( segment );
  22060. vertex.y = radius * Math.sin( segment );
  22061. vertices.push( vertex.x, vertex.y, vertex.z );
  22062. // normal
  22063. normals.push( 0, 0, 1 );
  22064. // uvs
  22065. uv.x = ( vertices[ i ] / radius + 1 ) / 2;
  22066. uv.y = ( vertices[ i + 1 ] / radius + 1 ) / 2;
  22067. uvs.push( uv.x, uv.y );
  22068. }
  22069. // indices
  22070. for ( i = 1; i <= segments; i ++ ) {
  22071. indices.push( i, i + 1, 0 );
  22072. }
  22073. // build geometry
  22074. this.setIndex( indices );
  22075. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  22076. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  22077. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  22078. }
  22079. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  22080. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  22081. var Geometries = Object.freeze({
  22082. WireframeGeometry: WireframeGeometry,
  22083. ParametricGeometry: ParametricGeometry,
  22084. ParametricBufferGeometry: ParametricBufferGeometry,
  22085. TetrahedronGeometry: TetrahedronGeometry,
  22086. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  22087. OctahedronGeometry: OctahedronGeometry,
  22088. OctahedronBufferGeometry: OctahedronBufferGeometry,
  22089. IcosahedronGeometry: IcosahedronGeometry,
  22090. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  22091. DodecahedronGeometry: DodecahedronGeometry,
  22092. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  22093. PolyhedronGeometry: PolyhedronGeometry,
  22094. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  22095. TubeGeometry: TubeGeometry,
  22096. TubeBufferGeometry: TubeBufferGeometry,
  22097. TorusKnotGeometry: TorusKnotGeometry,
  22098. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  22099. TorusGeometry: TorusGeometry,
  22100. TorusBufferGeometry: TorusBufferGeometry,
  22101. TextGeometry: TextGeometry,
  22102. TextBufferGeometry: TextBufferGeometry,
  22103. SphereGeometry: SphereGeometry,
  22104. SphereBufferGeometry: SphereBufferGeometry,
  22105. RingGeometry: RingGeometry,
  22106. RingBufferGeometry: RingBufferGeometry,
  22107. PlaneGeometry: PlaneGeometry,
  22108. PlaneBufferGeometry: PlaneBufferGeometry,
  22109. LatheGeometry: LatheGeometry,
  22110. LatheBufferGeometry: LatheBufferGeometry,
  22111. ShapeGeometry: ShapeGeometry,
  22112. ShapeBufferGeometry: ShapeBufferGeometry,
  22113. ExtrudeGeometry: ExtrudeGeometry,
  22114. ExtrudeBufferGeometry: ExtrudeBufferGeometry,
  22115. EdgesGeometry: EdgesGeometry,
  22116. ConeGeometry: ConeGeometry,
  22117. ConeBufferGeometry: ConeBufferGeometry,
  22118. CylinderGeometry: CylinderGeometry,
  22119. CylinderBufferGeometry: CylinderBufferGeometry,
  22120. CircleGeometry: CircleGeometry,
  22121. CircleBufferGeometry: CircleBufferGeometry,
  22122. BoxGeometry: BoxGeometry,
  22123. BoxBufferGeometry: BoxBufferGeometry
  22124. });
  22125. /**
  22126. * @author mrdoob / http://mrdoob.com/
  22127. *
  22128. * parameters = {
  22129. * color: <THREE.Color>,
  22130. * opacity: <float>
  22131. * }
  22132. */
  22133. function ShadowMaterial( parameters ) {
  22134. Material.call( this );
  22135. this.type = 'ShadowMaterial';
  22136. this.color = new Color( 0x000000 );
  22137. this.opacity = 1.0;
  22138. this.lights = true;
  22139. this.transparent = true;
  22140. this.setValues( parameters );
  22141. }
  22142. ShadowMaterial.prototype = Object.create( Material.prototype );
  22143. ShadowMaterial.prototype.constructor = ShadowMaterial;
  22144. ShadowMaterial.prototype.isShadowMaterial = true;
  22145. /**
  22146. * @author mrdoob / http://mrdoob.com/
  22147. */
  22148. function RawShaderMaterial( parameters ) {
  22149. ShaderMaterial.call( this, parameters );
  22150. this.type = 'RawShaderMaterial';
  22151. }
  22152. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  22153. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  22154. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  22155. /**
  22156. * @author WestLangley / http://github.com/WestLangley
  22157. *
  22158. * parameters = {
  22159. * color: <hex>,
  22160. * roughness: <float>,
  22161. * metalness: <float>,
  22162. * opacity: <float>,
  22163. *
  22164. * map: new THREE.Texture( <Image> ),
  22165. *
  22166. * lightMap: new THREE.Texture( <Image> ),
  22167. * lightMapIntensity: <float>
  22168. *
  22169. * aoMap: new THREE.Texture( <Image> ),
  22170. * aoMapIntensity: <float>
  22171. *
  22172. * emissive: <hex>,
  22173. * emissiveIntensity: <float>
  22174. * emissiveMap: new THREE.Texture( <Image> ),
  22175. *
  22176. * bumpMap: new THREE.Texture( <Image> ),
  22177. * bumpScale: <float>,
  22178. *
  22179. * normalMap: new THREE.Texture( <Image> ),
  22180. * normalScale: <Vector2>,
  22181. *
  22182. * displacementMap: new THREE.Texture( <Image> ),
  22183. * displacementScale: <float>,
  22184. * displacementBias: <float>,
  22185. *
  22186. * roughnessMap: new THREE.Texture( <Image> ),
  22187. *
  22188. * metalnessMap: new THREE.Texture( <Image> ),
  22189. *
  22190. * alphaMap: new THREE.Texture( <Image> ),
  22191. *
  22192. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  22193. * envMapIntensity: <float>
  22194. *
  22195. * refractionRatio: <float>,
  22196. *
  22197. * wireframe: <boolean>,
  22198. * wireframeLinewidth: <float>,
  22199. *
  22200. * skinning: <bool>,
  22201. * morphTargets: <bool>,
  22202. * morphNormals: <bool>
  22203. * }
  22204. */
  22205. function MeshStandardMaterial( parameters ) {
  22206. Material.call( this );
  22207. this.defines = { 'STANDARD': '' };
  22208. this.type = 'MeshStandardMaterial';
  22209. this.color = new Color( 0xffffff ); // diffuse
  22210. this.roughness = 0.5;
  22211. this.metalness = 0.5;
  22212. this.map = null;
  22213. this.lightMap = null;
  22214. this.lightMapIntensity = 1.0;
  22215. this.aoMap = null;
  22216. this.aoMapIntensity = 1.0;
  22217. this.emissive = new Color( 0x000000 );
  22218. this.emissiveIntensity = 1.0;
  22219. this.emissiveMap = null;
  22220. this.bumpMap = null;
  22221. this.bumpScale = 1;
  22222. this.normalMap = null;
  22223. this.normalScale = new Vector2( 1, 1 );
  22224. this.displacementMap = null;
  22225. this.displacementScale = 1;
  22226. this.displacementBias = 0;
  22227. this.roughnessMap = null;
  22228. this.metalnessMap = null;
  22229. this.alphaMap = null;
  22230. this.envMap = null;
  22231. this.envMapIntensity = 1.0;
  22232. this.refractionRatio = 0.98;
  22233. this.wireframe = false;
  22234. this.wireframeLinewidth = 1;
  22235. this.wireframeLinecap = 'round';
  22236. this.wireframeLinejoin = 'round';
  22237. this.skinning = false;
  22238. this.morphTargets = false;
  22239. this.morphNormals = false;
  22240. this.setValues( parameters );
  22241. }
  22242. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  22243. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  22244. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  22245. MeshStandardMaterial.prototype.copy = function ( source ) {
  22246. Material.prototype.copy.call( this, source );
  22247. this.defines = { 'STANDARD': '' };
  22248. this.color.copy( source.color );
  22249. this.roughness = source.roughness;
  22250. this.metalness = source.metalness;
  22251. this.map = source.map;
  22252. this.lightMap = source.lightMap;
  22253. this.lightMapIntensity = source.lightMapIntensity;
  22254. this.aoMap = source.aoMap;
  22255. this.aoMapIntensity = source.aoMapIntensity;
  22256. this.emissive.copy( source.emissive );
  22257. this.emissiveMap = source.emissiveMap;
  22258. this.emissiveIntensity = source.emissiveIntensity;
  22259. this.bumpMap = source.bumpMap;
  22260. this.bumpScale = source.bumpScale;
  22261. this.normalMap = source.normalMap;
  22262. this.normalScale.copy( source.normalScale );
  22263. this.displacementMap = source.displacementMap;
  22264. this.displacementScale = source.displacementScale;
  22265. this.displacementBias = source.displacementBias;
  22266. this.roughnessMap = source.roughnessMap;
  22267. this.metalnessMap = source.metalnessMap;
  22268. this.alphaMap = source.alphaMap;
  22269. this.envMap = source.envMap;
  22270. this.envMapIntensity = source.envMapIntensity;
  22271. this.refractionRatio = source.refractionRatio;
  22272. this.wireframe = source.wireframe;
  22273. this.wireframeLinewidth = source.wireframeLinewidth;
  22274. this.wireframeLinecap = source.wireframeLinecap;
  22275. this.wireframeLinejoin = source.wireframeLinejoin;
  22276. this.skinning = source.skinning;
  22277. this.morphTargets = source.morphTargets;
  22278. this.morphNormals = source.morphNormals;
  22279. return this;
  22280. };
  22281. /**
  22282. * @author WestLangley / http://github.com/WestLangley
  22283. *
  22284. * parameters = {
  22285. * reflectivity: <float>
  22286. * }
  22287. */
  22288. function MeshPhysicalMaterial( parameters ) {
  22289. MeshStandardMaterial.call( this );
  22290. this.defines = { 'PHYSICAL': '' };
  22291. this.type = 'MeshPhysicalMaterial';
  22292. this.reflectivity = 0.5; // maps to F0 = 0.04
  22293. this.clearCoat = 0.0;
  22294. this.clearCoatRoughness = 0.0;
  22295. this.setValues( parameters );
  22296. }
  22297. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  22298. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  22299. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  22300. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  22301. MeshStandardMaterial.prototype.copy.call( this, source );
  22302. this.defines = { 'PHYSICAL': '' };
  22303. this.reflectivity = source.reflectivity;
  22304. this.clearCoat = source.clearCoat;
  22305. this.clearCoatRoughness = source.clearCoatRoughness;
  22306. return this;
  22307. };
  22308. /**
  22309. * @author mrdoob / http://mrdoob.com/
  22310. * @author alteredq / http://alteredqualia.com/
  22311. *
  22312. * parameters = {
  22313. * color: <hex>,
  22314. * specular: <hex>,
  22315. * shininess: <float>,
  22316. * opacity: <float>,
  22317. *
  22318. * map: new THREE.Texture( <Image> ),
  22319. *
  22320. * lightMap: new THREE.Texture( <Image> ),
  22321. * lightMapIntensity: <float>
  22322. *
  22323. * aoMap: new THREE.Texture( <Image> ),
  22324. * aoMapIntensity: <float>
  22325. *
  22326. * emissive: <hex>,
  22327. * emissiveIntensity: <float>
  22328. * emissiveMap: new THREE.Texture( <Image> ),
  22329. *
  22330. * bumpMap: new THREE.Texture( <Image> ),
  22331. * bumpScale: <float>,
  22332. *
  22333. * normalMap: new THREE.Texture( <Image> ),
  22334. * normalScale: <Vector2>,
  22335. *
  22336. * displacementMap: new THREE.Texture( <Image> ),
  22337. * displacementScale: <float>,
  22338. * displacementBias: <float>,
  22339. *
  22340. * specularMap: new THREE.Texture( <Image> ),
  22341. *
  22342. * alphaMap: new THREE.Texture( <Image> ),
  22343. *
  22344. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  22345. * combine: THREE.Multiply,
  22346. * reflectivity: <float>,
  22347. * refractionRatio: <float>,
  22348. *
  22349. * wireframe: <boolean>,
  22350. * wireframeLinewidth: <float>,
  22351. *
  22352. * skinning: <bool>,
  22353. * morphTargets: <bool>,
  22354. * morphNormals: <bool>
  22355. * }
  22356. */
  22357. function MeshPhongMaterial( parameters ) {
  22358. Material.call( this );
  22359. this.type = 'MeshPhongMaterial';
  22360. this.color = new Color( 0xffffff ); // diffuse
  22361. this.specular = new Color( 0x111111 );
  22362. this.shininess = 30;
  22363. this.map = null;
  22364. this.lightMap = null;
  22365. this.lightMapIntensity = 1.0;
  22366. this.aoMap = null;
  22367. this.aoMapIntensity = 1.0;
  22368. this.emissive = new Color( 0x000000 );
  22369. this.emissiveIntensity = 1.0;
  22370. this.emissiveMap = null;
  22371. this.bumpMap = null;
  22372. this.bumpScale = 1;
  22373. this.normalMap = null;
  22374. this.normalScale = new Vector2( 1, 1 );
  22375. this.displacementMap = null;
  22376. this.displacementScale = 1;
  22377. this.displacementBias = 0;
  22378. this.specularMap = null;
  22379. this.alphaMap = null;
  22380. this.envMap = null;
  22381. this.combine = MultiplyOperation;
  22382. this.reflectivity = 1;
  22383. this.refractionRatio = 0.98;
  22384. this.wireframe = false;
  22385. this.wireframeLinewidth = 1;
  22386. this.wireframeLinecap = 'round';
  22387. this.wireframeLinejoin = 'round';
  22388. this.skinning = false;
  22389. this.morphTargets = false;
  22390. this.morphNormals = false;
  22391. this.setValues( parameters );
  22392. }
  22393. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  22394. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  22395. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  22396. MeshPhongMaterial.prototype.copy = function ( source ) {
  22397. Material.prototype.copy.call( this, source );
  22398. this.color.copy( source.color );
  22399. this.specular.copy( source.specular );
  22400. this.shininess = source.shininess;
  22401. this.map = source.map;
  22402. this.lightMap = source.lightMap;
  22403. this.lightMapIntensity = source.lightMapIntensity;
  22404. this.aoMap = source.aoMap;
  22405. this.aoMapIntensity = source.aoMapIntensity;
  22406. this.emissive.copy( source.emissive );
  22407. this.emissiveMap = source.emissiveMap;
  22408. this.emissiveIntensity = source.emissiveIntensity;
  22409. this.bumpMap = source.bumpMap;
  22410. this.bumpScale = source.bumpScale;
  22411. this.normalMap = source.normalMap;
  22412. this.normalScale.copy( source.normalScale );
  22413. this.displacementMap = source.displacementMap;
  22414. this.displacementScale = source.displacementScale;
  22415. this.displacementBias = source.displacementBias;
  22416. this.specularMap = source.specularMap;
  22417. this.alphaMap = source.alphaMap;
  22418. this.envMap = source.envMap;
  22419. this.combine = source.combine;
  22420. this.reflectivity = source.reflectivity;
  22421. this.refractionRatio = source.refractionRatio;
  22422. this.wireframe = source.wireframe;
  22423. this.wireframeLinewidth = source.wireframeLinewidth;
  22424. this.wireframeLinecap = source.wireframeLinecap;
  22425. this.wireframeLinejoin = source.wireframeLinejoin;
  22426. this.skinning = source.skinning;
  22427. this.morphTargets = source.morphTargets;
  22428. this.morphNormals = source.morphNormals;
  22429. return this;
  22430. };
  22431. /**
  22432. * @author takahirox / http://github.com/takahirox
  22433. *
  22434. * parameters = {
  22435. * gradientMap: new THREE.Texture( <Image> )
  22436. * }
  22437. */
  22438. function MeshToonMaterial( parameters ) {
  22439. MeshPhongMaterial.call( this );
  22440. this.defines = { 'TOON': '' };
  22441. this.type = 'MeshToonMaterial';
  22442. this.gradientMap = null;
  22443. this.setValues( parameters );
  22444. }
  22445. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  22446. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  22447. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  22448. MeshToonMaterial.prototype.copy = function ( source ) {
  22449. MeshPhongMaterial.prototype.copy.call( this, source );
  22450. this.gradientMap = source.gradientMap;
  22451. return this;
  22452. };
  22453. /**
  22454. * @author mrdoob / http://mrdoob.com/
  22455. * @author WestLangley / http://github.com/WestLangley
  22456. *
  22457. * parameters = {
  22458. * opacity: <float>,
  22459. *
  22460. * bumpMap: new THREE.Texture( <Image> ),
  22461. * bumpScale: <float>,
  22462. *
  22463. * normalMap: new THREE.Texture( <Image> ),
  22464. * normalScale: <Vector2>,
  22465. *
  22466. * displacementMap: new THREE.Texture( <Image> ),
  22467. * displacementScale: <float>,
  22468. * displacementBias: <float>,
  22469. *
  22470. * wireframe: <boolean>,
  22471. * wireframeLinewidth: <float>
  22472. *
  22473. * skinning: <bool>,
  22474. * morphTargets: <bool>,
  22475. * morphNormals: <bool>
  22476. * }
  22477. */
  22478. function MeshNormalMaterial( parameters ) {
  22479. Material.call( this );
  22480. this.type = 'MeshNormalMaterial';
  22481. this.bumpMap = null;
  22482. this.bumpScale = 1;
  22483. this.normalMap = null;
  22484. this.normalScale = new Vector2( 1, 1 );
  22485. this.displacementMap = null;
  22486. this.displacementScale = 1;
  22487. this.displacementBias = 0;
  22488. this.wireframe = false;
  22489. this.wireframeLinewidth = 1;
  22490. this.fog = false;
  22491. this.lights = false;
  22492. this.skinning = false;
  22493. this.morphTargets = false;
  22494. this.morphNormals = false;
  22495. this.setValues( parameters );
  22496. }
  22497. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  22498. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  22499. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  22500. MeshNormalMaterial.prototype.copy = function ( source ) {
  22501. Material.prototype.copy.call( this, source );
  22502. this.bumpMap = source.bumpMap;
  22503. this.bumpScale = source.bumpScale;
  22504. this.normalMap = source.normalMap;
  22505. this.normalScale.copy( source.normalScale );
  22506. this.displacementMap = source.displacementMap;
  22507. this.displacementScale = source.displacementScale;
  22508. this.displacementBias = source.displacementBias;
  22509. this.wireframe = source.wireframe;
  22510. this.wireframeLinewidth = source.wireframeLinewidth;
  22511. this.skinning = source.skinning;
  22512. this.morphTargets = source.morphTargets;
  22513. this.morphNormals = source.morphNormals;
  22514. return this;
  22515. };
  22516. /**
  22517. * @author mrdoob / http://mrdoob.com/
  22518. * @author alteredq / http://alteredqualia.com/
  22519. *
  22520. * parameters = {
  22521. * color: <hex>,
  22522. * opacity: <float>,
  22523. *
  22524. * map: new THREE.Texture( <Image> ),
  22525. *
  22526. * lightMap: new THREE.Texture( <Image> ),
  22527. * lightMapIntensity: <float>
  22528. *
  22529. * aoMap: new THREE.Texture( <Image> ),
  22530. * aoMapIntensity: <float>
  22531. *
  22532. * emissive: <hex>,
  22533. * emissiveIntensity: <float>
  22534. * emissiveMap: new THREE.Texture( <Image> ),
  22535. *
  22536. * specularMap: new THREE.Texture( <Image> ),
  22537. *
  22538. * alphaMap: new THREE.Texture( <Image> ),
  22539. *
  22540. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  22541. * combine: THREE.Multiply,
  22542. * reflectivity: <float>,
  22543. * refractionRatio: <float>,
  22544. *
  22545. * wireframe: <boolean>,
  22546. * wireframeLinewidth: <float>,
  22547. *
  22548. * skinning: <bool>,
  22549. * morphTargets: <bool>,
  22550. * morphNormals: <bool>
  22551. * }
  22552. */
  22553. function MeshLambertMaterial( parameters ) {
  22554. Material.call( this );
  22555. this.type = 'MeshLambertMaterial';
  22556. this.color = new Color( 0xffffff ); // diffuse
  22557. this.map = null;
  22558. this.lightMap = null;
  22559. this.lightMapIntensity = 1.0;
  22560. this.aoMap = null;
  22561. this.aoMapIntensity = 1.0;
  22562. this.emissive = new Color( 0x000000 );
  22563. this.emissiveIntensity = 1.0;
  22564. this.emissiveMap = null;
  22565. this.specularMap = null;
  22566. this.alphaMap = null;
  22567. this.envMap = null;
  22568. this.combine = MultiplyOperation;
  22569. this.reflectivity = 1;
  22570. this.refractionRatio = 0.98;
  22571. this.wireframe = false;
  22572. this.wireframeLinewidth = 1;
  22573. this.wireframeLinecap = 'round';
  22574. this.wireframeLinejoin = 'round';
  22575. this.skinning = false;
  22576. this.morphTargets = false;
  22577. this.morphNormals = false;
  22578. this.setValues( parameters );
  22579. }
  22580. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  22581. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  22582. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  22583. MeshLambertMaterial.prototype.copy = function ( source ) {
  22584. Material.prototype.copy.call( this, source );
  22585. this.color.copy( source.color );
  22586. this.map = source.map;
  22587. this.lightMap = source.lightMap;
  22588. this.lightMapIntensity = source.lightMapIntensity;
  22589. this.aoMap = source.aoMap;
  22590. this.aoMapIntensity = source.aoMapIntensity;
  22591. this.emissive.copy( source.emissive );
  22592. this.emissiveMap = source.emissiveMap;
  22593. this.emissiveIntensity = source.emissiveIntensity;
  22594. this.specularMap = source.specularMap;
  22595. this.alphaMap = source.alphaMap;
  22596. this.envMap = source.envMap;
  22597. this.combine = source.combine;
  22598. this.reflectivity = source.reflectivity;
  22599. this.refractionRatio = source.refractionRatio;
  22600. this.wireframe = source.wireframe;
  22601. this.wireframeLinewidth = source.wireframeLinewidth;
  22602. this.wireframeLinecap = source.wireframeLinecap;
  22603. this.wireframeLinejoin = source.wireframeLinejoin;
  22604. this.skinning = source.skinning;
  22605. this.morphTargets = source.morphTargets;
  22606. this.morphNormals = source.morphNormals;
  22607. return this;
  22608. };
  22609. /**
  22610. * @author alteredq / http://alteredqualia.com/
  22611. *
  22612. * parameters = {
  22613. * color: <hex>,
  22614. * opacity: <float>,
  22615. *
  22616. * linewidth: <float>,
  22617. *
  22618. * scale: <float>,
  22619. * dashSize: <float>,
  22620. * gapSize: <float>
  22621. * }
  22622. */
  22623. function LineDashedMaterial( parameters ) {
  22624. LineBasicMaterial.call( this );
  22625. this.type = 'LineDashedMaterial';
  22626. this.scale = 1;
  22627. this.dashSize = 3;
  22628. this.gapSize = 1;
  22629. this.setValues( parameters );
  22630. }
  22631. LineDashedMaterial.prototype = Object.create( LineBasicMaterial.prototype );
  22632. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  22633. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  22634. LineDashedMaterial.prototype.copy = function ( source ) {
  22635. LineBasicMaterial.prototype.copy.call( this, source );
  22636. this.scale = source.scale;
  22637. this.dashSize = source.dashSize;
  22638. this.gapSize = source.gapSize;
  22639. return this;
  22640. };
  22641. var Materials = Object.freeze({
  22642. ShadowMaterial: ShadowMaterial,
  22643. SpriteMaterial: SpriteMaterial,
  22644. RawShaderMaterial: RawShaderMaterial,
  22645. ShaderMaterial: ShaderMaterial,
  22646. PointsMaterial: PointsMaterial,
  22647. MeshPhysicalMaterial: MeshPhysicalMaterial,
  22648. MeshStandardMaterial: MeshStandardMaterial,
  22649. MeshPhongMaterial: MeshPhongMaterial,
  22650. MeshToonMaterial: MeshToonMaterial,
  22651. MeshNormalMaterial: MeshNormalMaterial,
  22652. MeshLambertMaterial: MeshLambertMaterial,
  22653. MeshDepthMaterial: MeshDepthMaterial,
  22654. MeshDistanceMaterial: MeshDistanceMaterial,
  22655. MeshBasicMaterial: MeshBasicMaterial,
  22656. LineDashedMaterial: LineDashedMaterial,
  22657. LineBasicMaterial: LineBasicMaterial,
  22658. Material: Material
  22659. });
  22660. /**
  22661. * @author mrdoob / http://mrdoob.com/
  22662. */
  22663. var Cache = {
  22664. enabled: false,
  22665. files: {},
  22666. add: function ( key, file ) {
  22667. if ( this.enabled === false ) return;
  22668. // console.log( 'THREE.Cache', 'Adding key:', key );
  22669. this.files[ key ] = file;
  22670. },
  22671. get: function ( key ) {
  22672. if ( this.enabled === false ) return;
  22673. // console.log( 'THREE.Cache', 'Checking key:', key );
  22674. return this.files[ key ];
  22675. },
  22676. remove: function ( key ) {
  22677. delete this.files[ key ];
  22678. },
  22679. clear: function () {
  22680. this.files = {};
  22681. }
  22682. };
  22683. /**
  22684. * @author mrdoob / http://mrdoob.com/
  22685. */
  22686. function LoadingManager( onLoad, onProgress, onError ) {
  22687. var scope = this;
  22688. var isLoading = false;
  22689. var itemsLoaded = 0;
  22690. var itemsTotal = 0;
  22691. var urlModifier = undefined;
  22692. this.onStart = undefined;
  22693. this.onLoad = onLoad;
  22694. this.onProgress = onProgress;
  22695. this.onError = onError;
  22696. this.itemStart = function ( url ) {
  22697. itemsTotal ++;
  22698. if ( isLoading === false ) {
  22699. if ( scope.onStart !== undefined ) {
  22700. scope.onStart( url, itemsLoaded, itemsTotal );
  22701. }
  22702. }
  22703. isLoading = true;
  22704. };
  22705. this.itemEnd = function ( url ) {
  22706. itemsLoaded ++;
  22707. if ( scope.onProgress !== undefined ) {
  22708. scope.onProgress( url, itemsLoaded, itemsTotal );
  22709. }
  22710. if ( itemsLoaded === itemsTotal ) {
  22711. isLoading = false;
  22712. if ( scope.onLoad !== undefined ) {
  22713. scope.onLoad();
  22714. }
  22715. }
  22716. };
  22717. this.itemError = function ( url ) {
  22718. if ( scope.onError !== undefined ) {
  22719. scope.onError( url );
  22720. }
  22721. };
  22722. this.resolveURL = function ( url ) {
  22723. if ( urlModifier ) {
  22724. return urlModifier( url );
  22725. }
  22726. return url;
  22727. };
  22728. this.setURLModifier = function ( transform ) {
  22729. urlModifier = transform;
  22730. return this;
  22731. };
  22732. }
  22733. var DefaultLoadingManager = new LoadingManager();
  22734. /**
  22735. * @author mrdoob / http://mrdoob.com/
  22736. */
  22737. var loading = {};
  22738. function FileLoader( manager ) {
  22739. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22740. }
  22741. Object.assign( FileLoader.prototype, {
  22742. load: function ( url, onLoad, onProgress, onError ) {
  22743. if ( url === undefined ) url = '';
  22744. if ( this.path !== undefined ) url = this.path + url;
  22745. url = this.manager.resolveURL( url );
  22746. var scope = this;
  22747. var cached = Cache.get( url );
  22748. if ( cached !== undefined ) {
  22749. scope.manager.itemStart( url );
  22750. setTimeout( function () {
  22751. if ( onLoad ) onLoad( cached );
  22752. scope.manager.itemEnd( url );
  22753. }, 0 );
  22754. return cached;
  22755. }
  22756. // Check if request is duplicate
  22757. if ( loading[ url ] !== undefined ) {
  22758. loading[ url ].push( {
  22759. onLoad: onLoad,
  22760. onProgress: onProgress,
  22761. onError: onError
  22762. } );
  22763. return;
  22764. }
  22765. // Check for data: URI
  22766. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  22767. var dataUriRegexResult = url.match( dataUriRegex );
  22768. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  22769. if ( dataUriRegexResult ) {
  22770. var mimeType = dataUriRegexResult[ 1 ];
  22771. var isBase64 = !! dataUriRegexResult[ 2 ];
  22772. var data = dataUriRegexResult[ 3 ];
  22773. data = window.decodeURIComponent( data );
  22774. if ( isBase64 ) data = window.atob( data );
  22775. try {
  22776. var response;
  22777. var responseType = ( this.responseType || '' ).toLowerCase();
  22778. switch ( responseType ) {
  22779. case 'arraybuffer':
  22780. case 'blob':
  22781. var view = new Uint8Array( data.length );
  22782. for ( var i = 0; i < data.length; i ++ ) {
  22783. view[ i ] = data.charCodeAt( i );
  22784. }
  22785. if ( responseType === 'blob' ) {
  22786. response = new Blob( [ view.buffer ], { type: mimeType } );
  22787. } else {
  22788. response = view.buffer;
  22789. }
  22790. break;
  22791. case 'document':
  22792. var parser = new DOMParser();
  22793. response = parser.parseFromString( data, mimeType );
  22794. break;
  22795. case 'json':
  22796. response = JSON.parse( data );
  22797. break;
  22798. default: // 'text' or other
  22799. response = data;
  22800. break;
  22801. }
  22802. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22803. window.setTimeout( function () {
  22804. if ( onLoad ) onLoad( response );
  22805. scope.manager.itemEnd( url );
  22806. }, 0 );
  22807. } catch ( error ) {
  22808. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  22809. window.setTimeout( function () {
  22810. if ( onError ) onError( error );
  22811. scope.manager.itemEnd( url );
  22812. scope.manager.itemError( url );
  22813. }, 0 );
  22814. }
  22815. } else {
  22816. // Initialise array for duplicate requests
  22817. loading[ url ] = [];
  22818. loading[ url ].push( {
  22819. onLoad: onLoad,
  22820. onProgress: onProgress,
  22821. onError: onError
  22822. } );
  22823. var request = new XMLHttpRequest();
  22824. request.open( 'GET', url, true );
  22825. request.addEventListener( 'load', function ( event ) {
  22826. var response = this.response;
  22827. Cache.add( url, response );
  22828. var callbacks = loading[ url ];
  22829. delete loading[ url ];
  22830. if ( this.status === 200 ) {
  22831. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22832. var callback = callbacks[ i ];
  22833. if ( callback.onLoad ) callback.onLoad( response );
  22834. }
  22835. scope.manager.itemEnd( url );
  22836. } else if ( this.status === 0 ) {
  22837. // Some browsers return HTTP Status 0 when using non-http protocol
  22838. // e.g. 'file://' or 'data://'. Handle as success.
  22839. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  22840. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22841. var callback = callbacks[ i ];
  22842. if ( callback.onLoad ) callback.onLoad( response );
  22843. }
  22844. scope.manager.itemEnd( url );
  22845. } else {
  22846. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22847. var callback = callbacks[ i ];
  22848. if ( callback.onError ) callback.onError( event );
  22849. }
  22850. scope.manager.itemEnd( url );
  22851. scope.manager.itemError( url );
  22852. }
  22853. }, false );
  22854. request.addEventListener( 'progress', function ( event ) {
  22855. var callbacks = loading[ url ];
  22856. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22857. var callback = callbacks[ i ];
  22858. if ( callback.onProgress ) callback.onProgress( event );
  22859. }
  22860. }, false );
  22861. request.addEventListener( 'error', function ( event ) {
  22862. var callbacks = loading[ url ];
  22863. delete loading[ url ];
  22864. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  22865. var callback = callbacks[ i ];
  22866. if ( callback.onError ) callback.onError( event );
  22867. }
  22868. scope.manager.itemEnd( url );
  22869. scope.manager.itemError( url );
  22870. }, false );
  22871. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  22872. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  22873. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  22874. for ( var header in this.requestHeader ) {
  22875. request.setRequestHeader( header, this.requestHeader[ header ] );
  22876. }
  22877. request.send( null );
  22878. }
  22879. scope.manager.itemStart( url );
  22880. return request;
  22881. },
  22882. setPath: function ( value ) {
  22883. this.path = value;
  22884. return this;
  22885. },
  22886. setResponseType: function ( value ) {
  22887. this.responseType = value;
  22888. return this;
  22889. },
  22890. setWithCredentials: function ( value ) {
  22891. this.withCredentials = value;
  22892. return this;
  22893. },
  22894. setMimeType: function ( value ) {
  22895. this.mimeType = value;
  22896. return this;
  22897. },
  22898. setRequestHeader: function ( value ) {
  22899. this.requestHeader = value;
  22900. return this;
  22901. }
  22902. } );
  22903. /**
  22904. * @author mrdoob / http://mrdoob.com/
  22905. *
  22906. * Abstract Base class to block based textures loader (dds, pvr, ...)
  22907. */
  22908. function CompressedTextureLoader( manager ) {
  22909. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22910. // override in sub classes
  22911. this._parser = null;
  22912. }
  22913. Object.assign( CompressedTextureLoader.prototype, {
  22914. load: function ( url, onLoad, onProgress, onError ) {
  22915. var scope = this;
  22916. var images = [];
  22917. var texture = new CompressedTexture();
  22918. texture.image = images;
  22919. var loader = new FileLoader( this.manager );
  22920. loader.setPath( this.path );
  22921. loader.setResponseType( 'arraybuffer' );
  22922. function loadTexture( i ) {
  22923. loader.load( url[ i ], function ( buffer ) {
  22924. var texDatas = scope._parser( buffer, true );
  22925. images[ i ] = {
  22926. width: texDatas.width,
  22927. height: texDatas.height,
  22928. format: texDatas.format,
  22929. mipmaps: texDatas.mipmaps
  22930. };
  22931. loaded += 1;
  22932. if ( loaded === 6 ) {
  22933. if ( texDatas.mipmapCount === 1 )
  22934. texture.minFilter = LinearFilter;
  22935. texture.format = texDatas.format;
  22936. texture.needsUpdate = true;
  22937. if ( onLoad ) onLoad( texture );
  22938. }
  22939. }, onProgress, onError );
  22940. }
  22941. if ( Array.isArray( url ) ) {
  22942. var loaded = 0;
  22943. for ( var i = 0, il = url.length; i < il; ++ i ) {
  22944. loadTexture( i );
  22945. }
  22946. } else {
  22947. // compressed cubemap texture stored in a single DDS file
  22948. loader.load( url, function ( buffer ) {
  22949. var texDatas = scope._parser( buffer, true );
  22950. if ( texDatas.isCubemap ) {
  22951. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  22952. for ( var f = 0; f < faces; f ++ ) {
  22953. images[ f ] = { mipmaps: [] };
  22954. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  22955. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  22956. images[ f ].format = texDatas.format;
  22957. images[ f ].width = texDatas.width;
  22958. images[ f ].height = texDatas.height;
  22959. }
  22960. }
  22961. } else {
  22962. texture.image.width = texDatas.width;
  22963. texture.image.height = texDatas.height;
  22964. texture.mipmaps = texDatas.mipmaps;
  22965. }
  22966. if ( texDatas.mipmapCount === 1 ) {
  22967. texture.minFilter = LinearFilter;
  22968. }
  22969. texture.format = texDatas.format;
  22970. texture.needsUpdate = true;
  22971. if ( onLoad ) onLoad( texture );
  22972. }, onProgress, onError );
  22973. }
  22974. return texture;
  22975. },
  22976. setPath: function ( value ) {
  22977. this.path = value;
  22978. return this;
  22979. }
  22980. } );
  22981. /**
  22982. * @author Nikos M. / https://github.com/foo123/
  22983. *
  22984. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  22985. */
  22986. function DataTextureLoader( manager ) {
  22987. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22988. // override in sub classes
  22989. this._parser = null;
  22990. }
  22991. Object.assign( DataTextureLoader.prototype, {
  22992. load: function ( url, onLoad, onProgress, onError ) {
  22993. var scope = this;
  22994. var texture = new DataTexture();
  22995. var loader = new FileLoader( this.manager );
  22996. loader.setResponseType( 'arraybuffer' );
  22997. loader.load( url, function ( buffer ) {
  22998. var texData = scope._parser( buffer );
  22999. if ( ! texData ) return;
  23000. if ( undefined !== texData.image ) {
  23001. texture.image = texData.image;
  23002. } else if ( undefined !== texData.data ) {
  23003. texture.image.width = texData.width;
  23004. texture.image.height = texData.height;
  23005. texture.image.data = texData.data;
  23006. }
  23007. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  23008. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  23009. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  23010. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  23011. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  23012. if ( undefined !== texData.format ) {
  23013. texture.format = texData.format;
  23014. }
  23015. if ( undefined !== texData.type ) {
  23016. texture.type = texData.type;
  23017. }
  23018. if ( undefined !== texData.mipmaps ) {
  23019. texture.mipmaps = texData.mipmaps;
  23020. }
  23021. if ( 1 === texData.mipmapCount ) {
  23022. texture.minFilter = LinearFilter;
  23023. }
  23024. texture.needsUpdate = true;
  23025. if ( onLoad ) onLoad( texture, texData );
  23026. }, onProgress, onError );
  23027. return texture;
  23028. }
  23029. } );
  23030. /**
  23031. * @author mrdoob / http://mrdoob.com/
  23032. */
  23033. function ImageLoader( manager ) {
  23034. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23035. }
  23036. Object.assign( ImageLoader.prototype, {
  23037. crossOrigin: 'Anonymous',
  23038. load: function ( url, onLoad, onProgress, onError ) {
  23039. if ( url === undefined ) url = '';
  23040. if ( this.path !== undefined ) url = this.path + url;
  23041. url = this.manager.resolveURL( url );
  23042. var scope = this;
  23043. var cached = Cache.get( url );
  23044. if ( cached !== undefined ) {
  23045. scope.manager.itemStart( url );
  23046. setTimeout( function () {
  23047. if ( onLoad ) onLoad( cached );
  23048. scope.manager.itemEnd( url );
  23049. }, 0 );
  23050. return cached;
  23051. }
  23052. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  23053. image.addEventListener( 'load', function () {
  23054. Cache.add( url, this );
  23055. if ( onLoad ) onLoad( this );
  23056. scope.manager.itemEnd( url );
  23057. }, false );
  23058. /*
  23059. image.addEventListener( 'progress', function ( event ) {
  23060. if ( onProgress ) onProgress( event );
  23061. }, false );
  23062. */
  23063. image.addEventListener( 'error', function ( event ) {
  23064. if ( onError ) onError( event );
  23065. scope.manager.itemEnd( url );
  23066. scope.manager.itemError( url );
  23067. }, false );
  23068. if ( url.substr( 0, 5 ) !== 'data:' ) {
  23069. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  23070. }
  23071. scope.manager.itemStart( url );
  23072. image.src = url;
  23073. return image;
  23074. },
  23075. setCrossOrigin: function ( value ) {
  23076. this.crossOrigin = value;
  23077. return this;
  23078. },
  23079. setPath: function ( value ) {
  23080. this.path = value;
  23081. return this;
  23082. }
  23083. } );
  23084. /**
  23085. * @author mrdoob / http://mrdoob.com/
  23086. */
  23087. function CubeTextureLoader( manager ) {
  23088. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23089. }
  23090. Object.assign( CubeTextureLoader.prototype, {
  23091. crossOrigin: 'Anonymous',
  23092. load: function ( urls, onLoad, onProgress, onError ) {
  23093. var texture = new CubeTexture();
  23094. var loader = new ImageLoader( this.manager );
  23095. loader.setCrossOrigin( this.crossOrigin );
  23096. loader.setPath( this.path );
  23097. var loaded = 0;
  23098. function loadTexture( i ) {
  23099. loader.load( urls[ i ], function ( image ) {
  23100. texture.images[ i ] = image;
  23101. loaded ++;
  23102. if ( loaded === 6 ) {
  23103. texture.needsUpdate = true;
  23104. if ( onLoad ) onLoad( texture );
  23105. }
  23106. }, undefined, onError );
  23107. }
  23108. for ( var i = 0; i < urls.length; ++ i ) {
  23109. loadTexture( i );
  23110. }
  23111. return texture;
  23112. },
  23113. setCrossOrigin: function ( value ) {
  23114. this.crossOrigin = value;
  23115. return this;
  23116. },
  23117. setPath: function ( value ) {
  23118. this.path = value;
  23119. return this;
  23120. }
  23121. } );
  23122. /**
  23123. * @author mrdoob / http://mrdoob.com/
  23124. */
  23125. function TextureLoader( manager ) {
  23126. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23127. }
  23128. Object.assign( TextureLoader.prototype, {
  23129. crossOrigin: 'Anonymous',
  23130. load: function ( url, onLoad, onProgress, onError ) {
  23131. var texture = new Texture();
  23132. var loader = new ImageLoader( this.manager );
  23133. loader.setCrossOrigin( this.crossOrigin );
  23134. loader.setPath( this.path );
  23135. loader.load( url, function ( image ) {
  23136. texture.image = image;
  23137. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  23138. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  23139. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  23140. texture.needsUpdate = true;
  23141. if ( onLoad !== undefined ) {
  23142. onLoad( texture );
  23143. }
  23144. }, onProgress, onError );
  23145. return texture;
  23146. },
  23147. setCrossOrigin: function ( value ) {
  23148. this.crossOrigin = value;
  23149. return this;
  23150. },
  23151. setPath: function ( value ) {
  23152. this.path = value;
  23153. return this;
  23154. }
  23155. } );
  23156. /**
  23157. * @author zz85 / http://www.lab4games.net/zz85/blog
  23158. * Extensible curve object
  23159. *
  23160. * Some common of curve methods:
  23161. * .getPoint( t, optionalTarget ), .getTangent( t )
  23162. * .getPointAt( u, optionalTarget ), .getTangentAt( u )
  23163. * .getPoints(), .getSpacedPoints()
  23164. * .getLength()
  23165. * .updateArcLengths()
  23166. *
  23167. * This following curves inherit from THREE.Curve:
  23168. *
  23169. * -- 2D curves --
  23170. * THREE.ArcCurve
  23171. * THREE.CubicBezierCurve
  23172. * THREE.EllipseCurve
  23173. * THREE.LineCurve
  23174. * THREE.QuadraticBezierCurve
  23175. * THREE.SplineCurve
  23176. *
  23177. * -- 3D curves --
  23178. * THREE.CatmullRomCurve3
  23179. * THREE.CubicBezierCurve3
  23180. * THREE.LineCurve3
  23181. * THREE.QuadraticBezierCurve3
  23182. *
  23183. * A series of curves can be represented as a THREE.CurvePath.
  23184. *
  23185. **/
  23186. /**************************************************************
  23187. * Abstract Curve base class
  23188. **************************************************************/
  23189. function Curve() {
  23190. this.type = 'Curve';
  23191. this.arcLengthDivisions = 200;
  23192. }
  23193. Object.assign( Curve.prototype, {
  23194. // Virtual base class method to overwrite and implement in subclasses
  23195. // - t [0 .. 1]
  23196. getPoint: function ( /* t, optionalTarget */ ) {
  23197. console.warn( 'THREE.Curve: .getPoint() not implemented.' );
  23198. return null;
  23199. },
  23200. // Get point at relative position in curve according to arc length
  23201. // - u [0 .. 1]
  23202. getPointAt: function ( u, optionalTarget ) {
  23203. var t = this.getUtoTmapping( u );
  23204. return this.getPoint( t, optionalTarget );
  23205. },
  23206. // Get sequence of points using getPoint( t )
  23207. getPoints: function ( divisions ) {
  23208. if ( divisions === undefined ) divisions = 5;
  23209. var points = [];
  23210. for ( var d = 0; d <= divisions; d ++ ) {
  23211. points.push( this.getPoint( d / divisions ) );
  23212. }
  23213. return points;
  23214. },
  23215. // Get sequence of points using getPointAt( u )
  23216. getSpacedPoints: function ( divisions ) {
  23217. if ( divisions === undefined ) divisions = 5;
  23218. var points = [];
  23219. for ( var d = 0; d <= divisions; d ++ ) {
  23220. points.push( this.getPointAt( d / divisions ) );
  23221. }
  23222. return points;
  23223. },
  23224. // Get total curve arc length
  23225. getLength: function () {
  23226. var lengths = this.getLengths();
  23227. return lengths[ lengths.length - 1 ];
  23228. },
  23229. // Get list of cumulative segment lengths
  23230. getLengths: function ( divisions ) {
  23231. if ( divisions === undefined ) divisions = this.arcLengthDivisions;
  23232. if ( this.cacheArcLengths &&
  23233. ( this.cacheArcLengths.length === divisions + 1 ) &&
  23234. ! this.needsUpdate ) {
  23235. return this.cacheArcLengths;
  23236. }
  23237. this.needsUpdate = false;
  23238. var cache = [];
  23239. var current, last = this.getPoint( 0 );
  23240. var p, sum = 0;
  23241. cache.push( 0 );
  23242. for ( p = 1; p <= divisions; p ++ ) {
  23243. current = this.getPoint( p / divisions );
  23244. sum += current.distanceTo( last );
  23245. cache.push( sum );
  23246. last = current;
  23247. }
  23248. this.cacheArcLengths = cache;
  23249. return cache; // { sums: cache, sum: sum }; Sum is in the last element.
  23250. },
  23251. updateArcLengths: function () {
  23252. this.needsUpdate = true;
  23253. this.getLengths();
  23254. },
  23255. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  23256. getUtoTmapping: function ( u, distance ) {
  23257. var arcLengths = this.getLengths();
  23258. var i = 0, il = arcLengths.length;
  23259. var targetArcLength; // The targeted u distance value to get
  23260. if ( distance ) {
  23261. targetArcLength = distance;
  23262. } else {
  23263. targetArcLength = u * arcLengths[ il - 1 ];
  23264. }
  23265. // binary search for the index with largest value smaller than target u distance
  23266. var low = 0, high = il - 1, comparison;
  23267. while ( low <= high ) {
  23268. 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
  23269. comparison = arcLengths[ i ] - targetArcLength;
  23270. if ( comparison < 0 ) {
  23271. low = i + 1;
  23272. } else if ( comparison > 0 ) {
  23273. high = i - 1;
  23274. } else {
  23275. high = i;
  23276. break;
  23277. // DONE
  23278. }
  23279. }
  23280. i = high;
  23281. if ( arcLengths[ i ] === targetArcLength ) {
  23282. return i / ( il - 1 );
  23283. }
  23284. // we could get finer grain at lengths, or use simple interpolation between two points
  23285. var lengthBefore = arcLengths[ i ];
  23286. var lengthAfter = arcLengths[ i + 1 ];
  23287. var segmentLength = lengthAfter - lengthBefore;
  23288. // determine where we are between the 'before' and 'after' points
  23289. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  23290. // add that fractional amount to t
  23291. var t = ( i + segmentFraction ) / ( il - 1 );
  23292. return t;
  23293. },
  23294. // Returns a unit vector tangent at t
  23295. // In case any sub curve does not implement its tangent derivation,
  23296. // 2 points a small delta apart will be used to find its gradient
  23297. // which seems to give a reasonable approximation
  23298. getTangent: function ( t ) {
  23299. var delta = 0.0001;
  23300. var t1 = t - delta;
  23301. var t2 = t + delta;
  23302. // Capping in case of danger
  23303. if ( t1 < 0 ) t1 = 0;
  23304. if ( t2 > 1 ) t2 = 1;
  23305. var pt1 = this.getPoint( t1 );
  23306. var pt2 = this.getPoint( t2 );
  23307. var vec = pt2.clone().sub( pt1 );
  23308. return vec.normalize();
  23309. },
  23310. getTangentAt: function ( u ) {
  23311. var t = this.getUtoTmapping( u );
  23312. return this.getTangent( t );
  23313. },
  23314. computeFrenetFrames: function ( segments, closed ) {
  23315. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  23316. var normal = new Vector3();
  23317. var tangents = [];
  23318. var normals = [];
  23319. var binormals = [];
  23320. var vec = new Vector3();
  23321. var mat = new Matrix4();
  23322. var i, u, theta;
  23323. // compute the tangent vectors for each segment on the curve
  23324. for ( i = 0; i <= segments; i ++ ) {
  23325. u = i / segments;
  23326. tangents[ i ] = this.getTangentAt( u );
  23327. tangents[ i ].normalize();
  23328. }
  23329. // select an initial normal vector perpendicular to the first tangent vector,
  23330. // and in the direction of the minimum tangent xyz component
  23331. normals[ 0 ] = new Vector3();
  23332. binormals[ 0 ] = new Vector3();
  23333. var min = Number.MAX_VALUE;
  23334. var tx = Math.abs( tangents[ 0 ].x );
  23335. var ty = Math.abs( tangents[ 0 ].y );
  23336. var tz = Math.abs( tangents[ 0 ].z );
  23337. if ( tx <= min ) {
  23338. min = tx;
  23339. normal.set( 1, 0, 0 );
  23340. }
  23341. if ( ty <= min ) {
  23342. min = ty;
  23343. normal.set( 0, 1, 0 );
  23344. }
  23345. if ( tz <= min ) {
  23346. normal.set( 0, 0, 1 );
  23347. }
  23348. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  23349. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  23350. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  23351. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  23352. for ( i = 1; i <= segments; i ++ ) {
  23353. normals[ i ] = normals[ i - 1 ].clone();
  23354. binormals[ i ] = binormals[ i - 1 ].clone();
  23355. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  23356. if ( vec.length() > Number.EPSILON ) {
  23357. vec.normalize();
  23358. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  23359. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  23360. }
  23361. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23362. }
  23363. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  23364. if ( closed === true ) {
  23365. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  23366. theta /= segments;
  23367. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  23368. theta = - theta;
  23369. }
  23370. for ( i = 1; i <= segments; i ++ ) {
  23371. // twist a little...
  23372. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  23373. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  23374. }
  23375. }
  23376. return {
  23377. tangents: tangents,
  23378. normals: normals,
  23379. binormals: binormals
  23380. };
  23381. },
  23382. clone: function () {
  23383. return new this.constructor().copy( this );
  23384. },
  23385. copy: function ( source ) {
  23386. this.arcLengthDivisions = source.arcLengthDivisions;
  23387. return this;
  23388. },
  23389. toJSON: function () {
  23390. var data = {
  23391. metadata: {
  23392. version: 4.5,
  23393. type: 'Curve',
  23394. generator: 'Curve.toJSON'
  23395. }
  23396. };
  23397. data.arcLengthDivisions = this.arcLengthDivisions;
  23398. data.type = this.type;
  23399. return data;
  23400. },
  23401. fromJSON: function ( json ) {
  23402. this.arcLengthDivisions = json.arcLengthDivisions;
  23403. return this;
  23404. }
  23405. } );
  23406. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  23407. Curve.call( this );
  23408. this.type = 'EllipseCurve';
  23409. this.aX = aX || 0;
  23410. this.aY = aY || 0;
  23411. this.xRadius = xRadius || 1;
  23412. this.yRadius = yRadius || 1;
  23413. this.aStartAngle = aStartAngle || 0;
  23414. this.aEndAngle = aEndAngle || 2 * Math.PI;
  23415. this.aClockwise = aClockwise || false;
  23416. this.aRotation = aRotation || 0;
  23417. }
  23418. EllipseCurve.prototype = Object.create( Curve.prototype );
  23419. EllipseCurve.prototype.constructor = EllipseCurve;
  23420. EllipseCurve.prototype.isEllipseCurve = true;
  23421. EllipseCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23422. var point = optionalTarget || new Vector2();
  23423. var twoPi = Math.PI * 2;
  23424. var deltaAngle = this.aEndAngle - this.aStartAngle;
  23425. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  23426. // ensures that deltaAngle is 0 .. 2 PI
  23427. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  23428. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  23429. if ( deltaAngle < Number.EPSILON ) {
  23430. if ( samePoints ) {
  23431. deltaAngle = 0;
  23432. } else {
  23433. deltaAngle = twoPi;
  23434. }
  23435. }
  23436. if ( this.aClockwise === true && ! samePoints ) {
  23437. if ( deltaAngle === twoPi ) {
  23438. deltaAngle = - twoPi;
  23439. } else {
  23440. deltaAngle = deltaAngle - twoPi;
  23441. }
  23442. }
  23443. var angle = this.aStartAngle + t * deltaAngle;
  23444. var x = this.aX + this.xRadius * Math.cos( angle );
  23445. var y = this.aY + this.yRadius * Math.sin( angle );
  23446. if ( this.aRotation !== 0 ) {
  23447. var cos = Math.cos( this.aRotation );
  23448. var sin = Math.sin( this.aRotation );
  23449. var tx = x - this.aX;
  23450. var ty = y - this.aY;
  23451. // Rotate the point about the center of the ellipse.
  23452. x = tx * cos - ty * sin + this.aX;
  23453. y = tx * sin + ty * cos + this.aY;
  23454. }
  23455. return point.set( x, y );
  23456. };
  23457. EllipseCurve.prototype.copy = function ( source ) {
  23458. Curve.prototype.copy.call( this, source );
  23459. this.aX = source.aX;
  23460. this.aY = source.aY;
  23461. this.xRadius = source.xRadius;
  23462. this.yRadius = source.yRadius;
  23463. this.aStartAngle = source.aStartAngle;
  23464. this.aEndAngle = source.aEndAngle;
  23465. this.aClockwise = source.aClockwise;
  23466. this.aRotation = source.aRotation;
  23467. return this;
  23468. };
  23469. EllipseCurve.prototype.toJSON = function () {
  23470. var data = Curve.prototype.toJSON.call( this );
  23471. data.aX = this.aX;
  23472. data.aY = this.aY;
  23473. data.xRadius = this.xRadius;
  23474. data.yRadius = this.yRadius;
  23475. data.aStartAngle = this.aStartAngle;
  23476. data.aEndAngle = this.aEndAngle;
  23477. data.aClockwise = this.aClockwise;
  23478. data.aRotation = this.aRotation;
  23479. return data;
  23480. };
  23481. EllipseCurve.prototype.fromJSON = function ( json ) {
  23482. Curve.prototype.fromJSON.call( this, json );
  23483. this.aX = json.aX;
  23484. this.aY = json.aY;
  23485. this.xRadius = json.xRadius;
  23486. this.yRadius = json.yRadius;
  23487. this.aStartAngle = json.aStartAngle;
  23488. this.aEndAngle = json.aEndAngle;
  23489. this.aClockwise = json.aClockwise;
  23490. this.aRotation = json.aRotation;
  23491. return this;
  23492. };
  23493. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  23494. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  23495. this.type = 'ArcCurve';
  23496. }
  23497. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  23498. ArcCurve.prototype.constructor = ArcCurve;
  23499. ArcCurve.prototype.isArcCurve = true;
  23500. /**
  23501. * @author zz85 https://github.com/zz85
  23502. *
  23503. * Centripetal CatmullRom Curve - which is useful for avoiding
  23504. * cusps and self-intersections in non-uniform catmull rom curves.
  23505. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  23506. *
  23507. * curve.type accepts centripetal(default), chordal and catmullrom
  23508. * curve.tension is used for catmullrom which defaults to 0.5
  23509. */
  23510. /*
  23511. Based on an optimized c++ solution in
  23512. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  23513. - http://ideone.com/NoEbVM
  23514. This CubicPoly class could be used for reusing some variables and calculations,
  23515. but for three.js curve use, it could be possible inlined and flatten into a single function call
  23516. which can be placed in CurveUtils.
  23517. */
  23518. function CubicPoly() {
  23519. var c0 = 0, c1 = 0, c2 = 0, c3 = 0;
  23520. /*
  23521. * Compute coefficients for a cubic polynomial
  23522. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  23523. * such that
  23524. * p(0) = x0, p(1) = x1
  23525. * and
  23526. * p'(0) = t0, p'(1) = t1.
  23527. */
  23528. function init( x0, x1, t0, t1 ) {
  23529. c0 = x0;
  23530. c1 = t0;
  23531. c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  23532. c3 = 2 * x0 - 2 * x1 + t0 + t1;
  23533. }
  23534. return {
  23535. initCatmullRom: function ( x0, x1, x2, x3, tension ) {
  23536. init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  23537. },
  23538. initNonuniformCatmullRom: function ( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  23539. // compute tangents when parameterized in [t1,t2]
  23540. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  23541. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  23542. // rescale tangents for parametrization in [0,1]
  23543. t1 *= dt1;
  23544. t2 *= dt1;
  23545. init( x1, x2, t1, t2 );
  23546. },
  23547. calc: function ( t ) {
  23548. var t2 = t * t;
  23549. var t3 = t2 * t;
  23550. return c0 + c1 * t + c2 * t2 + c3 * t3;
  23551. }
  23552. };
  23553. }
  23554. //
  23555. var tmp = new Vector3();
  23556. var px = new CubicPoly();
  23557. var py = new CubicPoly();
  23558. var pz = new CubicPoly();
  23559. function CatmullRomCurve3( points, closed, curveType, tension ) {
  23560. Curve.call( this );
  23561. this.type = 'CatmullRomCurve3';
  23562. this.points = points || [];
  23563. this.closed = closed || false;
  23564. this.curveType = curveType || 'centripetal';
  23565. this.tension = tension || 0.5;
  23566. }
  23567. CatmullRomCurve3.prototype = Object.create( Curve.prototype );
  23568. CatmullRomCurve3.prototype.constructor = CatmullRomCurve3;
  23569. CatmullRomCurve3.prototype.isCatmullRomCurve3 = true;
  23570. CatmullRomCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23571. var point = optionalTarget || new Vector3();
  23572. var points = this.points;
  23573. var l = points.length;
  23574. var p = ( l - ( this.closed ? 0 : 1 ) ) * t;
  23575. var intPoint = Math.floor( p );
  23576. var weight = p - intPoint;
  23577. if ( this.closed ) {
  23578. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  23579. } else if ( weight === 0 && intPoint === l - 1 ) {
  23580. intPoint = l - 2;
  23581. weight = 1;
  23582. }
  23583. var p0, p1, p2, p3; // 4 points
  23584. if ( this.closed || intPoint > 0 ) {
  23585. p0 = points[ ( intPoint - 1 ) % l ];
  23586. } else {
  23587. // extrapolate first point
  23588. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  23589. p0 = tmp;
  23590. }
  23591. p1 = points[ intPoint % l ];
  23592. p2 = points[ ( intPoint + 1 ) % l ];
  23593. if ( this.closed || intPoint + 2 < l ) {
  23594. p3 = points[ ( intPoint + 2 ) % l ];
  23595. } else {
  23596. // extrapolate last point
  23597. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  23598. p3 = tmp;
  23599. }
  23600. if ( this.curveType === 'centripetal' || this.curveType === 'chordal' ) {
  23601. // init Centripetal / Chordal Catmull-Rom
  23602. var pow = this.curveType === 'chordal' ? 0.5 : 0.25;
  23603. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  23604. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  23605. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  23606. // safety check for repeated points
  23607. if ( dt1 < 1e-4 ) dt1 = 1.0;
  23608. if ( dt0 < 1e-4 ) dt0 = dt1;
  23609. if ( dt2 < 1e-4 ) dt2 = dt1;
  23610. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  23611. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  23612. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  23613. } else if ( this.curveType === 'catmullrom' ) {
  23614. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, this.tension );
  23615. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, this.tension );
  23616. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, this.tension );
  23617. }
  23618. point.set(
  23619. px.calc( weight ),
  23620. py.calc( weight ),
  23621. pz.calc( weight )
  23622. );
  23623. return point;
  23624. };
  23625. CatmullRomCurve3.prototype.copy = function ( source ) {
  23626. Curve.prototype.copy.call( this, source );
  23627. this.points = [];
  23628. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  23629. var point = source.points[ i ];
  23630. this.points.push( point.clone() );
  23631. }
  23632. this.closed = source.closed;
  23633. this.curveType = source.curveType;
  23634. this.tension = source.tension;
  23635. return this;
  23636. };
  23637. CatmullRomCurve3.prototype.toJSON = function () {
  23638. var data = Curve.prototype.toJSON.call( this );
  23639. data.points = [];
  23640. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  23641. var point = this.points[ i ];
  23642. data.points.push( point.toArray() );
  23643. }
  23644. data.closed = this.closed;
  23645. data.curveType = this.curveType;
  23646. data.tension = this.tension;
  23647. return data;
  23648. };
  23649. CatmullRomCurve3.prototype.fromJSON = function ( json ) {
  23650. Curve.prototype.fromJSON.call( this, json );
  23651. this.points = [];
  23652. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  23653. var point = json.points[ i ];
  23654. this.points.push( new Vector3().fromArray( point ) );
  23655. }
  23656. this.closed = json.closed;
  23657. this.curveType = json.curveType;
  23658. this.tension = json.tension;
  23659. return this;
  23660. };
  23661. /**
  23662. * @author zz85 / http://www.lab4games.net/zz85/blog
  23663. *
  23664. * Bezier Curves formulas obtained from
  23665. * http://en.wikipedia.org/wiki/Bézier_curve
  23666. */
  23667. function CatmullRom( t, p0, p1, p2, p3 ) {
  23668. var v0 = ( p2 - p0 ) * 0.5;
  23669. var v1 = ( p3 - p1 ) * 0.5;
  23670. var t2 = t * t;
  23671. var t3 = t * t2;
  23672. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  23673. }
  23674. //
  23675. function QuadraticBezierP0( t, p ) {
  23676. var k = 1 - t;
  23677. return k * k * p;
  23678. }
  23679. function QuadraticBezierP1( t, p ) {
  23680. return 2 * ( 1 - t ) * t * p;
  23681. }
  23682. function QuadraticBezierP2( t, p ) {
  23683. return t * t * p;
  23684. }
  23685. function QuadraticBezier( t, p0, p1, p2 ) {
  23686. return QuadraticBezierP0( t, p0 ) + QuadraticBezierP1( t, p1 ) +
  23687. QuadraticBezierP2( t, p2 );
  23688. }
  23689. //
  23690. function CubicBezierP0( t, p ) {
  23691. var k = 1 - t;
  23692. return k * k * k * p;
  23693. }
  23694. function CubicBezierP1( t, p ) {
  23695. var k = 1 - t;
  23696. return 3 * k * k * t * p;
  23697. }
  23698. function CubicBezierP2( t, p ) {
  23699. return 3 * ( 1 - t ) * t * t * p;
  23700. }
  23701. function CubicBezierP3( t, p ) {
  23702. return t * t * t * p;
  23703. }
  23704. function CubicBezier( t, p0, p1, p2, p3 ) {
  23705. return CubicBezierP0( t, p0 ) + CubicBezierP1( t, p1 ) + CubicBezierP2( t, p2 ) +
  23706. CubicBezierP3( t, p3 );
  23707. }
  23708. function CubicBezierCurve( v0, v1, v2, v3 ) {
  23709. Curve.call( this );
  23710. this.type = 'CubicBezierCurve';
  23711. this.v0 = v0 || new Vector2();
  23712. this.v1 = v1 || new Vector2();
  23713. this.v2 = v2 || new Vector2();
  23714. this.v3 = v3 || new Vector2();
  23715. }
  23716. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  23717. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  23718. CubicBezierCurve.prototype.isCubicBezierCurve = true;
  23719. CubicBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23720. var point = optionalTarget || new Vector2();
  23721. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23722. point.set(
  23723. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23724. CubicBezier( t, v0.y, v1.y, v2.y, v3.y )
  23725. );
  23726. return point;
  23727. };
  23728. CubicBezierCurve.prototype.copy = function ( source ) {
  23729. Curve.prototype.copy.call( this, source );
  23730. this.v0.copy( source.v0 );
  23731. this.v1.copy( source.v1 );
  23732. this.v2.copy( source.v2 );
  23733. this.v3.copy( source.v3 );
  23734. return this;
  23735. };
  23736. CubicBezierCurve.prototype.toJSON = function () {
  23737. var data = Curve.prototype.toJSON.call( this );
  23738. data.v0 = this.v0.toArray();
  23739. data.v1 = this.v1.toArray();
  23740. data.v2 = this.v2.toArray();
  23741. data.v3 = this.v3.toArray();
  23742. return data;
  23743. };
  23744. CubicBezierCurve.prototype.fromJSON = function ( json ) {
  23745. Curve.prototype.fromJSON.call( this, json );
  23746. this.v0.fromArray( json.v0 );
  23747. this.v1.fromArray( json.v1 );
  23748. this.v2.fromArray( json.v2 );
  23749. this.v3.fromArray( json.v3 );
  23750. return this;
  23751. };
  23752. function CubicBezierCurve3( v0, v1, v2, v3 ) {
  23753. Curve.call( this );
  23754. this.type = 'CubicBezierCurve3';
  23755. this.v0 = v0 || new Vector3();
  23756. this.v1 = v1 || new Vector3();
  23757. this.v2 = v2 || new Vector3();
  23758. this.v3 = v3 || new Vector3();
  23759. }
  23760. CubicBezierCurve3.prototype = Object.create( Curve.prototype );
  23761. CubicBezierCurve3.prototype.constructor = CubicBezierCurve3;
  23762. CubicBezierCurve3.prototype.isCubicBezierCurve3 = true;
  23763. CubicBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23764. var point = optionalTarget || new Vector3();
  23765. var v0 = this.v0, v1 = this.v1, v2 = this.v2, v3 = this.v3;
  23766. point.set(
  23767. CubicBezier( t, v0.x, v1.x, v2.x, v3.x ),
  23768. CubicBezier( t, v0.y, v1.y, v2.y, v3.y ),
  23769. CubicBezier( t, v0.z, v1.z, v2.z, v3.z )
  23770. );
  23771. return point;
  23772. };
  23773. CubicBezierCurve3.prototype.copy = function ( source ) {
  23774. Curve.prototype.copy.call( this, source );
  23775. this.v0.copy( source.v0 );
  23776. this.v1.copy( source.v1 );
  23777. this.v2.copy( source.v2 );
  23778. this.v3.copy( source.v3 );
  23779. return this;
  23780. };
  23781. CubicBezierCurve3.prototype.toJSON = function () {
  23782. var data = Curve.prototype.toJSON.call( this );
  23783. data.v0 = this.v0.toArray();
  23784. data.v1 = this.v1.toArray();
  23785. data.v2 = this.v2.toArray();
  23786. data.v3 = this.v3.toArray();
  23787. return data;
  23788. };
  23789. CubicBezierCurve3.prototype.fromJSON = function ( json ) {
  23790. Curve.prototype.fromJSON.call( this, json );
  23791. this.v0.fromArray( json.v0 );
  23792. this.v1.fromArray( json.v1 );
  23793. this.v2.fromArray( json.v2 );
  23794. this.v3.fromArray( json.v3 );
  23795. return this;
  23796. };
  23797. function LineCurve( v1, v2 ) {
  23798. Curve.call( this );
  23799. this.type = 'LineCurve';
  23800. this.v1 = v1 || new Vector2();
  23801. this.v2 = v2 || new Vector2();
  23802. }
  23803. LineCurve.prototype = Object.create( Curve.prototype );
  23804. LineCurve.prototype.constructor = LineCurve;
  23805. LineCurve.prototype.isLineCurve = true;
  23806. LineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23807. var point = optionalTarget || new Vector2();
  23808. if ( t === 1 ) {
  23809. point.copy( this.v2 );
  23810. } else {
  23811. point.copy( this.v2 ).sub( this.v1 );
  23812. point.multiplyScalar( t ).add( this.v1 );
  23813. }
  23814. return point;
  23815. };
  23816. // Line curve is linear, so we can overwrite default getPointAt
  23817. LineCurve.prototype.getPointAt = function ( u, optionalTarget ) {
  23818. return this.getPoint( u, optionalTarget );
  23819. };
  23820. LineCurve.prototype.getTangent = function ( /* t */ ) {
  23821. var tangent = this.v2.clone().sub( this.v1 );
  23822. return tangent.normalize();
  23823. };
  23824. LineCurve.prototype.copy = function ( source ) {
  23825. Curve.prototype.copy.call( this, source );
  23826. this.v1.copy( source.v1 );
  23827. this.v2.copy( source.v2 );
  23828. return this;
  23829. };
  23830. LineCurve.prototype.toJSON = function () {
  23831. var data = Curve.prototype.toJSON.call( this );
  23832. data.v1 = this.v1.toArray();
  23833. data.v2 = this.v2.toArray();
  23834. return data;
  23835. };
  23836. LineCurve.prototype.fromJSON = function ( json ) {
  23837. Curve.prototype.fromJSON.call( this, json );
  23838. this.v1.fromArray( json.v1 );
  23839. this.v2.fromArray( json.v2 );
  23840. return this;
  23841. };
  23842. function LineCurve3( v1, v2 ) {
  23843. Curve.call( this );
  23844. this.type = 'LineCurve3';
  23845. this.v1 = v1 || new Vector3();
  23846. this.v2 = v2 || new Vector3();
  23847. }
  23848. LineCurve3.prototype = Object.create( Curve.prototype );
  23849. LineCurve3.prototype.constructor = LineCurve3;
  23850. LineCurve3.prototype.isLineCurve3 = true;
  23851. LineCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23852. var point = optionalTarget || new Vector3();
  23853. if ( t === 1 ) {
  23854. point.copy( this.v2 );
  23855. } else {
  23856. point.copy( this.v2 ).sub( this.v1 );
  23857. point.multiplyScalar( t ).add( this.v1 );
  23858. }
  23859. return point;
  23860. };
  23861. // Line curve is linear, so we can overwrite default getPointAt
  23862. LineCurve3.prototype.getPointAt = function ( u, optionalTarget ) {
  23863. return this.getPoint( u, optionalTarget );
  23864. };
  23865. LineCurve3.prototype.copy = function ( source ) {
  23866. Curve.prototype.copy.call( this, source );
  23867. this.v1.copy( source.v1 );
  23868. this.v2.copy( source.v2 );
  23869. return this;
  23870. };
  23871. LineCurve3.prototype.toJSON = function () {
  23872. var data = Curve.prototype.toJSON.call( this );
  23873. data.v1 = this.v1.toArray();
  23874. data.v2 = this.v2.toArray();
  23875. return data;
  23876. };
  23877. LineCurve3.prototype.fromJSON = function ( json ) {
  23878. Curve.prototype.fromJSON.call( this, json );
  23879. this.v1.fromArray( json.v1 );
  23880. this.v2.fromArray( json.v2 );
  23881. return this;
  23882. };
  23883. function QuadraticBezierCurve( v0, v1, v2 ) {
  23884. Curve.call( this );
  23885. this.type = 'QuadraticBezierCurve';
  23886. this.v0 = v0 || new Vector2();
  23887. this.v1 = v1 || new Vector2();
  23888. this.v2 = v2 || new Vector2();
  23889. }
  23890. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  23891. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  23892. QuadraticBezierCurve.prototype.isQuadraticBezierCurve = true;
  23893. QuadraticBezierCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23894. var point = optionalTarget || new Vector2();
  23895. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23896. point.set(
  23897. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23898. QuadraticBezier( t, v0.y, v1.y, v2.y )
  23899. );
  23900. return point;
  23901. };
  23902. QuadraticBezierCurve.prototype.copy = function ( source ) {
  23903. Curve.prototype.copy.call( this, source );
  23904. this.v0.copy( source.v0 );
  23905. this.v1.copy( source.v1 );
  23906. this.v2.copy( source.v2 );
  23907. return this;
  23908. };
  23909. QuadraticBezierCurve.prototype.toJSON = function () {
  23910. var data = Curve.prototype.toJSON.call( this );
  23911. data.v0 = this.v0.toArray();
  23912. data.v1 = this.v1.toArray();
  23913. data.v2 = this.v2.toArray();
  23914. return data;
  23915. };
  23916. QuadraticBezierCurve.prototype.fromJSON = function ( json ) {
  23917. Curve.prototype.fromJSON.call( this, json );
  23918. this.v0.fromArray( json.v0 );
  23919. this.v1.fromArray( json.v1 );
  23920. this.v2.fromArray( json.v2 );
  23921. return this;
  23922. };
  23923. function QuadraticBezierCurve3( v0, v1, v2 ) {
  23924. Curve.call( this );
  23925. this.type = 'QuadraticBezierCurve3';
  23926. this.v0 = v0 || new Vector3();
  23927. this.v1 = v1 || new Vector3();
  23928. this.v2 = v2 || new Vector3();
  23929. }
  23930. QuadraticBezierCurve3.prototype = Object.create( Curve.prototype );
  23931. QuadraticBezierCurve3.prototype.constructor = QuadraticBezierCurve3;
  23932. QuadraticBezierCurve3.prototype.isQuadraticBezierCurve3 = true;
  23933. QuadraticBezierCurve3.prototype.getPoint = function ( t, optionalTarget ) {
  23934. var point = optionalTarget || new Vector3();
  23935. var v0 = this.v0, v1 = this.v1, v2 = this.v2;
  23936. point.set(
  23937. QuadraticBezier( t, v0.x, v1.x, v2.x ),
  23938. QuadraticBezier( t, v0.y, v1.y, v2.y ),
  23939. QuadraticBezier( t, v0.z, v1.z, v2.z )
  23940. );
  23941. return point;
  23942. };
  23943. QuadraticBezierCurve3.prototype.copy = function ( source ) {
  23944. Curve.prototype.copy.call( this, source );
  23945. this.v0.copy( source.v0 );
  23946. this.v1.copy( source.v1 );
  23947. this.v2.copy( source.v2 );
  23948. return this;
  23949. };
  23950. QuadraticBezierCurve3.prototype.toJSON = function () {
  23951. var data = Curve.prototype.toJSON.call( this );
  23952. data.v0 = this.v0.toArray();
  23953. data.v1 = this.v1.toArray();
  23954. data.v2 = this.v2.toArray();
  23955. return data;
  23956. };
  23957. QuadraticBezierCurve3.prototype.fromJSON = function ( json ) {
  23958. Curve.prototype.fromJSON.call( this, json );
  23959. this.v0.fromArray( json.v0 );
  23960. this.v1.fromArray( json.v1 );
  23961. this.v2.fromArray( json.v2 );
  23962. return this;
  23963. };
  23964. function SplineCurve( points /* array of Vector2 */ ) {
  23965. Curve.call( this );
  23966. this.type = 'SplineCurve';
  23967. this.points = points || [];
  23968. }
  23969. SplineCurve.prototype = Object.create( Curve.prototype );
  23970. SplineCurve.prototype.constructor = SplineCurve;
  23971. SplineCurve.prototype.isSplineCurve = true;
  23972. SplineCurve.prototype.getPoint = function ( t, optionalTarget ) {
  23973. var point = optionalTarget || new Vector2();
  23974. var points = this.points;
  23975. var p = ( points.length - 1 ) * t;
  23976. var intPoint = Math.floor( p );
  23977. var weight = p - intPoint;
  23978. var p0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  23979. var p1 = points[ intPoint ];
  23980. var p2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  23981. var p3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  23982. point.set(
  23983. CatmullRom( weight, p0.x, p1.x, p2.x, p3.x ),
  23984. CatmullRom( weight, p0.y, p1.y, p2.y, p3.y )
  23985. );
  23986. return point;
  23987. };
  23988. SplineCurve.prototype.copy = function ( source ) {
  23989. Curve.prototype.copy.call( this, source );
  23990. this.points = [];
  23991. for ( var i = 0, l = source.points.length; i < l; i ++ ) {
  23992. var point = source.points[ i ];
  23993. this.points.push( point.clone() );
  23994. }
  23995. return this;
  23996. };
  23997. SplineCurve.prototype.toJSON = function () {
  23998. var data = Curve.prototype.toJSON.call( this );
  23999. data.points = [];
  24000. for ( var i = 0, l = this.points.length; i < l; i ++ ) {
  24001. var point = this.points[ i ];
  24002. data.points.push( point.toArray() );
  24003. }
  24004. return data;
  24005. };
  24006. SplineCurve.prototype.fromJSON = function ( json ) {
  24007. Curve.prototype.fromJSON.call( this, json );
  24008. this.points = [];
  24009. for ( var i = 0, l = json.points.length; i < l; i ++ ) {
  24010. var point = json.points[ i ];
  24011. this.points.push( new Vector2().fromArray( point ) );
  24012. }
  24013. return this;
  24014. };
  24015. var Curves = Object.freeze({
  24016. ArcCurve: ArcCurve,
  24017. CatmullRomCurve3: CatmullRomCurve3,
  24018. CubicBezierCurve: CubicBezierCurve,
  24019. CubicBezierCurve3: CubicBezierCurve3,
  24020. EllipseCurve: EllipseCurve,
  24021. LineCurve: LineCurve,
  24022. LineCurve3: LineCurve3,
  24023. QuadraticBezierCurve: QuadraticBezierCurve,
  24024. QuadraticBezierCurve3: QuadraticBezierCurve3,
  24025. SplineCurve: SplineCurve
  24026. });
  24027. /**
  24028. * @author zz85 / http://www.lab4games.net/zz85/blog
  24029. *
  24030. **/
  24031. /**************************************************************
  24032. * Curved Path - a curve path is simply a array of connected
  24033. * curves, but retains the api of a curve
  24034. **************************************************************/
  24035. function CurvePath() {
  24036. Curve.call( this );
  24037. this.type = 'CurvePath';
  24038. this.curves = [];
  24039. this.autoClose = false; // Automatically closes the path
  24040. }
  24041. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  24042. constructor: CurvePath,
  24043. add: function ( curve ) {
  24044. this.curves.push( curve );
  24045. },
  24046. closePath: function () {
  24047. // Add a line curve if start and end of lines are not connected
  24048. var startPoint = this.curves[ 0 ].getPoint( 0 );
  24049. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24050. if ( ! startPoint.equals( endPoint ) ) {
  24051. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24052. }
  24053. },
  24054. // To get accurate point with reference to
  24055. // entire path distance at time t,
  24056. // following has to be done:
  24057. // 1. Length of each sub path have to be known
  24058. // 2. Locate and identify type of curve
  24059. // 3. Get t for the curve
  24060. // 4. Return curve.getPointAt(t')
  24061. getPoint: function ( t ) {
  24062. var d = t * this.getLength();
  24063. var curveLengths = this.getCurveLengths();
  24064. var i = 0;
  24065. // To think about boundaries points.
  24066. while ( i < curveLengths.length ) {
  24067. if ( curveLengths[ i ] >= d ) {
  24068. var diff = curveLengths[ i ] - d;
  24069. var curve = this.curves[ i ];
  24070. var segmentLength = curve.getLength();
  24071. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24072. return curve.getPointAt( u );
  24073. }
  24074. i ++;
  24075. }
  24076. return null;
  24077. // loop where sum != 0, sum > d , sum+1 <d
  24078. },
  24079. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24080. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24081. // getPoint() depends on getLength
  24082. getLength: function () {
  24083. var lens = this.getCurveLengths();
  24084. return lens[ lens.length - 1 ];
  24085. },
  24086. // cacheLengths must be recalculated.
  24087. updateArcLengths: function () {
  24088. this.needsUpdate = true;
  24089. this.cacheLengths = null;
  24090. this.getCurveLengths();
  24091. },
  24092. // Compute lengths and cache them
  24093. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24094. getCurveLengths: function () {
  24095. // We use cache values if curves and cache array are same length
  24096. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24097. return this.cacheLengths;
  24098. }
  24099. // Get length of sub-curve
  24100. // Push sums into cached array
  24101. var lengths = [], sums = 0;
  24102. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24103. sums += this.curves[ i ].getLength();
  24104. lengths.push( sums );
  24105. }
  24106. this.cacheLengths = lengths;
  24107. return lengths;
  24108. },
  24109. getSpacedPoints: function ( divisions ) {
  24110. if ( divisions === undefined ) divisions = 40;
  24111. var points = [];
  24112. for ( var i = 0; i <= divisions; i ++ ) {
  24113. points.push( this.getPoint( i / divisions ) );
  24114. }
  24115. if ( this.autoClose ) {
  24116. points.push( points[ 0 ] );
  24117. }
  24118. return points;
  24119. },
  24120. getPoints: function ( divisions ) {
  24121. divisions = divisions || 12;
  24122. var points = [], last;
  24123. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24124. var curve = curves[ i ];
  24125. var resolution = ( curve && curve.isEllipseCurve ) ? divisions * 2
  24126. : ( curve && curve.isLineCurve ) ? 1
  24127. : ( curve && curve.isSplineCurve ) ? divisions * curve.points.length
  24128. : divisions;
  24129. var pts = curve.getPoints( resolution );
  24130. for ( var j = 0; j < pts.length; j ++ ) {
  24131. var point = pts[ j ];
  24132. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24133. points.push( point );
  24134. last = point;
  24135. }
  24136. }
  24137. if ( this.autoClose && points.length > 1 && ! points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24138. points.push( points[ 0 ] );
  24139. }
  24140. return points;
  24141. },
  24142. copy: function ( source ) {
  24143. Curve.prototype.copy.call( this, source );
  24144. this.curves = [];
  24145. for ( var i = 0, l = source.curves.length; i < l; i ++ ) {
  24146. var curve = source.curves[ i ];
  24147. this.curves.push( curve.clone() );
  24148. }
  24149. this.autoClose = source.autoClose;
  24150. return this;
  24151. },
  24152. toJSON: function () {
  24153. var data = Curve.prototype.toJSON.call( this );
  24154. data.autoClose = this.autoClose;
  24155. data.curves = [];
  24156. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24157. var curve = this.curves[ i ];
  24158. data.curves.push( curve.toJSON() );
  24159. }
  24160. return data;
  24161. },
  24162. fromJSON: function ( json ) {
  24163. Curve.prototype.fromJSON.call( this, json );
  24164. this.autoClose = json.autoClose;
  24165. this.curves = [];
  24166. for ( var i = 0, l = json.curves.length; i < l; i ++ ) {
  24167. var curve = json.curves[ i ];
  24168. this.curves.push( new Curves[ curve.type ]().fromJSON( curve ) );
  24169. }
  24170. return this;
  24171. }
  24172. } );
  24173. /**
  24174. * @author zz85 / http://www.lab4games.net/zz85/blog
  24175. * Creates free form 2d path using series of points, lines or curves.
  24176. **/
  24177. function Path( points ) {
  24178. CurvePath.call( this );
  24179. this.type = 'Path';
  24180. this.currentPoint = new Vector2();
  24181. if ( points ) {
  24182. this.setFromPoints( points );
  24183. }
  24184. }
  24185. Path.prototype = Object.assign( Object.create( CurvePath.prototype ), {
  24186. constructor: Path,
  24187. setFromPoints: function ( points ) {
  24188. this.moveTo( points[ 0 ].x, points[ 0 ].y );
  24189. for ( var i = 1, l = points.length; i < l; i ++ ) {
  24190. this.lineTo( points[ i ].x, points[ i ].y );
  24191. }
  24192. },
  24193. moveTo: function ( x, y ) {
  24194. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  24195. },
  24196. lineTo: function ( x, y ) {
  24197. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  24198. this.curves.push( curve );
  24199. this.currentPoint.set( x, y );
  24200. },
  24201. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  24202. var curve = new QuadraticBezierCurve(
  24203. this.currentPoint.clone(),
  24204. new Vector2( aCPx, aCPy ),
  24205. new Vector2( aX, aY )
  24206. );
  24207. this.curves.push( curve );
  24208. this.currentPoint.set( aX, aY );
  24209. },
  24210. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  24211. var curve = new CubicBezierCurve(
  24212. this.currentPoint.clone(),
  24213. new Vector2( aCP1x, aCP1y ),
  24214. new Vector2( aCP2x, aCP2y ),
  24215. new Vector2( aX, aY )
  24216. );
  24217. this.curves.push( curve );
  24218. this.currentPoint.set( aX, aY );
  24219. },
  24220. splineThru: function ( pts /*Array of Vector*/ ) {
  24221. var npts = [ this.currentPoint.clone() ].concat( pts );
  24222. var curve = new SplineCurve( npts );
  24223. this.curves.push( curve );
  24224. this.currentPoint.copy( pts[ pts.length - 1 ] );
  24225. },
  24226. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24227. var x0 = this.currentPoint.x;
  24228. var y0 = this.currentPoint.y;
  24229. this.absarc( aX + x0, aY + y0, aRadius,
  24230. aStartAngle, aEndAngle, aClockwise );
  24231. },
  24232. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  24233. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  24234. },
  24235. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24236. var x0 = this.currentPoint.x;
  24237. var y0 = this.currentPoint.y;
  24238. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24239. },
  24240. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24241. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  24242. if ( this.curves.length > 0 ) {
  24243. // if a previous curve is present, attempt to join
  24244. var firstPoint = curve.getPoint( 0 );
  24245. if ( ! firstPoint.equals( this.currentPoint ) ) {
  24246. this.lineTo( firstPoint.x, firstPoint.y );
  24247. }
  24248. }
  24249. this.curves.push( curve );
  24250. var lastPoint = curve.getPoint( 1 );
  24251. this.currentPoint.copy( lastPoint );
  24252. },
  24253. copy: function ( source ) {
  24254. CurvePath.prototype.copy.call( this, source );
  24255. this.currentPoint.copy( source.currentPoint );
  24256. return this;
  24257. },
  24258. toJSON: function () {
  24259. var data = CurvePath.prototype.toJSON.call( this );
  24260. data.currentPoint = this.currentPoint.toArray();
  24261. return data;
  24262. },
  24263. fromJSON: function ( json ) {
  24264. CurvePath.prototype.fromJSON.call( this, json );
  24265. this.currentPoint.fromArray( json.currentPoint );
  24266. return this;
  24267. }
  24268. } );
  24269. /**
  24270. * @author zz85 / http://www.lab4games.net/zz85/blog
  24271. * Defines a 2d shape plane using paths.
  24272. **/
  24273. // STEP 1 Create a path.
  24274. // STEP 2 Turn path into shape.
  24275. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  24276. // STEP 3a - Extract points from each shape, turn to vertices
  24277. // STEP 3b - Triangulate each shape, add faces.
  24278. function Shape( points ) {
  24279. Path.call( this, points );
  24280. this.uuid = _Math.generateUUID();
  24281. this.type = 'Shape';
  24282. this.holes = [];
  24283. }
  24284. Shape.prototype = Object.assign( Object.create( Path.prototype ), {
  24285. constructor: Shape,
  24286. getPointsHoles: function ( divisions ) {
  24287. var holesPts = [];
  24288. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24289. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  24290. }
  24291. return holesPts;
  24292. },
  24293. // get points of shape and holes (keypoints based on segments parameter)
  24294. extractPoints: function ( divisions ) {
  24295. return {
  24296. shape: this.getPoints( divisions ),
  24297. holes: this.getPointsHoles( divisions )
  24298. };
  24299. },
  24300. copy: function ( source ) {
  24301. Path.prototype.copy.call( this, source );
  24302. this.holes = [];
  24303. for ( var i = 0, l = source.holes.length; i < l; i ++ ) {
  24304. var hole = source.holes[ i ];
  24305. this.holes.push( hole.clone() );
  24306. }
  24307. return this;
  24308. },
  24309. toJSON: function () {
  24310. var data = Path.prototype.toJSON.call( this );
  24311. data.uuid = this.uuid;
  24312. data.holes = [];
  24313. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  24314. var hole = this.holes[ i ];
  24315. data.holes.push( hole.toJSON() );
  24316. }
  24317. return data;
  24318. },
  24319. fromJSON: function ( json ) {
  24320. Path.prototype.fromJSON.call( this, json );
  24321. this.uuid = json.uuid;
  24322. this.holes = [];
  24323. for ( var i = 0, l = json.holes.length; i < l; i ++ ) {
  24324. var hole = json.holes[ i ];
  24325. this.holes.push( new Path().fromJSON( hole ) );
  24326. }
  24327. return this;
  24328. }
  24329. } );
  24330. /**
  24331. * @author mrdoob / http://mrdoob.com/
  24332. * @author alteredq / http://alteredqualia.com/
  24333. */
  24334. function Light( color, intensity ) {
  24335. Object3D.call( this );
  24336. this.type = 'Light';
  24337. this.color = new Color( color );
  24338. this.intensity = intensity !== undefined ? intensity : 1;
  24339. this.receiveShadow = undefined;
  24340. }
  24341. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  24342. constructor: Light,
  24343. isLight: true,
  24344. copy: function ( source ) {
  24345. Object3D.prototype.copy.call( this, source );
  24346. this.color.copy( source.color );
  24347. this.intensity = source.intensity;
  24348. return this;
  24349. },
  24350. toJSON: function ( meta ) {
  24351. var data = Object3D.prototype.toJSON.call( this, meta );
  24352. data.object.color = this.color.getHex();
  24353. data.object.intensity = this.intensity;
  24354. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  24355. if ( this.distance !== undefined ) data.object.distance = this.distance;
  24356. if ( this.angle !== undefined ) data.object.angle = this.angle;
  24357. if ( this.decay !== undefined ) data.object.decay = this.decay;
  24358. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  24359. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  24360. return data;
  24361. }
  24362. } );
  24363. /**
  24364. * @author alteredq / http://alteredqualia.com/
  24365. */
  24366. function HemisphereLight( skyColor, groundColor, intensity ) {
  24367. Light.call( this, skyColor, intensity );
  24368. this.type = 'HemisphereLight';
  24369. this.castShadow = undefined;
  24370. this.position.copy( Object3D.DefaultUp );
  24371. this.updateMatrix();
  24372. this.groundColor = new Color( groundColor );
  24373. }
  24374. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24375. constructor: HemisphereLight,
  24376. isHemisphereLight: true,
  24377. copy: function ( source ) {
  24378. Light.prototype.copy.call( this, source );
  24379. this.groundColor.copy( source.groundColor );
  24380. return this;
  24381. }
  24382. } );
  24383. /**
  24384. * @author mrdoob / http://mrdoob.com/
  24385. */
  24386. function LightShadow( camera ) {
  24387. this.camera = camera;
  24388. this.bias = 0;
  24389. this.radius = 1;
  24390. this.mapSize = new Vector2( 512, 512 );
  24391. this.map = null;
  24392. this.matrix = new Matrix4();
  24393. }
  24394. Object.assign( LightShadow.prototype, {
  24395. copy: function ( source ) {
  24396. this.camera = source.camera.clone();
  24397. this.bias = source.bias;
  24398. this.radius = source.radius;
  24399. this.mapSize.copy( source.mapSize );
  24400. return this;
  24401. },
  24402. clone: function () {
  24403. return new this.constructor().copy( this );
  24404. },
  24405. toJSON: function () {
  24406. var object = {};
  24407. if ( this.bias !== 0 ) object.bias = this.bias;
  24408. if ( this.radius !== 1 ) object.radius = this.radius;
  24409. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  24410. object.camera = this.camera.toJSON( false ).object;
  24411. delete object.camera.matrix;
  24412. return object;
  24413. }
  24414. } );
  24415. /**
  24416. * @author mrdoob / http://mrdoob.com/
  24417. */
  24418. function SpotLightShadow() {
  24419. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  24420. }
  24421. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24422. constructor: SpotLightShadow,
  24423. isSpotLightShadow: true,
  24424. update: function ( light ) {
  24425. var camera = this.camera;
  24426. var fov = _Math.RAD2DEG * 2 * light.angle;
  24427. var aspect = this.mapSize.width / this.mapSize.height;
  24428. var far = light.distance || camera.far;
  24429. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  24430. camera.fov = fov;
  24431. camera.aspect = aspect;
  24432. camera.far = far;
  24433. camera.updateProjectionMatrix();
  24434. }
  24435. }
  24436. } );
  24437. /**
  24438. * @author alteredq / http://alteredqualia.com/
  24439. */
  24440. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  24441. Light.call( this, color, intensity );
  24442. this.type = 'SpotLight';
  24443. this.position.copy( Object3D.DefaultUp );
  24444. this.updateMatrix();
  24445. this.target = new Object3D();
  24446. Object.defineProperty( this, 'power', {
  24447. get: function () {
  24448. // intensity = power per solid angle.
  24449. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  24450. return this.intensity * Math.PI;
  24451. },
  24452. set: function ( power ) {
  24453. // intensity = power per solid angle.
  24454. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  24455. this.intensity = power / Math.PI;
  24456. }
  24457. } );
  24458. this.distance = ( distance !== undefined ) ? distance : 0;
  24459. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  24460. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  24461. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24462. this.shadow = new SpotLightShadow();
  24463. }
  24464. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24465. constructor: SpotLight,
  24466. isSpotLight: true,
  24467. copy: function ( source ) {
  24468. Light.prototype.copy.call( this, source );
  24469. this.distance = source.distance;
  24470. this.angle = source.angle;
  24471. this.penumbra = source.penumbra;
  24472. this.decay = source.decay;
  24473. this.target = source.target.clone();
  24474. this.shadow = source.shadow.clone();
  24475. return this;
  24476. }
  24477. } );
  24478. /**
  24479. * @author mrdoob / http://mrdoob.com/
  24480. */
  24481. function PointLight( color, intensity, distance, decay ) {
  24482. Light.call( this, color, intensity );
  24483. this.type = 'PointLight';
  24484. Object.defineProperty( this, 'power', {
  24485. get: function () {
  24486. // intensity = power per solid angle.
  24487. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  24488. return this.intensity * 4 * Math.PI;
  24489. },
  24490. set: function ( power ) {
  24491. // intensity = power per solid angle.
  24492. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  24493. this.intensity = power / ( 4 * Math.PI );
  24494. }
  24495. } );
  24496. this.distance = ( distance !== undefined ) ? distance : 0;
  24497. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  24498. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  24499. }
  24500. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24501. constructor: PointLight,
  24502. isPointLight: true,
  24503. copy: function ( source ) {
  24504. Light.prototype.copy.call( this, source );
  24505. this.distance = source.distance;
  24506. this.decay = source.decay;
  24507. this.shadow = source.shadow.clone();
  24508. return this;
  24509. }
  24510. } );
  24511. /**
  24512. * @author mrdoob / http://mrdoob.com/
  24513. */
  24514. function DirectionalLightShadow( ) {
  24515. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  24516. }
  24517. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  24518. constructor: DirectionalLightShadow
  24519. } );
  24520. /**
  24521. * @author mrdoob / http://mrdoob.com/
  24522. * @author alteredq / http://alteredqualia.com/
  24523. */
  24524. function DirectionalLight( color, intensity ) {
  24525. Light.call( this, color, intensity );
  24526. this.type = 'DirectionalLight';
  24527. this.position.copy( Object3D.DefaultUp );
  24528. this.updateMatrix();
  24529. this.target = new Object3D();
  24530. this.shadow = new DirectionalLightShadow();
  24531. }
  24532. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24533. constructor: DirectionalLight,
  24534. isDirectionalLight: true,
  24535. copy: function ( source ) {
  24536. Light.prototype.copy.call( this, source );
  24537. this.target = source.target.clone();
  24538. this.shadow = source.shadow.clone();
  24539. return this;
  24540. }
  24541. } );
  24542. /**
  24543. * @author mrdoob / http://mrdoob.com/
  24544. */
  24545. function AmbientLight( color, intensity ) {
  24546. Light.call( this, color, intensity );
  24547. this.type = 'AmbientLight';
  24548. this.castShadow = undefined;
  24549. }
  24550. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24551. constructor: AmbientLight,
  24552. isAmbientLight: true
  24553. } );
  24554. /**
  24555. * @author abelnation / http://github.com/abelnation
  24556. */
  24557. function RectAreaLight( color, intensity, width, height ) {
  24558. Light.call( this, color, intensity );
  24559. this.type = 'RectAreaLight';
  24560. this.position.set( 0, 1, 0 );
  24561. this.updateMatrix();
  24562. this.width = ( width !== undefined ) ? width : 10;
  24563. this.height = ( height !== undefined ) ? height : 10;
  24564. // TODO (abelnation): distance/decay
  24565. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  24566. // TODO (abelnation): shadows
  24567. }
  24568. // TODO (abelnation): RectAreaLight update when light shape is changed
  24569. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  24570. constructor: RectAreaLight,
  24571. isRectAreaLight: true,
  24572. copy: function ( source ) {
  24573. Light.prototype.copy.call( this, source );
  24574. this.width = source.width;
  24575. this.height = source.height;
  24576. return this;
  24577. },
  24578. toJSON: function ( meta ) {
  24579. var data = Light.prototype.toJSON.call( this, meta );
  24580. data.object.width = this.width;
  24581. data.object.height = this.height;
  24582. return data;
  24583. }
  24584. } );
  24585. /**
  24586. *
  24587. * A Track that interpolates Strings
  24588. *
  24589. *
  24590. * @author Ben Houston / http://clara.io/
  24591. * @author David Sarno / http://lighthaus.us/
  24592. * @author tschw
  24593. */
  24594. function StringKeyframeTrack( name, times, values, interpolation ) {
  24595. KeyframeTrack.call( this, name, times, values, interpolation );
  24596. }
  24597. StringKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24598. constructor: StringKeyframeTrack,
  24599. ValueTypeName: 'string',
  24600. ValueBufferType: Array,
  24601. DefaultInterpolation: InterpolateDiscrete,
  24602. InterpolantFactoryMethodLinear: undefined,
  24603. InterpolantFactoryMethodSmooth: undefined
  24604. } );
  24605. /**
  24606. *
  24607. * A Track of Boolean keyframe values.
  24608. *
  24609. *
  24610. * @author Ben Houston / http://clara.io/
  24611. * @author David Sarno / http://lighthaus.us/
  24612. * @author tschw
  24613. */
  24614. function BooleanKeyframeTrack( name, times, values ) {
  24615. KeyframeTrack.call( this, name, times, values );
  24616. }
  24617. BooleanKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24618. constructor: BooleanKeyframeTrack,
  24619. ValueTypeName: 'bool',
  24620. ValueBufferType: Array,
  24621. DefaultInterpolation: InterpolateDiscrete,
  24622. InterpolantFactoryMethodLinear: undefined,
  24623. InterpolantFactoryMethodSmooth: undefined
  24624. // Note: Actually this track could have a optimized / compressed
  24625. // representation of a single value and a custom interpolant that
  24626. // computes "firstValue ^ isOdd( index )".
  24627. } );
  24628. /**
  24629. * Abstract base class of interpolants over parametric samples.
  24630. *
  24631. * The parameter domain is one dimensional, typically the time or a path
  24632. * along a curve defined by the data.
  24633. *
  24634. * The sample values can have any dimensionality and derived classes may
  24635. * apply special interpretations to the data.
  24636. *
  24637. * This class provides the interval seek in a Template Method, deferring
  24638. * the actual interpolation to derived classes.
  24639. *
  24640. * Time complexity is O(1) for linear access crossing at most two points
  24641. * and O(log N) for random access, where N is the number of positions.
  24642. *
  24643. * References:
  24644. *
  24645. * http://www.oodesign.com/template-method-pattern.html
  24646. *
  24647. * @author tschw
  24648. */
  24649. function Interpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24650. this.parameterPositions = parameterPositions;
  24651. this._cachedIndex = 0;
  24652. this.resultBuffer = resultBuffer !== undefined ?
  24653. resultBuffer : new sampleValues.constructor( sampleSize );
  24654. this.sampleValues = sampleValues;
  24655. this.valueSize = sampleSize;
  24656. }
  24657. Object.assign( Interpolant.prototype, {
  24658. evaluate: function ( t ) {
  24659. var pp = this.parameterPositions,
  24660. i1 = this._cachedIndex,
  24661. t1 = pp[ i1 ],
  24662. t0 = pp[ i1 - 1 ];
  24663. validate_interval: {
  24664. seek: {
  24665. var right;
  24666. linear_scan: {
  24667. //- See http://jsperf.com/comparison-to-undefined/3
  24668. //- slower code:
  24669. //-
  24670. //- if ( t >= t1 || t1 === undefined ) {
  24671. forward_scan: if ( ! ( t < t1 ) ) {
  24672. for ( var giveUpAt = i1 + 2; ; ) {
  24673. if ( t1 === undefined ) {
  24674. if ( t < t0 ) break forward_scan;
  24675. // after end
  24676. i1 = pp.length;
  24677. this._cachedIndex = i1;
  24678. return this.afterEnd_( i1 - 1, t, t0 );
  24679. }
  24680. if ( i1 === giveUpAt ) break; // this loop
  24681. t0 = t1;
  24682. t1 = pp[ ++ i1 ];
  24683. if ( t < t1 ) {
  24684. // we have arrived at the sought interval
  24685. break seek;
  24686. }
  24687. }
  24688. // prepare binary search on the right side of the index
  24689. right = pp.length;
  24690. break linear_scan;
  24691. }
  24692. //- slower code:
  24693. //- if ( t < t0 || t0 === undefined ) {
  24694. if ( ! ( t >= t0 ) ) {
  24695. // looping?
  24696. var t1global = pp[ 1 ];
  24697. if ( t < t1global ) {
  24698. i1 = 2; // + 1, using the scan for the details
  24699. t0 = t1global;
  24700. }
  24701. // linear reverse scan
  24702. for ( var giveUpAt = i1 - 2; ; ) {
  24703. if ( t0 === undefined ) {
  24704. // before start
  24705. this._cachedIndex = 0;
  24706. return this.beforeStart_( 0, t, t1 );
  24707. }
  24708. if ( i1 === giveUpAt ) break; // this loop
  24709. t1 = t0;
  24710. t0 = pp[ -- i1 - 1 ];
  24711. if ( t >= t0 ) {
  24712. // we have arrived at the sought interval
  24713. break seek;
  24714. }
  24715. }
  24716. // prepare binary search on the left side of the index
  24717. right = i1;
  24718. i1 = 0;
  24719. break linear_scan;
  24720. }
  24721. // the interval is valid
  24722. break validate_interval;
  24723. } // linear scan
  24724. // binary search
  24725. while ( i1 < right ) {
  24726. var mid = ( i1 + right ) >>> 1;
  24727. if ( t < pp[ mid ] ) {
  24728. right = mid;
  24729. } else {
  24730. i1 = mid + 1;
  24731. }
  24732. }
  24733. t1 = pp[ i1 ];
  24734. t0 = pp[ i1 - 1 ];
  24735. // check boundary cases, again
  24736. if ( t0 === undefined ) {
  24737. this._cachedIndex = 0;
  24738. return this.beforeStart_( 0, t, t1 );
  24739. }
  24740. if ( t1 === undefined ) {
  24741. i1 = pp.length;
  24742. this._cachedIndex = i1;
  24743. return this.afterEnd_( i1 - 1, t0, t );
  24744. }
  24745. } // seek
  24746. this._cachedIndex = i1;
  24747. this.intervalChanged_( i1, t0, t1 );
  24748. } // validate_interval
  24749. return this.interpolate_( i1, t0, t, t1 );
  24750. },
  24751. settings: null, // optional, subclass-specific settings structure
  24752. // Note: The indirection allows central control of many interpolants.
  24753. // --- Protected interface
  24754. DefaultSettings_: {},
  24755. getSettings_: function () {
  24756. return this.settings || this.DefaultSettings_;
  24757. },
  24758. copySampleValue_: function ( index ) {
  24759. // copies a sample value to the result buffer
  24760. var result = this.resultBuffer,
  24761. values = this.sampleValues,
  24762. stride = this.valueSize,
  24763. offset = index * stride;
  24764. for ( var i = 0; i !== stride; ++ i ) {
  24765. result[ i ] = values[ offset + i ];
  24766. }
  24767. return result;
  24768. },
  24769. // Template methods for derived classes:
  24770. interpolate_: function ( /* i1, t0, t, t1 */ ) {
  24771. throw new Error( 'call to abstract method' );
  24772. // implementations shall return this.resultBuffer
  24773. },
  24774. intervalChanged_: function ( /* i1, t0, t1 */ ) {
  24775. // empty
  24776. }
  24777. } );
  24778. //!\ DECLARE ALIAS AFTER assign prototype !
  24779. Object.assign( Interpolant.prototype, {
  24780. //( 0, t, t0 ), returns this.resultBuffer
  24781. beforeStart_: Interpolant.prototype.copySampleValue_,
  24782. //( N-1, tN-1, t ), returns this.resultBuffer
  24783. afterEnd_: Interpolant.prototype.copySampleValue_,
  24784. } );
  24785. /**
  24786. * Spherical linear unit quaternion interpolant.
  24787. *
  24788. * @author tschw
  24789. */
  24790. function QuaternionLinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24791. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24792. }
  24793. QuaternionLinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24794. constructor: QuaternionLinearInterpolant,
  24795. interpolate_: function ( i1, t0, t, t1 ) {
  24796. var result = this.resultBuffer,
  24797. values = this.sampleValues,
  24798. stride = this.valueSize,
  24799. offset = i1 * stride,
  24800. alpha = ( t - t0 ) / ( t1 - t0 );
  24801. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  24802. Quaternion.slerpFlat( result, 0, values, offset - stride, values, offset, alpha );
  24803. }
  24804. return result;
  24805. }
  24806. } );
  24807. /**
  24808. *
  24809. * A Track of quaternion keyframe values.
  24810. *
  24811. * @author Ben Houston / http://clara.io/
  24812. * @author David Sarno / http://lighthaus.us/
  24813. * @author tschw
  24814. */
  24815. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  24816. KeyframeTrack.call( this, name, times, values, interpolation );
  24817. }
  24818. QuaternionKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24819. constructor: QuaternionKeyframeTrack,
  24820. ValueTypeName: 'quaternion',
  24821. // ValueBufferType is inherited
  24822. DefaultInterpolation: InterpolateLinear,
  24823. InterpolantFactoryMethodLinear: function ( result ) {
  24824. return new QuaternionLinearInterpolant( this.times, this.values, this.getValueSize(), result );
  24825. },
  24826. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  24827. } );
  24828. /**
  24829. *
  24830. * A Track of keyframe values that represent color.
  24831. *
  24832. *
  24833. * @author Ben Houston / http://clara.io/
  24834. * @author David Sarno / http://lighthaus.us/
  24835. * @author tschw
  24836. */
  24837. function ColorKeyframeTrack( name, times, values, interpolation ) {
  24838. KeyframeTrack.call( this, name, times, values, interpolation );
  24839. }
  24840. ColorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24841. constructor: ColorKeyframeTrack,
  24842. ValueTypeName: 'color'
  24843. // ValueBufferType is inherited
  24844. // DefaultInterpolation is inherited
  24845. // Note: Very basic implementation and nothing special yet.
  24846. // However, this is the place for color space parameterization.
  24847. } );
  24848. /**
  24849. *
  24850. * A Track of numeric keyframe values.
  24851. *
  24852. * @author Ben Houston / http://clara.io/
  24853. * @author David Sarno / http://lighthaus.us/
  24854. * @author tschw
  24855. */
  24856. function NumberKeyframeTrack( name, times, values, interpolation ) {
  24857. KeyframeTrack.call( this, name, times, values, interpolation );
  24858. }
  24859. NumberKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  24860. constructor: NumberKeyframeTrack,
  24861. ValueTypeName: 'number'
  24862. // ValueBufferType is inherited
  24863. // DefaultInterpolation is inherited
  24864. } );
  24865. /**
  24866. * Fast and simple cubic spline interpolant.
  24867. *
  24868. * It was derived from a Hermitian construction setting the first derivative
  24869. * at each sample position to the linear slope between neighboring positions
  24870. * over their parameter interval.
  24871. *
  24872. * @author tschw
  24873. */
  24874. function CubicInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24875. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24876. this._weightPrev = - 0;
  24877. this._offsetPrev = - 0;
  24878. this._weightNext = - 0;
  24879. this._offsetNext = - 0;
  24880. }
  24881. CubicInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24882. constructor: CubicInterpolant,
  24883. DefaultSettings_: {
  24884. endingStart: ZeroCurvatureEnding,
  24885. endingEnd: ZeroCurvatureEnding
  24886. },
  24887. intervalChanged_: function ( i1, t0, t1 ) {
  24888. var pp = this.parameterPositions,
  24889. iPrev = i1 - 2,
  24890. iNext = i1 + 1,
  24891. tPrev = pp[ iPrev ],
  24892. tNext = pp[ iNext ];
  24893. if ( tPrev === undefined ) {
  24894. switch ( this.getSettings_().endingStart ) {
  24895. case ZeroSlopeEnding:
  24896. // f'(t0) = 0
  24897. iPrev = i1;
  24898. tPrev = 2 * t0 - t1;
  24899. break;
  24900. case WrapAroundEnding:
  24901. // use the other end of the curve
  24902. iPrev = pp.length - 2;
  24903. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  24904. break;
  24905. default: // ZeroCurvatureEnding
  24906. // f''(t0) = 0 a.k.a. Natural Spline
  24907. iPrev = i1;
  24908. tPrev = t1;
  24909. }
  24910. }
  24911. if ( tNext === undefined ) {
  24912. switch ( this.getSettings_().endingEnd ) {
  24913. case ZeroSlopeEnding:
  24914. // f'(tN) = 0
  24915. iNext = i1;
  24916. tNext = 2 * t1 - t0;
  24917. break;
  24918. case WrapAroundEnding:
  24919. // use the other end of the curve
  24920. iNext = 1;
  24921. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  24922. break;
  24923. default: // ZeroCurvatureEnding
  24924. // f''(tN) = 0, a.k.a. Natural Spline
  24925. iNext = i1 - 1;
  24926. tNext = t0;
  24927. }
  24928. }
  24929. var halfDt = ( t1 - t0 ) * 0.5,
  24930. stride = this.valueSize;
  24931. this._weightPrev = halfDt / ( t0 - tPrev );
  24932. this._weightNext = halfDt / ( tNext - t1 );
  24933. this._offsetPrev = iPrev * stride;
  24934. this._offsetNext = iNext * stride;
  24935. },
  24936. interpolate_: function ( i1, t0, t, t1 ) {
  24937. var result = this.resultBuffer,
  24938. values = this.sampleValues,
  24939. stride = this.valueSize,
  24940. o1 = i1 * stride, o0 = o1 - stride,
  24941. oP = this._offsetPrev, oN = this._offsetNext,
  24942. wP = this._weightPrev, wN = this._weightNext,
  24943. p = ( t - t0 ) / ( t1 - t0 ),
  24944. pp = p * p,
  24945. ppp = pp * p;
  24946. // evaluate polynomials
  24947. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  24948. var s0 = ( 1 + wP ) * ppp + ( - 1.5 - 2 * wP ) * pp + ( - 0.5 + wP ) * p + 1;
  24949. var s1 = ( - 1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  24950. var sN = wN * ppp - wN * pp;
  24951. // combine data linearly
  24952. for ( var i = 0; i !== stride; ++ i ) {
  24953. result[ i ] =
  24954. sP * values[ oP + i ] +
  24955. s0 * values[ o0 + i ] +
  24956. s1 * values[ o1 + i ] +
  24957. sN * values[ oN + i ];
  24958. }
  24959. return result;
  24960. }
  24961. } );
  24962. /**
  24963. * @author tschw
  24964. */
  24965. function LinearInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24966. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24967. }
  24968. LinearInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24969. constructor: LinearInterpolant,
  24970. interpolate_: function ( i1, t0, t, t1 ) {
  24971. var result = this.resultBuffer,
  24972. values = this.sampleValues,
  24973. stride = this.valueSize,
  24974. offset1 = i1 * stride,
  24975. offset0 = offset1 - stride,
  24976. weight1 = ( t - t0 ) / ( t1 - t0 ),
  24977. weight0 = 1 - weight1;
  24978. for ( var i = 0; i !== stride; ++ i ) {
  24979. result[ i ] =
  24980. values[ offset0 + i ] * weight0 +
  24981. values[ offset1 + i ] * weight1;
  24982. }
  24983. return result;
  24984. }
  24985. } );
  24986. /**
  24987. *
  24988. * Interpolant that evaluates to the sample value at the position preceeding
  24989. * the parameter.
  24990. *
  24991. * @author tschw
  24992. */
  24993. function DiscreteInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  24994. Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  24995. }
  24996. DiscreteInterpolant.prototype = Object.assign( Object.create( Interpolant.prototype ), {
  24997. constructor: DiscreteInterpolant,
  24998. interpolate_: function ( i1 /*, t0, t, t1 */ ) {
  24999. return this.copySampleValue_( i1 - 1 );
  25000. }
  25001. } );
  25002. /**
  25003. * @author tschw
  25004. * @author Ben Houston / http://clara.io/
  25005. * @author David Sarno / http://lighthaus.us/
  25006. */
  25007. var AnimationUtils = {
  25008. // same as Array.prototype.slice, but also works on typed arrays
  25009. arraySlice: function ( array, from, to ) {
  25010. if ( AnimationUtils.isTypedArray( array ) ) {
  25011. // in ios9 array.subarray(from, undefined) will return empty array
  25012. // but array.subarray(from) or array.subarray(from, len) is correct
  25013. return new array.constructor( array.subarray( from, to !== undefined ? to : array.length ) );
  25014. }
  25015. return array.slice( from, to );
  25016. },
  25017. // converts an array to a specific type
  25018. convertArray: function ( array, type, forceClone ) {
  25019. if ( ! array || // let 'undefined' and 'null' pass
  25020. ! forceClone && array.constructor === type ) return array;
  25021. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  25022. return new type( array ); // create typed array
  25023. }
  25024. return Array.prototype.slice.call( array ); // create Array
  25025. },
  25026. isTypedArray: function ( object ) {
  25027. return ArrayBuffer.isView( object ) &&
  25028. ! ( object instanceof DataView );
  25029. },
  25030. // returns an array by which times and values can be sorted
  25031. getKeyframeOrder: function ( times ) {
  25032. function compareTime( i, j ) {
  25033. return times[ i ] - times[ j ];
  25034. }
  25035. var n = times.length;
  25036. var result = new Array( n );
  25037. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  25038. result.sort( compareTime );
  25039. return result;
  25040. },
  25041. // uses the array previously returned by 'getKeyframeOrder' to sort data
  25042. sortedArray: function ( values, stride, order ) {
  25043. var nValues = values.length;
  25044. var result = new values.constructor( nValues );
  25045. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  25046. var srcOffset = order[ i ] * stride;
  25047. for ( var j = 0; j !== stride; ++ j ) {
  25048. result[ dstOffset ++ ] = values[ srcOffset + j ];
  25049. }
  25050. }
  25051. return result;
  25052. },
  25053. // function for parsing AOS keyframe formats
  25054. flattenJSON: function ( jsonKeys, times, values, valuePropertyName ) {
  25055. var i = 1, key = jsonKeys[ 0 ];
  25056. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  25057. key = jsonKeys[ i ++ ];
  25058. }
  25059. if ( key === undefined ) return; // no data
  25060. var value = key[ valuePropertyName ];
  25061. if ( value === undefined ) return; // no data
  25062. if ( Array.isArray( value ) ) {
  25063. do {
  25064. value = key[ valuePropertyName ];
  25065. if ( value !== undefined ) {
  25066. times.push( key.time );
  25067. values.push.apply( values, value ); // push all elements
  25068. }
  25069. key = jsonKeys[ i ++ ];
  25070. } while ( key !== undefined );
  25071. } else if ( value.toArray !== undefined ) {
  25072. // ...assume THREE.Math-ish
  25073. do {
  25074. value = key[ valuePropertyName ];
  25075. if ( value !== undefined ) {
  25076. times.push( key.time );
  25077. value.toArray( values, values.length );
  25078. }
  25079. key = jsonKeys[ i ++ ];
  25080. } while ( key !== undefined );
  25081. } else {
  25082. // otherwise push as-is
  25083. do {
  25084. value = key[ valuePropertyName ];
  25085. if ( value !== undefined ) {
  25086. times.push( key.time );
  25087. values.push( value );
  25088. }
  25089. key = jsonKeys[ i ++ ];
  25090. } while ( key !== undefined );
  25091. }
  25092. }
  25093. };
  25094. /**
  25095. *
  25096. * A timed sequence of keyframes for a specific property.
  25097. *
  25098. *
  25099. * @author Ben Houston / http://clara.io/
  25100. * @author David Sarno / http://lighthaus.us/
  25101. * @author tschw
  25102. */
  25103. function KeyframeTrack( name, times, values, interpolation ) {
  25104. if ( name === undefined ) throw new Error( 'THREE.KeyframeTrack: track name is undefined' );
  25105. if ( times === undefined || times.length === 0 ) throw new Error( 'THREE.KeyframeTrack: no keyframes in track named ' + name );
  25106. this.name = name;
  25107. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  25108. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  25109. this.setInterpolation( interpolation || this.DefaultInterpolation );
  25110. this.validate();
  25111. this.optimize();
  25112. }
  25113. // Static methods:
  25114. Object.assign( KeyframeTrack, {
  25115. // Serialization (in static context, because of constructor invocation
  25116. // and automatic invocation of .toJSON):
  25117. parse: function ( json ) {
  25118. if ( json.type === undefined ) {
  25119. throw new Error( 'THREE.KeyframeTrack: track type undefined, can not parse' );
  25120. }
  25121. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  25122. if ( json.times === undefined ) {
  25123. var times = [], values = [];
  25124. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  25125. json.times = times;
  25126. json.values = values;
  25127. }
  25128. // derived classes can define a static parse method
  25129. if ( trackType.parse !== undefined ) {
  25130. return trackType.parse( json );
  25131. } else {
  25132. // by default, we assume a constructor compatible with the base
  25133. return new trackType( json.name, json.times, json.values, json.interpolation );
  25134. }
  25135. },
  25136. toJSON: function ( track ) {
  25137. var trackType = track.constructor;
  25138. var json;
  25139. // derived classes can define a static toJSON method
  25140. if ( trackType.toJSON !== undefined ) {
  25141. json = trackType.toJSON( track );
  25142. } else {
  25143. // by default, we assume the data can be serialized as-is
  25144. json = {
  25145. 'name': track.name,
  25146. 'times': AnimationUtils.convertArray( track.times, Array ),
  25147. 'values': AnimationUtils.convertArray( track.values, Array )
  25148. };
  25149. var interpolation = track.getInterpolation();
  25150. if ( interpolation !== track.DefaultInterpolation ) {
  25151. json.interpolation = interpolation;
  25152. }
  25153. }
  25154. json.type = track.ValueTypeName; // mandatory
  25155. return json;
  25156. },
  25157. _getTrackTypeForValueTypeName: function ( typeName ) {
  25158. switch ( typeName.toLowerCase() ) {
  25159. case 'scalar':
  25160. case 'double':
  25161. case 'float':
  25162. case 'number':
  25163. case 'integer':
  25164. return NumberKeyframeTrack;
  25165. case 'vector':
  25166. case 'vector2':
  25167. case 'vector3':
  25168. case 'vector4':
  25169. return VectorKeyframeTrack;
  25170. case 'color':
  25171. return ColorKeyframeTrack;
  25172. case 'quaternion':
  25173. return QuaternionKeyframeTrack;
  25174. case 'bool':
  25175. case 'boolean':
  25176. return BooleanKeyframeTrack;
  25177. case 'string':
  25178. return StringKeyframeTrack;
  25179. }
  25180. throw new Error( 'THREE.KeyframeTrack: Unsupported typeName: ' + typeName );
  25181. }
  25182. } );
  25183. Object.assign( KeyframeTrack.prototype, {
  25184. constructor: KeyframeTrack,
  25185. TimeBufferType: Float32Array,
  25186. ValueBufferType: Float32Array,
  25187. DefaultInterpolation: InterpolateLinear,
  25188. InterpolantFactoryMethodDiscrete: function ( result ) {
  25189. return new DiscreteInterpolant( this.times, this.values, this.getValueSize(), result );
  25190. },
  25191. InterpolantFactoryMethodLinear: function ( result ) {
  25192. return new LinearInterpolant( this.times, this.values, this.getValueSize(), result );
  25193. },
  25194. InterpolantFactoryMethodSmooth: function ( result ) {
  25195. return new CubicInterpolant( this.times, this.values, this.getValueSize(), result );
  25196. },
  25197. setInterpolation: function ( interpolation ) {
  25198. var factoryMethod;
  25199. switch ( interpolation ) {
  25200. case InterpolateDiscrete:
  25201. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  25202. break;
  25203. case InterpolateLinear:
  25204. factoryMethod = this.InterpolantFactoryMethodLinear;
  25205. break;
  25206. case InterpolateSmooth:
  25207. factoryMethod = this.InterpolantFactoryMethodSmooth;
  25208. break;
  25209. }
  25210. if ( factoryMethod === undefined ) {
  25211. var message = "unsupported interpolation for " +
  25212. this.ValueTypeName + " keyframe track named " + this.name;
  25213. if ( this.createInterpolant === undefined ) {
  25214. // fall back to default, unless the default itself is messed up
  25215. if ( interpolation !== this.DefaultInterpolation ) {
  25216. this.setInterpolation( this.DefaultInterpolation );
  25217. } else {
  25218. throw new Error( message ); // fatal, in this case
  25219. }
  25220. }
  25221. console.warn( 'THREE.KeyframeTrack:', message );
  25222. return;
  25223. }
  25224. this.createInterpolant = factoryMethod;
  25225. },
  25226. getInterpolation: function () {
  25227. switch ( this.createInterpolant ) {
  25228. case this.InterpolantFactoryMethodDiscrete:
  25229. return InterpolateDiscrete;
  25230. case this.InterpolantFactoryMethodLinear:
  25231. return InterpolateLinear;
  25232. case this.InterpolantFactoryMethodSmooth:
  25233. return InterpolateSmooth;
  25234. }
  25235. },
  25236. getValueSize: function () {
  25237. return this.values.length / this.times.length;
  25238. },
  25239. // move all keyframes either forwards or backwards in time
  25240. shift: function ( timeOffset ) {
  25241. if ( timeOffset !== 0.0 ) {
  25242. var times = this.times;
  25243. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25244. times[ i ] += timeOffset;
  25245. }
  25246. }
  25247. return this;
  25248. },
  25249. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  25250. scale: function ( timeScale ) {
  25251. if ( timeScale !== 1.0 ) {
  25252. var times = this.times;
  25253. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  25254. times[ i ] *= timeScale;
  25255. }
  25256. }
  25257. return this;
  25258. },
  25259. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  25260. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  25261. trim: function ( startTime, endTime ) {
  25262. var times = this.times,
  25263. nKeys = times.length,
  25264. from = 0,
  25265. to = nKeys - 1;
  25266. while ( from !== nKeys && times[ from ] < startTime ) {
  25267. ++ from;
  25268. }
  25269. while ( to !== - 1 && times[ to ] > endTime ) {
  25270. -- to;
  25271. }
  25272. ++ to; // inclusive -> exclusive bound
  25273. if ( from !== 0 || to !== nKeys ) {
  25274. // empty tracks are forbidden, so keep at least one keyframe
  25275. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  25276. var stride = this.getValueSize();
  25277. this.times = AnimationUtils.arraySlice( times, from, to );
  25278. this.values = AnimationUtils.arraySlice( this.values, from * stride, to * stride );
  25279. }
  25280. return this;
  25281. },
  25282. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  25283. validate: function () {
  25284. var valid = true;
  25285. var valueSize = this.getValueSize();
  25286. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  25287. console.error( 'THREE.KeyframeTrack: Invalid value size in track.', this );
  25288. valid = false;
  25289. }
  25290. var times = this.times,
  25291. values = this.values,
  25292. nKeys = times.length;
  25293. if ( nKeys === 0 ) {
  25294. console.error( 'THREE.KeyframeTrack: Track is empty.', this );
  25295. valid = false;
  25296. }
  25297. var prevTime = null;
  25298. for ( var i = 0; i !== nKeys; i ++ ) {
  25299. var currTime = times[ i ];
  25300. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  25301. console.error( 'THREE.KeyframeTrack: Time is not a valid number.', this, i, currTime );
  25302. valid = false;
  25303. break;
  25304. }
  25305. if ( prevTime !== null && prevTime > currTime ) {
  25306. console.error( 'THREE.KeyframeTrack: Out of order keys.', this, i, currTime, prevTime );
  25307. valid = false;
  25308. break;
  25309. }
  25310. prevTime = currTime;
  25311. }
  25312. if ( values !== undefined ) {
  25313. if ( AnimationUtils.isTypedArray( values ) ) {
  25314. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  25315. var value = values[ i ];
  25316. if ( isNaN( value ) ) {
  25317. console.error( 'THREE.KeyframeTrack: Value is not a valid number.', this, i, value );
  25318. valid = false;
  25319. break;
  25320. }
  25321. }
  25322. }
  25323. }
  25324. return valid;
  25325. },
  25326. // removes equivalent sequential keys as common in morph target sequences
  25327. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  25328. optimize: function () {
  25329. var times = this.times,
  25330. values = this.values,
  25331. stride = this.getValueSize(),
  25332. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  25333. writeIndex = 1,
  25334. lastIndex = times.length - 1;
  25335. for ( var i = 1; i < lastIndex; ++ i ) {
  25336. var keep = false;
  25337. var time = times[ i ];
  25338. var timeNext = times[ i + 1 ];
  25339. // remove adjacent keyframes scheduled at the same time
  25340. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  25341. if ( ! smoothInterpolation ) {
  25342. // remove unnecessary keyframes same as their neighbors
  25343. var offset = i * stride,
  25344. offsetP = offset - stride,
  25345. offsetN = offset + stride;
  25346. for ( var j = 0; j !== stride; ++ j ) {
  25347. var value = values[ offset + j ];
  25348. if ( value !== values[ offsetP + j ] ||
  25349. value !== values[ offsetN + j ] ) {
  25350. keep = true;
  25351. break;
  25352. }
  25353. }
  25354. } else {
  25355. keep = true;
  25356. }
  25357. }
  25358. // in-place compaction
  25359. if ( keep ) {
  25360. if ( i !== writeIndex ) {
  25361. times[ writeIndex ] = times[ i ];
  25362. var readOffset = i * stride,
  25363. writeOffset = writeIndex * stride;
  25364. for ( var j = 0; j !== stride; ++ j ) {
  25365. values[ writeOffset + j ] = values[ readOffset + j ];
  25366. }
  25367. }
  25368. ++ writeIndex;
  25369. }
  25370. }
  25371. // flush last keyframe (compaction looks ahead)
  25372. if ( lastIndex > 0 ) {
  25373. times[ writeIndex ] = times[ lastIndex ];
  25374. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j ) {
  25375. values[ writeOffset + j ] = values[ readOffset + j ];
  25376. }
  25377. ++ writeIndex;
  25378. }
  25379. if ( writeIndex !== times.length ) {
  25380. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  25381. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  25382. }
  25383. return this;
  25384. }
  25385. } );
  25386. /**
  25387. *
  25388. * A Track of vectored keyframe values.
  25389. *
  25390. *
  25391. * @author Ben Houston / http://clara.io/
  25392. * @author David Sarno / http://lighthaus.us/
  25393. * @author tschw
  25394. */
  25395. function VectorKeyframeTrack( name, times, values, interpolation ) {
  25396. KeyframeTrack.call( this, name, times, values, interpolation );
  25397. }
  25398. VectorKeyframeTrack.prototype = Object.assign( Object.create( KeyframeTrack.prototype ), {
  25399. constructor: VectorKeyframeTrack,
  25400. ValueTypeName: 'vector'
  25401. // ValueBufferType is inherited
  25402. // DefaultInterpolation is inherited
  25403. } );
  25404. /**
  25405. *
  25406. * Reusable set of Tracks that represent an animation.
  25407. *
  25408. * @author Ben Houston / http://clara.io/
  25409. * @author David Sarno / http://lighthaus.us/
  25410. */
  25411. function AnimationClip( name, duration, tracks ) {
  25412. this.name = name;
  25413. this.tracks = tracks;
  25414. this.duration = ( duration !== undefined ) ? duration : - 1;
  25415. this.uuid = _Math.generateUUID();
  25416. // this means it should figure out its duration by scanning the tracks
  25417. if ( this.duration < 0 ) {
  25418. this.resetDuration();
  25419. }
  25420. this.optimize();
  25421. }
  25422. Object.assign( AnimationClip, {
  25423. parse: function ( json ) {
  25424. var tracks = [],
  25425. jsonTracks = json.tracks,
  25426. frameTime = 1.0 / ( json.fps || 1.0 );
  25427. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  25428. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  25429. }
  25430. return new AnimationClip( json.name, json.duration, tracks );
  25431. },
  25432. toJSON: function ( clip ) {
  25433. var tracks = [],
  25434. clipTracks = clip.tracks;
  25435. var json = {
  25436. 'name': clip.name,
  25437. 'duration': clip.duration,
  25438. 'tracks': tracks
  25439. };
  25440. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  25441. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  25442. }
  25443. return json;
  25444. },
  25445. CreateFromMorphTargetSequence: function ( name, morphTargetSequence, fps, noLoop ) {
  25446. var numMorphTargets = morphTargetSequence.length;
  25447. var tracks = [];
  25448. for ( var i = 0; i < numMorphTargets; i ++ ) {
  25449. var times = [];
  25450. var values = [];
  25451. times.push(
  25452. ( i + numMorphTargets - 1 ) % numMorphTargets,
  25453. i,
  25454. ( i + 1 ) % numMorphTargets );
  25455. values.push( 0, 1, 0 );
  25456. var order = AnimationUtils.getKeyframeOrder( times );
  25457. times = AnimationUtils.sortedArray( times, 1, order );
  25458. values = AnimationUtils.sortedArray( values, 1, order );
  25459. // if there is a key at the first frame, duplicate it as the
  25460. // last frame as well for perfect loop.
  25461. if ( ! noLoop && times[ 0 ] === 0 ) {
  25462. times.push( numMorphTargets );
  25463. values.push( values[ 0 ] );
  25464. }
  25465. tracks.push(
  25466. new NumberKeyframeTrack(
  25467. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  25468. times, values
  25469. ).scale( 1.0 / fps ) );
  25470. }
  25471. return new AnimationClip( name, - 1, tracks );
  25472. },
  25473. findByName: function ( objectOrClipArray, name ) {
  25474. var clipArray = objectOrClipArray;
  25475. if ( ! Array.isArray( objectOrClipArray ) ) {
  25476. var o = objectOrClipArray;
  25477. clipArray = o.geometry && o.geometry.animations || o.animations;
  25478. }
  25479. for ( var i = 0; i < clipArray.length; i ++ ) {
  25480. if ( clipArray[ i ].name === name ) {
  25481. return clipArray[ i ];
  25482. }
  25483. }
  25484. return null;
  25485. },
  25486. CreateClipsFromMorphTargetSequences: function ( morphTargets, fps, noLoop ) {
  25487. var animationToMorphTargets = {};
  25488. // tested with https://regex101.com/ on trick sequences
  25489. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  25490. var pattern = /^([\w-]*?)([\d]+)$/;
  25491. // sort morph target names into animation groups based
  25492. // patterns like Walk_001, Walk_002, Run_001, Run_002
  25493. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  25494. var morphTarget = morphTargets[ i ];
  25495. var parts = morphTarget.name.match( pattern );
  25496. if ( parts && parts.length > 1 ) {
  25497. var name = parts[ 1 ];
  25498. var animationMorphTargets = animationToMorphTargets[ name ];
  25499. if ( ! animationMorphTargets ) {
  25500. animationToMorphTargets[ name ] = animationMorphTargets = [];
  25501. }
  25502. animationMorphTargets.push( morphTarget );
  25503. }
  25504. }
  25505. var clips = [];
  25506. for ( var name in animationToMorphTargets ) {
  25507. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  25508. }
  25509. return clips;
  25510. },
  25511. // parse the animation.hierarchy format
  25512. parseAnimation: function ( animation, bones ) {
  25513. if ( ! animation ) {
  25514. console.error( 'THREE.AnimationClip: No animation in JSONLoader data.' );
  25515. return null;
  25516. }
  25517. var addNonemptyTrack = function ( trackType, trackName, animationKeys, propertyName, destTracks ) {
  25518. // only return track if there are actually keys.
  25519. if ( animationKeys.length !== 0 ) {
  25520. var times = [];
  25521. var values = [];
  25522. AnimationUtils.flattenJSON( animationKeys, times, values, propertyName );
  25523. // empty keys are filtered out, so check again
  25524. if ( times.length !== 0 ) {
  25525. destTracks.push( new trackType( trackName, times, values ) );
  25526. }
  25527. }
  25528. };
  25529. var tracks = [];
  25530. var clipName = animation.name || 'default';
  25531. // automatic length determination in AnimationClip.
  25532. var duration = animation.length || - 1;
  25533. var fps = animation.fps || 30;
  25534. var hierarchyTracks = animation.hierarchy || [];
  25535. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  25536. var animationKeys = hierarchyTracks[ h ].keys;
  25537. // skip empty tracks
  25538. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  25539. // process morph targets
  25540. if ( animationKeys[ 0 ].morphTargets ) {
  25541. // figure out all morph targets used in this track
  25542. var morphTargetNames = {};
  25543. for ( var k = 0; k < animationKeys.length; k ++ ) {
  25544. if ( animationKeys[ k ].morphTargets ) {
  25545. for ( var m = 0; m < animationKeys[ k ].morphTargets.length; m ++ ) {
  25546. morphTargetNames[ animationKeys[ k ].morphTargets[ m ] ] = - 1;
  25547. }
  25548. }
  25549. }
  25550. // create a track for each morph target with all zero
  25551. // morphTargetInfluences except for the keys in which
  25552. // the morphTarget is named.
  25553. for ( var morphTargetName in morphTargetNames ) {
  25554. var times = [];
  25555. var values = [];
  25556. for ( var m = 0; m !== animationKeys[ k ].morphTargets.length; ++ m ) {
  25557. var animationKey = animationKeys[ k ];
  25558. times.push( animationKey.time );
  25559. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  25560. }
  25561. tracks.push( new NumberKeyframeTrack( '.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  25562. }
  25563. duration = morphTargetNames.length * ( fps || 1.0 );
  25564. } else {
  25565. // ...assume skeletal animation
  25566. var boneName = '.bones[' + bones[ h ].name + ']';
  25567. addNonemptyTrack(
  25568. VectorKeyframeTrack, boneName + '.position',
  25569. animationKeys, 'pos', tracks );
  25570. addNonemptyTrack(
  25571. QuaternionKeyframeTrack, boneName + '.quaternion',
  25572. animationKeys, 'rot', tracks );
  25573. addNonemptyTrack(
  25574. VectorKeyframeTrack, boneName + '.scale',
  25575. animationKeys, 'scl', tracks );
  25576. }
  25577. }
  25578. if ( tracks.length === 0 ) {
  25579. return null;
  25580. }
  25581. var clip = new AnimationClip( clipName, duration, tracks );
  25582. return clip;
  25583. }
  25584. } );
  25585. Object.assign( AnimationClip.prototype, {
  25586. resetDuration: function () {
  25587. var tracks = this.tracks, duration = 0;
  25588. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  25589. var track = this.tracks[ i ];
  25590. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  25591. }
  25592. this.duration = duration;
  25593. },
  25594. trim: function () {
  25595. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25596. this.tracks[ i ].trim( 0, this.duration );
  25597. }
  25598. return this;
  25599. },
  25600. optimize: function () {
  25601. for ( var i = 0; i < this.tracks.length; i ++ ) {
  25602. this.tracks[ i ].optimize();
  25603. }
  25604. return this;
  25605. }
  25606. } );
  25607. /**
  25608. * @author mrdoob / http://mrdoob.com/
  25609. */
  25610. function MaterialLoader( manager ) {
  25611. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25612. this.textures = {};
  25613. }
  25614. Object.assign( MaterialLoader.prototype, {
  25615. load: function ( url, onLoad, onProgress, onError ) {
  25616. var scope = this;
  25617. var loader = new FileLoader( scope.manager );
  25618. loader.load( url, function ( text ) {
  25619. onLoad( scope.parse( JSON.parse( text ) ) );
  25620. }, onProgress, onError );
  25621. },
  25622. setTextures: function ( value ) {
  25623. this.textures = value;
  25624. },
  25625. parse: function ( json ) {
  25626. var textures = this.textures;
  25627. function getTexture( name ) {
  25628. if ( textures[ name ] === undefined ) {
  25629. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  25630. }
  25631. return textures[ name ];
  25632. }
  25633. var material = new Materials[ json.type ]();
  25634. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  25635. if ( json.name !== undefined ) material.name = json.name;
  25636. if ( json.color !== undefined ) material.color.setHex( json.color );
  25637. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  25638. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  25639. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  25640. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  25641. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  25642. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  25643. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  25644. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  25645. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  25646. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  25647. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  25648. if ( json.fog !== undefined ) material.fog = json.fog;
  25649. if ( json.flatShading !== undefined ) material.flatShading = json.flatShading;
  25650. if ( json.blending !== undefined ) material.blending = json.blending;
  25651. if ( json.side !== undefined ) material.side = json.side;
  25652. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  25653. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  25654. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  25655. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  25656. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  25657. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  25658. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  25659. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  25660. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  25661. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  25662. if ( json.rotation !== undefined ) material.rotation = json.rotation;
  25663. if ( json.linewidth !== 1 ) material.linewidth = json.linewidth;
  25664. if ( json.dashSize !== undefined ) material.dashSize = json.dashSize;
  25665. if ( json.gapSize !== undefined ) material.gapSize = json.gapSize;
  25666. if ( json.scale !== undefined ) material.scale = json.scale;
  25667. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  25668. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  25669. if ( json.dithering !== undefined ) material.dithering = json.dithering;
  25670. if ( json.visible !== undefined ) material.visible = json.visible;
  25671. if ( json.userData !== undefined ) material.userData = json.userData;
  25672. // Deprecated
  25673. if ( json.shading !== undefined ) material.flatShading = json.shading === 1; // THREE.FlatShading
  25674. // for PointsMaterial
  25675. if ( json.size !== undefined ) material.size = json.size;
  25676. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  25677. // maps
  25678. if ( json.map !== undefined ) material.map = getTexture( json.map );
  25679. if ( json.alphaMap !== undefined ) {
  25680. material.alphaMap = getTexture( json.alphaMap );
  25681. material.transparent = true;
  25682. }
  25683. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  25684. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  25685. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  25686. if ( json.normalScale !== undefined ) {
  25687. var normalScale = json.normalScale;
  25688. if ( Array.isArray( normalScale ) === false ) {
  25689. // Blender exporter used to export a scalar. See #7459
  25690. normalScale = [ normalScale, normalScale ];
  25691. }
  25692. material.normalScale = new Vector2().fromArray( normalScale );
  25693. }
  25694. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  25695. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  25696. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  25697. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  25698. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  25699. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  25700. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  25701. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  25702. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  25703. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  25704. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  25705. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  25706. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  25707. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  25708. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  25709. return material;
  25710. }
  25711. } );
  25712. /**
  25713. * @author mrdoob / http://mrdoob.com/
  25714. */
  25715. function BufferGeometryLoader( manager ) {
  25716. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25717. }
  25718. Object.assign( BufferGeometryLoader.prototype, {
  25719. load: function ( url, onLoad, onProgress, onError ) {
  25720. var scope = this;
  25721. var loader = new FileLoader( scope.manager );
  25722. loader.load( url, function ( text ) {
  25723. onLoad( scope.parse( JSON.parse( text ) ) );
  25724. }, onProgress, onError );
  25725. },
  25726. parse: function ( json ) {
  25727. var geometry = new BufferGeometry();
  25728. var index = json.data.index;
  25729. if ( index !== undefined ) {
  25730. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  25731. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  25732. }
  25733. var attributes = json.data.attributes;
  25734. for ( var key in attributes ) {
  25735. var attribute = attributes[ key ];
  25736. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  25737. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  25738. }
  25739. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  25740. if ( groups !== undefined ) {
  25741. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  25742. var group = groups[ i ];
  25743. geometry.addGroup( group.start, group.count, group.materialIndex );
  25744. }
  25745. }
  25746. var boundingSphere = json.data.boundingSphere;
  25747. if ( boundingSphere !== undefined ) {
  25748. var center = new Vector3();
  25749. if ( boundingSphere.center !== undefined ) {
  25750. center.fromArray( boundingSphere.center );
  25751. }
  25752. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  25753. }
  25754. return geometry;
  25755. }
  25756. } );
  25757. var TYPED_ARRAYS = {
  25758. Int8Array: Int8Array,
  25759. Uint8Array: Uint8Array,
  25760. // Workaround for IE11 pre KB2929437. See #11440
  25761. Uint8ClampedArray: typeof Uint8ClampedArray !== 'undefined' ? Uint8ClampedArray : Uint8Array,
  25762. Int16Array: Int16Array,
  25763. Uint16Array: Uint16Array,
  25764. Int32Array: Int32Array,
  25765. Uint32Array: Uint32Array,
  25766. Float32Array: Float32Array,
  25767. Float64Array: Float64Array
  25768. };
  25769. /**
  25770. * @author alteredq / http://alteredqualia.com/
  25771. */
  25772. function Loader() {
  25773. this.onLoadStart = function () {};
  25774. this.onLoadProgress = function () {};
  25775. this.onLoadComplete = function () {};
  25776. }
  25777. Loader.Handlers = {
  25778. handlers: [],
  25779. add: function ( regex, loader ) {
  25780. this.handlers.push( regex, loader );
  25781. },
  25782. get: function ( file ) {
  25783. var handlers = this.handlers;
  25784. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  25785. var regex = handlers[ i ];
  25786. var loader = handlers[ i + 1 ];
  25787. if ( regex.test( file ) ) {
  25788. return loader;
  25789. }
  25790. }
  25791. return null;
  25792. }
  25793. };
  25794. Object.assign( Loader.prototype, {
  25795. crossOrigin: undefined,
  25796. initMaterials: function ( materials, texturePath, crossOrigin ) {
  25797. var array = [];
  25798. for ( var i = 0; i < materials.length; ++ i ) {
  25799. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  25800. }
  25801. return array;
  25802. },
  25803. createMaterial: ( function () {
  25804. var BlendingMode = {
  25805. NoBlending: NoBlending,
  25806. NormalBlending: NormalBlending,
  25807. AdditiveBlending: AdditiveBlending,
  25808. SubtractiveBlending: SubtractiveBlending,
  25809. MultiplyBlending: MultiplyBlending,
  25810. CustomBlending: CustomBlending
  25811. };
  25812. var color = new Color();
  25813. var textureLoader = new TextureLoader();
  25814. var materialLoader = new MaterialLoader();
  25815. return function createMaterial( m, texturePath, crossOrigin ) {
  25816. // convert from old material format
  25817. var textures = {};
  25818. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  25819. var fullPath = texturePath + path;
  25820. var loader = Loader.Handlers.get( fullPath );
  25821. var texture;
  25822. if ( loader !== null ) {
  25823. texture = loader.load( fullPath );
  25824. } else {
  25825. textureLoader.setCrossOrigin( crossOrigin );
  25826. texture = textureLoader.load( fullPath );
  25827. }
  25828. if ( repeat !== undefined ) {
  25829. texture.repeat.fromArray( repeat );
  25830. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  25831. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  25832. }
  25833. if ( offset !== undefined ) {
  25834. texture.offset.fromArray( offset );
  25835. }
  25836. if ( wrap !== undefined ) {
  25837. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  25838. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  25839. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  25840. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  25841. }
  25842. if ( anisotropy !== undefined ) {
  25843. texture.anisotropy = anisotropy;
  25844. }
  25845. var uuid = _Math.generateUUID();
  25846. textures[ uuid ] = texture;
  25847. return uuid;
  25848. }
  25849. //
  25850. var json = {
  25851. uuid: _Math.generateUUID(),
  25852. type: 'MeshLambertMaterial'
  25853. };
  25854. for ( var name in m ) {
  25855. var value = m[ name ];
  25856. switch ( name ) {
  25857. case 'DbgColor':
  25858. case 'DbgIndex':
  25859. case 'opticalDensity':
  25860. case 'illumination':
  25861. break;
  25862. case 'DbgName':
  25863. json.name = value;
  25864. break;
  25865. case 'blending':
  25866. json.blending = BlendingMode[ value ];
  25867. break;
  25868. case 'colorAmbient':
  25869. case 'mapAmbient':
  25870. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  25871. break;
  25872. case 'colorDiffuse':
  25873. json.color = color.fromArray( value ).getHex();
  25874. break;
  25875. case 'colorSpecular':
  25876. json.specular = color.fromArray( value ).getHex();
  25877. break;
  25878. case 'colorEmissive':
  25879. json.emissive = color.fromArray( value ).getHex();
  25880. break;
  25881. case 'specularCoef':
  25882. json.shininess = value;
  25883. break;
  25884. case 'shading':
  25885. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  25886. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  25887. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  25888. break;
  25889. case 'mapDiffuse':
  25890. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  25891. break;
  25892. case 'mapDiffuseRepeat':
  25893. case 'mapDiffuseOffset':
  25894. case 'mapDiffuseWrap':
  25895. case 'mapDiffuseAnisotropy':
  25896. break;
  25897. case 'mapEmissive':
  25898. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  25899. break;
  25900. case 'mapEmissiveRepeat':
  25901. case 'mapEmissiveOffset':
  25902. case 'mapEmissiveWrap':
  25903. case 'mapEmissiveAnisotropy':
  25904. break;
  25905. case 'mapLight':
  25906. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  25907. break;
  25908. case 'mapLightRepeat':
  25909. case 'mapLightOffset':
  25910. case 'mapLightWrap':
  25911. case 'mapLightAnisotropy':
  25912. break;
  25913. case 'mapAO':
  25914. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  25915. break;
  25916. case 'mapAORepeat':
  25917. case 'mapAOOffset':
  25918. case 'mapAOWrap':
  25919. case 'mapAOAnisotropy':
  25920. break;
  25921. case 'mapBump':
  25922. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  25923. break;
  25924. case 'mapBumpScale':
  25925. json.bumpScale = value;
  25926. break;
  25927. case 'mapBumpRepeat':
  25928. case 'mapBumpOffset':
  25929. case 'mapBumpWrap':
  25930. case 'mapBumpAnisotropy':
  25931. break;
  25932. case 'mapNormal':
  25933. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  25934. break;
  25935. case 'mapNormalFactor':
  25936. json.normalScale = [ value, value ];
  25937. break;
  25938. case 'mapNormalRepeat':
  25939. case 'mapNormalOffset':
  25940. case 'mapNormalWrap':
  25941. case 'mapNormalAnisotropy':
  25942. break;
  25943. case 'mapSpecular':
  25944. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  25945. break;
  25946. case 'mapSpecularRepeat':
  25947. case 'mapSpecularOffset':
  25948. case 'mapSpecularWrap':
  25949. case 'mapSpecularAnisotropy':
  25950. break;
  25951. case 'mapMetalness':
  25952. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  25953. break;
  25954. case 'mapMetalnessRepeat':
  25955. case 'mapMetalnessOffset':
  25956. case 'mapMetalnessWrap':
  25957. case 'mapMetalnessAnisotropy':
  25958. break;
  25959. case 'mapRoughness':
  25960. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  25961. break;
  25962. case 'mapRoughnessRepeat':
  25963. case 'mapRoughnessOffset':
  25964. case 'mapRoughnessWrap':
  25965. case 'mapRoughnessAnisotropy':
  25966. break;
  25967. case 'mapAlpha':
  25968. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  25969. break;
  25970. case 'mapAlphaRepeat':
  25971. case 'mapAlphaOffset':
  25972. case 'mapAlphaWrap':
  25973. case 'mapAlphaAnisotropy':
  25974. break;
  25975. case 'flipSided':
  25976. json.side = BackSide;
  25977. break;
  25978. case 'doubleSided':
  25979. json.side = DoubleSide;
  25980. break;
  25981. case 'transparency':
  25982. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  25983. json.opacity = value;
  25984. break;
  25985. case 'depthTest':
  25986. case 'depthWrite':
  25987. case 'colorWrite':
  25988. case 'opacity':
  25989. case 'reflectivity':
  25990. case 'transparent':
  25991. case 'visible':
  25992. case 'wireframe':
  25993. json[ name ] = value;
  25994. break;
  25995. case 'vertexColors':
  25996. if ( value === true ) json.vertexColors = VertexColors;
  25997. if ( value === 'face' ) json.vertexColors = FaceColors;
  25998. break;
  25999. default:
  26000. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  26001. break;
  26002. }
  26003. }
  26004. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  26005. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  26006. if ( json.opacity < 1 ) json.transparent = true;
  26007. materialLoader.setTextures( textures );
  26008. return materialLoader.parse( json );
  26009. };
  26010. } )()
  26011. } );
  26012. /**
  26013. * @author Don McCurdy / https://www.donmccurdy.com
  26014. */
  26015. var LoaderUtils = {
  26016. decodeText: function ( array ) {
  26017. if ( typeof TextDecoder !== 'undefined' ) {
  26018. return new TextDecoder().decode( array );
  26019. }
  26020. // Avoid the String.fromCharCode.apply(null, array) shortcut, which
  26021. // throws a "maximum call stack size exceeded" error for large arrays.
  26022. var s = '';
  26023. for ( var i = 0, il = array.length; i < il; i ++ ) {
  26024. // Implicitly assumes little-endian.
  26025. s += String.fromCharCode( array[ i ] );
  26026. }
  26027. return s;
  26028. },
  26029. extractUrlBase: function ( url ) {
  26030. var parts = url.split( '/' );
  26031. if ( parts.length === 1 ) return './';
  26032. parts.pop();
  26033. return parts.join( '/' ) + '/';
  26034. }
  26035. };
  26036. /**
  26037. * @author mrdoob / http://mrdoob.com/
  26038. * @author alteredq / http://alteredqualia.com/
  26039. */
  26040. function JSONLoader( manager ) {
  26041. if ( typeof manager === 'boolean' ) {
  26042. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  26043. manager = undefined;
  26044. }
  26045. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26046. this.withCredentials = false;
  26047. }
  26048. Object.assign( JSONLoader.prototype, {
  26049. load: function ( url, onLoad, onProgress, onError ) {
  26050. var scope = this;
  26051. var texturePath = this.texturePath && ( typeof this.texturePath === 'string' ) ? this.texturePath : LoaderUtils.extractUrlBase( url );
  26052. var loader = new FileLoader( this.manager );
  26053. loader.setWithCredentials( this.withCredentials );
  26054. loader.load( url, function ( text ) {
  26055. var json = JSON.parse( text );
  26056. var metadata = json.metadata;
  26057. if ( metadata !== undefined ) {
  26058. var type = metadata.type;
  26059. if ( type !== undefined ) {
  26060. if ( type.toLowerCase() === 'object' ) {
  26061. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  26062. return;
  26063. }
  26064. if ( type.toLowerCase() === 'scene' ) {
  26065. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  26066. return;
  26067. }
  26068. }
  26069. }
  26070. var object = scope.parse( json, texturePath );
  26071. onLoad( object.geometry, object.materials );
  26072. }, onProgress, onError );
  26073. },
  26074. setTexturePath: function ( value ) {
  26075. this.texturePath = value;
  26076. },
  26077. parse: ( function () {
  26078. function parseModel( json, geometry ) {
  26079. function isBitSet( value, position ) {
  26080. return value & ( 1 << position );
  26081. }
  26082. var i, j, fi,
  26083. offset, zLength,
  26084. colorIndex, normalIndex, uvIndex, materialIndex,
  26085. type,
  26086. isQuad,
  26087. hasMaterial,
  26088. hasFaceVertexUv,
  26089. hasFaceNormal, hasFaceVertexNormal,
  26090. hasFaceColor, hasFaceVertexColor,
  26091. vertex, face, faceA, faceB, hex, normal,
  26092. uvLayer, uv, u, v,
  26093. faces = json.faces,
  26094. vertices = json.vertices,
  26095. normals = json.normals,
  26096. colors = json.colors,
  26097. scale = json.scale,
  26098. nUvLayers = 0;
  26099. if ( json.uvs !== undefined ) {
  26100. // disregard empty arrays
  26101. for ( i = 0; i < json.uvs.length; i ++ ) {
  26102. if ( json.uvs[ i ].length ) nUvLayers ++;
  26103. }
  26104. for ( i = 0; i < nUvLayers; i ++ ) {
  26105. geometry.faceVertexUvs[ i ] = [];
  26106. }
  26107. }
  26108. offset = 0;
  26109. zLength = vertices.length;
  26110. while ( offset < zLength ) {
  26111. vertex = new Vector3();
  26112. vertex.x = vertices[ offset ++ ] * scale;
  26113. vertex.y = vertices[ offset ++ ] * scale;
  26114. vertex.z = vertices[ offset ++ ] * scale;
  26115. geometry.vertices.push( vertex );
  26116. }
  26117. offset = 0;
  26118. zLength = faces.length;
  26119. while ( offset < zLength ) {
  26120. type = faces[ offset ++ ];
  26121. isQuad = isBitSet( type, 0 );
  26122. hasMaterial = isBitSet( type, 1 );
  26123. hasFaceVertexUv = isBitSet( type, 3 );
  26124. hasFaceNormal = isBitSet( type, 4 );
  26125. hasFaceVertexNormal = isBitSet( type, 5 );
  26126. hasFaceColor = isBitSet( type, 6 );
  26127. hasFaceVertexColor = isBitSet( type, 7 );
  26128. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  26129. if ( isQuad ) {
  26130. faceA = new Face3();
  26131. faceA.a = faces[ offset ];
  26132. faceA.b = faces[ offset + 1 ];
  26133. faceA.c = faces[ offset + 3 ];
  26134. faceB = new Face3();
  26135. faceB.a = faces[ offset + 1 ];
  26136. faceB.b = faces[ offset + 2 ];
  26137. faceB.c = faces[ offset + 3 ];
  26138. offset += 4;
  26139. if ( hasMaterial ) {
  26140. materialIndex = faces[ offset ++ ];
  26141. faceA.materialIndex = materialIndex;
  26142. faceB.materialIndex = materialIndex;
  26143. }
  26144. // to get face <=> uv index correspondence
  26145. fi = geometry.faces.length;
  26146. if ( hasFaceVertexUv ) {
  26147. for ( i = 0; i < nUvLayers; i ++ ) {
  26148. uvLayer = json.uvs[ i ];
  26149. geometry.faceVertexUvs[ i ][ fi ] = [];
  26150. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  26151. for ( j = 0; j < 4; j ++ ) {
  26152. uvIndex = faces[ offset ++ ];
  26153. u = uvLayer[ uvIndex * 2 ];
  26154. v = uvLayer[ uvIndex * 2 + 1 ];
  26155. uv = new Vector2( u, v );
  26156. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26157. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  26158. }
  26159. }
  26160. }
  26161. if ( hasFaceNormal ) {
  26162. normalIndex = faces[ offset ++ ] * 3;
  26163. faceA.normal.set(
  26164. normals[ normalIndex ++ ],
  26165. normals[ normalIndex ++ ],
  26166. normals[ normalIndex ]
  26167. );
  26168. faceB.normal.copy( faceA.normal );
  26169. }
  26170. if ( hasFaceVertexNormal ) {
  26171. for ( i = 0; i < 4; i ++ ) {
  26172. normalIndex = faces[ offset ++ ] * 3;
  26173. normal = new Vector3(
  26174. normals[ normalIndex ++ ],
  26175. normals[ normalIndex ++ ],
  26176. normals[ normalIndex ]
  26177. );
  26178. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  26179. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  26180. }
  26181. }
  26182. if ( hasFaceColor ) {
  26183. colorIndex = faces[ offset ++ ];
  26184. hex = colors[ colorIndex ];
  26185. faceA.color.setHex( hex );
  26186. faceB.color.setHex( hex );
  26187. }
  26188. if ( hasFaceVertexColor ) {
  26189. for ( i = 0; i < 4; i ++ ) {
  26190. colorIndex = faces[ offset ++ ];
  26191. hex = colors[ colorIndex ];
  26192. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  26193. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  26194. }
  26195. }
  26196. geometry.faces.push( faceA );
  26197. geometry.faces.push( faceB );
  26198. } else {
  26199. face = new Face3();
  26200. face.a = faces[ offset ++ ];
  26201. face.b = faces[ offset ++ ];
  26202. face.c = faces[ offset ++ ];
  26203. if ( hasMaterial ) {
  26204. materialIndex = faces[ offset ++ ];
  26205. face.materialIndex = materialIndex;
  26206. }
  26207. // to get face <=> uv index correspondence
  26208. fi = geometry.faces.length;
  26209. if ( hasFaceVertexUv ) {
  26210. for ( i = 0; i < nUvLayers; i ++ ) {
  26211. uvLayer = json.uvs[ i ];
  26212. geometry.faceVertexUvs[ i ][ fi ] = [];
  26213. for ( j = 0; j < 3; j ++ ) {
  26214. uvIndex = faces[ offset ++ ];
  26215. u = uvLayer[ uvIndex * 2 ];
  26216. v = uvLayer[ uvIndex * 2 + 1 ];
  26217. uv = new Vector2( u, v );
  26218. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  26219. }
  26220. }
  26221. }
  26222. if ( hasFaceNormal ) {
  26223. normalIndex = faces[ offset ++ ] * 3;
  26224. face.normal.set(
  26225. normals[ normalIndex ++ ],
  26226. normals[ normalIndex ++ ],
  26227. normals[ normalIndex ]
  26228. );
  26229. }
  26230. if ( hasFaceVertexNormal ) {
  26231. for ( i = 0; i < 3; i ++ ) {
  26232. normalIndex = faces[ offset ++ ] * 3;
  26233. normal = new Vector3(
  26234. normals[ normalIndex ++ ],
  26235. normals[ normalIndex ++ ],
  26236. normals[ normalIndex ]
  26237. );
  26238. face.vertexNormals.push( normal );
  26239. }
  26240. }
  26241. if ( hasFaceColor ) {
  26242. colorIndex = faces[ offset ++ ];
  26243. face.color.setHex( colors[ colorIndex ] );
  26244. }
  26245. if ( hasFaceVertexColor ) {
  26246. for ( i = 0; i < 3; i ++ ) {
  26247. colorIndex = faces[ offset ++ ];
  26248. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  26249. }
  26250. }
  26251. geometry.faces.push( face );
  26252. }
  26253. }
  26254. }
  26255. function parseSkin( json, geometry ) {
  26256. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  26257. if ( json.skinWeights ) {
  26258. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  26259. var x = json.skinWeights[ i ];
  26260. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  26261. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  26262. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  26263. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  26264. }
  26265. }
  26266. if ( json.skinIndices ) {
  26267. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  26268. var a = json.skinIndices[ i ];
  26269. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  26270. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  26271. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  26272. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  26273. }
  26274. }
  26275. geometry.bones = json.bones;
  26276. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  26277. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  26278. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  26279. }
  26280. }
  26281. function parseMorphing( json, geometry ) {
  26282. var scale = json.scale;
  26283. if ( json.morphTargets !== undefined ) {
  26284. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  26285. geometry.morphTargets[ i ] = {};
  26286. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  26287. geometry.morphTargets[ i ].vertices = [];
  26288. var dstVertices = geometry.morphTargets[ i ].vertices;
  26289. var srcVertices = json.morphTargets[ i ].vertices;
  26290. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  26291. var vertex = new Vector3();
  26292. vertex.x = srcVertices[ v ] * scale;
  26293. vertex.y = srcVertices[ v + 1 ] * scale;
  26294. vertex.z = srcVertices[ v + 2 ] * scale;
  26295. dstVertices.push( vertex );
  26296. }
  26297. }
  26298. }
  26299. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  26300. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  26301. var faces = geometry.faces;
  26302. var morphColors = json.morphColors[ 0 ].colors;
  26303. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  26304. faces[ i ].color.fromArray( morphColors, i * 3 );
  26305. }
  26306. }
  26307. }
  26308. function parseAnimations( json, geometry ) {
  26309. var outputAnimations = [];
  26310. // parse old style Bone/Hierarchy animations
  26311. var animations = [];
  26312. if ( json.animation !== undefined ) {
  26313. animations.push( json.animation );
  26314. }
  26315. if ( json.animations !== undefined ) {
  26316. if ( json.animations.length ) {
  26317. animations = animations.concat( json.animations );
  26318. } else {
  26319. animations.push( json.animations );
  26320. }
  26321. }
  26322. for ( var i = 0; i < animations.length; i ++ ) {
  26323. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  26324. if ( clip ) outputAnimations.push( clip );
  26325. }
  26326. // parse implicit morph animations
  26327. if ( geometry.morphTargets ) {
  26328. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  26329. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  26330. outputAnimations = outputAnimations.concat( morphAnimationClips );
  26331. }
  26332. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  26333. }
  26334. return function ( json, texturePath ) {
  26335. if ( json.data !== undefined ) {
  26336. // Geometry 4.0 spec
  26337. json = json.data;
  26338. }
  26339. if ( json.scale !== undefined ) {
  26340. json.scale = 1.0 / json.scale;
  26341. } else {
  26342. json.scale = 1.0;
  26343. }
  26344. var geometry = new Geometry();
  26345. parseModel( json, geometry );
  26346. parseSkin( json, geometry );
  26347. parseMorphing( json, geometry );
  26348. parseAnimations( json, geometry );
  26349. geometry.computeFaceNormals();
  26350. geometry.computeBoundingSphere();
  26351. if ( json.materials === undefined || json.materials.length === 0 ) {
  26352. return { geometry: geometry };
  26353. } else {
  26354. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  26355. return { geometry: geometry, materials: materials };
  26356. }
  26357. };
  26358. } )()
  26359. } );
  26360. /**
  26361. * @author mrdoob / http://mrdoob.com/
  26362. */
  26363. function ObjectLoader( manager ) {
  26364. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  26365. this.texturePath = '';
  26366. }
  26367. Object.assign( ObjectLoader.prototype, {
  26368. load: function ( url, onLoad, onProgress, onError ) {
  26369. if ( this.texturePath === '' ) {
  26370. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  26371. }
  26372. var scope = this;
  26373. var loader = new FileLoader( scope.manager );
  26374. loader.load( url, function ( text ) {
  26375. var json = null;
  26376. try {
  26377. json = JSON.parse( text );
  26378. } catch ( error ) {
  26379. if ( onError !== undefined ) onError( error );
  26380. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  26381. return;
  26382. }
  26383. var metadata = json.metadata;
  26384. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  26385. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  26386. return;
  26387. }
  26388. scope.parse( json, onLoad );
  26389. }, onProgress, onError );
  26390. },
  26391. setTexturePath: function ( value ) {
  26392. this.texturePath = value;
  26393. },
  26394. setCrossOrigin: function ( value ) {
  26395. this.crossOrigin = value;
  26396. },
  26397. parse: function ( json, onLoad ) {
  26398. var shapes = this.parseShape( json.shapes );
  26399. var geometries = this.parseGeometries( json.geometries, shapes );
  26400. var images = this.parseImages( json.images, function () {
  26401. if ( onLoad !== undefined ) onLoad( object );
  26402. } );
  26403. var textures = this.parseTextures( json.textures, images );
  26404. var materials = this.parseMaterials( json.materials, textures );
  26405. var object = this.parseObject( json.object, geometries, materials );
  26406. if ( json.animations ) {
  26407. object.animations = this.parseAnimations( json.animations );
  26408. }
  26409. if ( json.images === undefined || json.images.length === 0 ) {
  26410. if ( onLoad !== undefined ) onLoad( object );
  26411. }
  26412. return object;
  26413. },
  26414. parseShape: function ( json ) {
  26415. var shapes = {};
  26416. if ( json !== undefined ) {
  26417. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26418. var shape = new Shape().fromJSON( json[ i ] );
  26419. shapes[ shape.uuid ] = shape;
  26420. }
  26421. }
  26422. return shapes;
  26423. },
  26424. parseGeometries: function ( json, shapes ) {
  26425. var geometries = {};
  26426. if ( json !== undefined ) {
  26427. var geometryLoader = new JSONLoader();
  26428. var bufferGeometryLoader = new BufferGeometryLoader();
  26429. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26430. var geometry;
  26431. var data = json[ i ];
  26432. switch ( data.type ) {
  26433. case 'PlaneGeometry':
  26434. case 'PlaneBufferGeometry':
  26435. geometry = new Geometries[ data.type ](
  26436. data.width,
  26437. data.height,
  26438. data.widthSegments,
  26439. data.heightSegments
  26440. );
  26441. break;
  26442. case 'BoxGeometry':
  26443. case 'BoxBufferGeometry':
  26444. case 'CubeGeometry': // backwards compatible
  26445. geometry = new Geometries[ data.type ](
  26446. data.width,
  26447. data.height,
  26448. data.depth,
  26449. data.widthSegments,
  26450. data.heightSegments,
  26451. data.depthSegments
  26452. );
  26453. break;
  26454. case 'CircleGeometry':
  26455. case 'CircleBufferGeometry':
  26456. geometry = new Geometries[ data.type ](
  26457. data.radius,
  26458. data.segments,
  26459. data.thetaStart,
  26460. data.thetaLength
  26461. );
  26462. break;
  26463. case 'CylinderGeometry':
  26464. case 'CylinderBufferGeometry':
  26465. geometry = new Geometries[ data.type ](
  26466. data.radiusTop,
  26467. data.radiusBottom,
  26468. data.height,
  26469. data.radialSegments,
  26470. data.heightSegments,
  26471. data.openEnded,
  26472. data.thetaStart,
  26473. data.thetaLength
  26474. );
  26475. break;
  26476. case 'ConeGeometry':
  26477. case 'ConeBufferGeometry':
  26478. geometry = new Geometries[ data.type ](
  26479. data.radius,
  26480. data.height,
  26481. data.radialSegments,
  26482. data.heightSegments,
  26483. data.openEnded,
  26484. data.thetaStart,
  26485. data.thetaLength
  26486. );
  26487. break;
  26488. case 'SphereGeometry':
  26489. case 'SphereBufferGeometry':
  26490. geometry = new Geometries[ data.type ](
  26491. data.radius,
  26492. data.widthSegments,
  26493. data.heightSegments,
  26494. data.phiStart,
  26495. data.phiLength,
  26496. data.thetaStart,
  26497. data.thetaLength
  26498. );
  26499. break;
  26500. case 'DodecahedronGeometry':
  26501. case 'DodecahedronBufferGeometry':
  26502. case 'IcosahedronGeometry':
  26503. case 'IcosahedronBufferGeometry':
  26504. case 'OctahedronGeometry':
  26505. case 'OctahedronBufferGeometry':
  26506. case 'TetrahedronGeometry':
  26507. case 'TetrahedronBufferGeometry':
  26508. geometry = new Geometries[ data.type ](
  26509. data.radius,
  26510. data.detail
  26511. );
  26512. break;
  26513. case 'RingGeometry':
  26514. case 'RingBufferGeometry':
  26515. geometry = new Geometries[ data.type ](
  26516. data.innerRadius,
  26517. data.outerRadius,
  26518. data.thetaSegments,
  26519. data.phiSegments,
  26520. data.thetaStart,
  26521. data.thetaLength
  26522. );
  26523. break;
  26524. case 'TorusGeometry':
  26525. case 'TorusBufferGeometry':
  26526. geometry = new Geometries[ data.type ](
  26527. data.radius,
  26528. data.tube,
  26529. data.radialSegments,
  26530. data.tubularSegments,
  26531. data.arc
  26532. );
  26533. break;
  26534. case 'TorusKnotGeometry':
  26535. case 'TorusKnotBufferGeometry':
  26536. geometry = new Geometries[ data.type ](
  26537. data.radius,
  26538. data.tube,
  26539. data.tubularSegments,
  26540. data.radialSegments,
  26541. data.p,
  26542. data.q
  26543. );
  26544. break;
  26545. case 'LatheGeometry':
  26546. case 'LatheBufferGeometry':
  26547. geometry = new Geometries[ data.type ](
  26548. data.points,
  26549. data.segments,
  26550. data.phiStart,
  26551. data.phiLength
  26552. );
  26553. break;
  26554. case 'PolyhedronGeometry':
  26555. case 'PolyhedronBufferGeometry':
  26556. geometry = new Geometries[ data.type ](
  26557. data.vertices,
  26558. data.indices,
  26559. data.radius,
  26560. data.details
  26561. );
  26562. break;
  26563. case 'ShapeGeometry':
  26564. case 'ShapeBufferGeometry':
  26565. var geometryShapes = [];
  26566. for ( var i = 0, l = data.shapes.length; i < l; i ++ ) {
  26567. var shape = shapes[ data.shapes[ i ] ];
  26568. geometryShapes.push( shape );
  26569. }
  26570. geometry = new Geometries[ data.type ](
  26571. geometryShapes,
  26572. data.curveSegments
  26573. );
  26574. break;
  26575. case 'BufferGeometry':
  26576. geometry = bufferGeometryLoader.parse( data );
  26577. break;
  26578. case 'Geometry':
  26579. geometry = geometryLoader.parse( data, this.texturePath ).geometry;
  26580. break;
  26581. default:
  26582. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  26583. continue;
  26584. }
  26585. geometry.uuid = data.uuid;
  26586. if ( data.name !== undefined ) geometry.name = data.name;
  26587. geometries[ data.uuid ] = geometry;
  26588. }
  26589. }
  26590. return geometries;
  26591. },
  26592. parseMaterials: function ( json, textures ) {
  26593. var materials = {};
  26594. if ( json !== undefined ) {
  26595. var loader = new MaterialLoader();
  26596. loader.setTextures( textures );
  26597. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26598. var data = json[ i ];
  26599. if ( data.type === 'MultiMaterial' ) {
  26600. // Deprecated
  26601. var array = [];
  26602. for ( var j = 0; j < data.materials.length; j ++ ) {
  26603. array.push( loader.parse( data.materials[ j ] ) );
  26604. }
  26605. materials[ data.uuid ] = array;
  26606. } else {
  26607. materials[ data.uuid ] = loader.parse( data );
  26608. }
  26609. }
  26610. }
  26611. return materials;
  26612. },
  26613. parseAnimations: function ( json ) {
  26614. var animations = [];
  26615. for ( var i = 0; i < json.length; i ++ ) {
  26616. var clip = AnimationClip.parse( json[ i ] );
  26617. animations.push( clip );
  26618. }
  26619. return animations;
  26620. },
  26621. parseImages: function ( json, onLoad ) {
  26622. var scope = this;
  26623. var images = {};
  26624. function loadImage( url ) {
  26625. scope.manager.itemStart( url );
  26626. return loader.load( url, function () {
  26627. scope.manager.itemEnd( url );
  26628. }, undefined, function () {
  26629. scope.manager.itemEnd( url );
  26630. scope.manager.itemError( url );
  26631. } );
  26632. }
  26633. if ( json !== undefined && json.length > 0 ) {
  26634. var manager = new LoadingManager( onLoad );
  26635. var loader = new ImageLoader( manager );
  26636. loader.setCrossOrigin( this.crossOrigin );
  26637. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26638. var image = json[ i ];
  26639. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  26640. images[ image.uuid ] = loadImage( path );
  26641. }
  26642. }
  26643. return images;
  26644. },
  26645. parseTextures: function ( json, images ) {
  26646. function parseConstant( value, type ) {
  26647. if ( typeof value === 'number' ) return value;
  26648. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  26649. return type[ value ];
  26650. }
  26651. var textures = {};
  26652. if ( json !== undefined ) {
  26653. for ( var i = 0, l = json.length; i < l; i ++ ) {
  26654. var data = json[ i ];
  26655. if ( data.image === undefined ) {
  26656. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  26657. }
  26658. if ( images[ data.image ] === undefined ) {
  26659. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  26660. }
  26661. var texture = new Texture( images[ data.image ] );
  26662. texture.needsUpdate = true;
  26663. texture.uuid = data.uuid;
  26664. if ( data.name !== undefined ) texture.name = data.name;
  26665. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TEXTURE_MAPPING );
  26666. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  26667. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  26668. if ( data.center !== undefined ) texture.center.fromArray( data.center );
  26669. if ( data.rotation !== undefined ) texture.rotation = data.rotation;
  26670. if ( data.wrap !== undefined ) {
  26671. texture.wrapS = parseConstant( data.wrap[ 0 ], TEXTURE_WRAPPING );
  26672. texture.wrapT = parseConstant( data.wrap[ 1 ], TEXTURE_WRAPPING );
  26673. }
  26674. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TEXTURE_FILTER );
  26675. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TEXTURE_FILTER );
  26676. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  26677. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  26678. textures[ data.uuid ] = texture;
  26679. }
  26680. }
  26681. return textures;
  26682. },
  26683. parseObject: function () {
  26684. var matrix = new Matrix4();
  26685. return function parseObject( data, geometries, materials ) {
  26686. var object;
  26687. function getGeometry( name ) {
  26688. if ( geometries[ name ] === undefined ) {
  26689. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  26690. }
  26691. return geometries[ name ];
  26692. }
  26693. function getMaterial( name ) {
  26694. if ( name === undefined ) return undefined;
  26695. if ( Array.isArray( name ) ) {
  26696. var array = [];
  26697. for ( var i = 0, l = name.length; i < l; i ++ ) {
  26698. var uuid = name[ i ];
  26699. if ( materials[ uuid ] === undefined ) {
  26700. console.warn( 'THREE.ObjectLoader: Undefined material', uuid );
  26701. }
  26702. array.push( materials[ uuid ] );
  26703. }
  26704. return array;
  26705. }
  26706. if ( materials[ name ] === undefined ) {
  26707. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  26708. }
  26709. return materials[ name ];
  26710. }
  26711. switch ( data.type ) {
  26712. case 'Scene':
  26713. object = new Scene();
  26714. if ( data.background !== undefined ) {
  26715. if ( Number.isInteger( data.background ) ) {
  26716. object.background = new Color( data.background );
  26717. }
  26718. }
  26719. if ( data.fog !== undefined ) {
  26720. if ( data.fog.type === 'Fog' ) {
  26721. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  26722. } else if ( data.fog.type === 'FogExp2' ) {
  26723. object.fog = new FogExp2( data.fog.color, data.fog.density );
  26724. }
  26725. }
  26726. break;
  26727. case 'PerspectiveCamera':
  26728. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  26729. if ( data.focus !== undefined ) object.focus = data.focus;
  26730. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  26731. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  26732. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  26733. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  26734. break;
  26735. case 'OrthographicCamera':
  26736. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  26737. break;
  26738. case 'AmbientLight':
  26739. object = new AmbientLight( data.color, data.intensity );
  26740. break;
  26741. case 'DirectionalLight':
  26742. object = new DirectionalLight( data.color, data.intensity );
  26743. break;
  26744. case 'PointLight':
  26745. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  26746. break;
  26747. case 'RectAreaLight':
  26748. object = new RectAreaLight( data.color, data.intensity, data.width, data.height );
  26749. break;
  26750. case 'SpotLight':
  26751. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  26752. break;
  26753. case 'HemisphereLight':
  26754. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  26755. break;
  26756. case 'SkinnedMesh':
  26757. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh yet.' );
  26758. case 'Mesh':
  26759. var geometry = getGeometry( data.geometry );
  26760. var material = getMaterial( data.material );
  26761. if ( geometry.bones && geometry.bones.length > 0 ) {
  26762. object = new SkinnedMesh( geometry, material );
  26763. } else {
  26764. object = new Mesh( geometry, material );
  26765. }
  26766. break;
  26767. case 'LOD':
  26768. object = new LOD();
  26769. break;
  26770. case 'Line':
  26771. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  26772. break;
  26773. case 'LineLoop':
  26774. object = new LineLoop( getGeometry( data.geometry ), getMaterial( data.material ) );
  26775. break;
  26776. case 'LineSegments':
  26777. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  26778. break;
  26779. case 'PointCloud':
  26780. case 'Points':
  26781. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  26782. break;
  26783. case 'Sprite':
  26784. object = new Sprite( getMaterial( data.material ) );
  26785. break;
  26786. case 'Group':
  26787. object = new Group();
  26788. break;
  26789. default:
  26790. object = new Object3D();
  26791. }
  26792. object.uuid = data.uuid;
  26793. if ( data.name !== undefined ) object.name = data.name;
  26794. if ( data.matrix !== undefined ) {
  26795. matrix.fromArray( data.matrix );
  26796. matrix.decompose( object.position, object.quaternion, object.scale );
  26797. } else {
  26798. if ( data.position !== undefined ) object.position.fromArray( data.position );
  26799. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  26800. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  26801. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  26802. }
  26803. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  26804. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  26805. if ( data.shadow ) {
  26806. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  26807. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  26808. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  26809. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  26810. }
  26811. if ( data.visible !== undefined ) object.visible = data.visible;
  26812. if ( data.userData !== undefined ) object.userData = data.userData;
  26813. if ( data.children !== undefined ) {
  26814. var children = data.children;
  26815. for ( var i = 0; i < children.length; i ++ ) {
  26816. object.add( this.parseObject( children[ i ], geometries, materials ) );
  26817. }
  26818. }
  26819. if ( data.type === 'LOD' ) {
  26820. var levels = data.levels;
  26821. for ( var l = 0; l < levels.length; l ++ ) {
  26822. var level = levels[ l ];
  26823. var child = object.getObjectByProperty( 'uuid', level.object );
  26824. if ( child !== undefined ) {
  26825. object.addLevel( child, level.distance );
  26826. }
  26827. }
  26828. }
  26829. return object;
  26830. };
  26831. }()
  26832. } );
  26833. var TEXTURE_MAPPING = {
  26834. UVMapping: UVMapping,
  26835. CubeReflectionMapping: CubeReflectionMapping,
  26836. CubeRefractionMapping: CubeRefractionMapping,
  26837. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  26838. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  26839. SphericalReflectionMapping: SphericalReflectionMapping,
  26840. CubeUVReflectionMapping: CubeUVReflectionMapping,
  26841. CubeUVRefractionMapping: CubeUVRefractionMapping
  26842. };
  26843. var TEXTURE_WRAPPING = {
  26844. RepeatWrapping: RepeatWrapping,
  26845. ClampToEdgeWrapping: ClampToEdgeWrapping,
  26846. MirroredRepeatWrapping: MirroredRepeatWrapping
  26847. };
  26848. var TEXTURE_FILTER = {
  26849. NearestFilter: NearestFilter,
  26850. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  26851. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  26852. LinearFilter: LinearFilter,
  26853. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  26854. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  26855. };
  26856. /**
  26857. * @author thespite / http://clicktorelease.com/
  26858. */
  26859. function ImageBitmapLoader( manager ) {
  26860. if ( typeof createImageBitmap === 'undefined' ) {
  26861. console.warn( 'THREE.ImageBitmapLoader: createImageBitmap() not supported.' );
  26862. }
  26863. if ( typeof fetch === 'undefined' ) {
  26864. console.warn( 'THREE.ImageBitmapLoader: fetch() not supported.' );
  26865. }
  26866. this.manager = manager !== undefined ? manager : DefaultLoadingManager;
  26867. this.options = undefined;
  26868. }
  26869. ImageBitmapLoader.prototype = {
  26870. constructor: ImageBitmapLoader,
  26871. setOptions: function setOptions( options ) {
  26872. this.options = options;
  26873. return this;
  26874. },
  26875. load: function load( url, onLoad, onProgress, onError ) {
  26876. if ( url === undefined ) url = '';
  26877. if ( this.path !== undefined ) url = this.path + url;
  26878. var scope = this;
  26879. var cached = Cache.get( url );
  26880. if ( cached !== undefined ) {
  26881. scope.manager.itemStart( url );
  26882. setTimeout( function () {
  26883. if ( onLoad ) onLoad( cached );
  26884. scope.manager.itemEnd( url );
  26885. }, 0 );
  26886. return cached;
  26887. }
  26888. fetch( url ).then( function ( res ) {
  26889. return res.blob();
  26890. } ).then( function ( blob ) {
  26891. return createImageBitmap( blob, scope.options );
  26892. } ).then( function ( imageBitmap ) {
  26893. Cache.add( url, imageBitmap );
  26894. if ( onLoad ) onLoad( imageBitmap );
  26895. scope.manager.itemEnd( url );
  26896. } ).catch( function ( e ) {
  26897. if ( onError ) onError( e );
  26898. scope.manager.itemEnd( url );
  26899. scope.manager.itemError( url );
  26900. } );
  26901. },
  26902. setCrossOrigin: function ( /* value */ ) {
  26903. return this;
  26904. },
  26905. setPath: function ( value ) {
  26906. this.path = value;
  26907. return this;
  26908. }
  26909. };
  26910. /**
  26911. * @author zz85 / http://www.lab4games.net/zz85/blog
  26912. * minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  26913. **/
  26914. function ShapePath() {
  26915. this.type = 'ShapePath';
  26916. this.subPaths = [];
  26917. this.currentPath = null;
  26918. }
  26919. Object.assign( ShapePath.prototype, {
  26920. moveTo: function ( x, y ) {
  26921. this.currentPath = new Path();
  26922. this.subPaths.push( this.currentPath );
  26923. this.currentPath.moveTo( x, y );
  26924. },
  26925. lineTo: function ( x, y ) {
  26926. this.currentPath.lineTo( x, y );
  26927. },
  26928. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  26929. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  26930. },
  26931. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  26932. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  26933. },
  26934. splineThru: function ( pts ) {
  26935. this.currentPath.splineThru( pts );
  26936. },
  26937. toShapes: function ( isCCW, noHoles ) {
  26938. function toShapesNoHoles( inSubpaths ) {
  26939. var shapes = [];
  26940. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  26941. var tmpPath = inSubpaths[ i ];
  26942. var tmpShape = new Shape();
  26943. tmpShape.curves = tmpPath.curves;
  26944. shapes.push( tmpShape );
  26945. }
  26946. return shapes;
  26947. }
  26948. function isPointInsidePolygon( inPt, inPolygon ) {
  26949. var polyLen = inPolygon.length;
  26950. // inPt on polygon contour => immediate success or
  26951. // toggling of inside/outside at every single! intersection point of an edge
  26952. // with the horizontal line through inPt, left of inPt
  26953. // not counting lowerY endpoints of edges and whole edges on that line
  26954. var inside = false;
  26955. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  26956. var edgeLowPt = inPolygon[ p ];
  26957. var edgeHighPt = inPolygon[ q ];
  26958. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  26959. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  26960. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  26961. // not parallel
  26962. if ( edgeDy < 0 ) {
  26963. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  26964. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  26965. }
  26966. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  26967. if ( inPt.y === edgeLowPt.y ) {
  26968. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  26969. // continue; // no intersection or edgeLowPt => doesn't count !!!
  26970. } else {
  26971. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  26972. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  26973. if ( perpEdge < 0 ) continue;
  26974. inside = ! inside; // true intersection left of inPt
  26975. }
  26976. } else {
  26977. // parallel or collinear
  26978. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  26979. // edge lies on the same horizontal line as inPt
  26980. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  26981. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  26982. // continue;
  26983. }
  26984. }
  26985. return inside;
  26986. }
  26987. var isClockWise = ShapeUtils.isClockWise;
  26988. var subPaths = this.subPaths;
  26989. if ( subPaths.length === 0 ) return [];
  26990. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  26991. var solid, tmpPath, tmpShape, shapes = [];
  26992. if ( subPaths.length === 1 ) {
  26993. tmpPath = subPaths[ 0 ];
  26994. tmpShape = new Shape();
  26995. tmpShape.curves = tmpPath.curves;
  26996. shapes.push( tmpShape );
  26997. return shapes;
  26998. }
  26999. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  27000. holesFirst = isCCW ? ! holesFirst : holesFirst;
  27001. // console.log("Holes first", holesFirst);
  27002. var betterShapeHoles = [];
  27003. var newShapes = [];
  27004. var newShapeHoles = [];
  27005. var mainIdx = 0;
  27006. var tmpPoints;
  27007. newShapes[ mainIdx ] = undefined;
  27008. newShapeHoles[ mainIdx ] = [];
  27009. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  27010. tmpPath = subPaths[ i ];
  27011. tmpPoints = tmpPath.getPoints();
  27012. solid = isClockWise( tmpPoints );
  27013. solid = isCCW ? ! solid : solid;
  27014. if ( solid ) {
  27015. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  27016. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  27017. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  27018. if ( holesFirst ) mainIdx ++;
  27019. newShapeHoles[ mainIdx ] = [];
  27020. //console.log('cw', i);
  27021. } else {
  27022. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  27023. //console.log('ccw', i);
  27024. }
  27025. }
  27026. // only Holes? -> probably all Shapes with wrong orientation
  27027. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  27028. if ( newShapes.length > 1 ) {
  27029. var ambiguous = false;
  27030. var toChange = [];
  27031. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27032. betterShapeHoles[ sIdx ] = [];
  27033. }
  27034. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  27035. var sho = newShapeHoles[ sIdx ];
  27036. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  27037. var ho = sho[ hIdx ];
  27038. var hole_unassigned = true;
  27039. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  27040. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  27041. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  27042. if ( hole_unassigned ) {
  27043. hole_unassigned = false;
  27044. betterShapeHoles[ s2Idx ].push( ho );
  27045. } else {
  27046. ambiguous = true;
  27047. }
  27048. }
  27049. }
  27050. if ( hole_unassigned ) {
  27051. betterShapeHoles[ sIdx ].push( ho );
  27052. }
  27053. }
  27054. }
  27055. // console.log("ambiguous: ", ambiguous);
  27056. if ( toChange.length > 0 ) {
  27057. // console.log("to change: ", toChange);
  27058. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  27059. }
  27060. }
  27061. var tmpHoles;
  27062. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  27063. tmpShape = newShapes[ i ].s;
  27064. shapes.push( tmpShape );
  27065. tmpHoles = newShapeHoles[ i ];
  27066. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  27067. tmpShape.holes.push( tmpHoles[ j ].h );
  27068. }
  27069. }
  27070. //console.log("shape", shapes);
  27071. return shapes;
  27072. }
  27073. } );
  27074. /**
  27075. * @author zz85 / http://www.lab4games.net/zz85/blog
  27076. * @author mrdoob / http://mrdoob.com/
  27077. */
  27078. function Font( data ) {
  27079. this.type = 'Font';
  27080. this.data = data;
  27081. }
  27082. Object.assign( Font.prototype, {
  27083. isFont: true,
  27084. generateShapes: function ( text, size, divisions ) {
  27085. function createPaths( text ) {
  27086. var chars = String( text ).split( '' );
  27087. var scale = size / data.resolution;
  27088. var line_height = ( data.boundingBox.yMax - data.boundingBox.yMin + data.underlineThickness ) * scale;
  27089. var offsetX = 0, offsetY = 0;
  27090. var paths = [];
  27091. for ( var i = 0; i < chars.length; i ++ ) {
  27092. var char = chars[ i ];
  27093. if ( char === '\n' ) {
  27094. offsetX = 0;
  27095. offsetY -= line_height;
  27096. } else {
  27097. var ret = createPath( char, scale, offsetX, offsetY );
  27098. offsetX += ret.offsetX;
  27099. paths.push( ret.path );
  27100. }
  27101. }
  27102. return paths;
  27103. }
  27104. function createPath( c, scale, offsetX, offsetY ) {
  27105. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  27106. if ( ! glyph ) return;
  27107. var path = new ShapePath();
  27108. var pts = [];
  27109. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  27110. if ( glyph.o ) {
  27111. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  27112. for ( var i = 0, l = outline.length; i < l; ) {
  27113. var action = outline[ i ++ ];
  27114. switch ( action ) {
  27115. case 'm': // moveTo
  27116. x = outline[ i ++ ] * scale + offsetX;
  27117. y = outline[ i ++ ] * scale + offsetY;
  27118. path.moveTo( x, y );
  27119. break;
  27120. case 'l': // lineTo
  27121. x = outline[ i ++ ] * scale + offsetX;
  27122. y = outline[ i ++ ] * scale + offsetY;
  27123. path.lineTo( x, y );
  27124. break;
  27125. case 'q': // quadraticCurveTo
  27126. cpx = outline[ i ++ ] * scale + offsetX;
  27127. cpy = outline[ i ++ ] * scale + offsetY;
  27128. cpx1 = outline[ i ++ ] * scale + offsetX;
  27129. cpy1 = outline[ i ++ ] * scale + offsetY;
  27130. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  27131. laste = pts[ pts.length - 1 ];
  27132. if ( laste ) {
  27133. cpx0 = laste.x;
  27134. cpy0 = laste.y;
  27135. }
  27136. break;
  27137. case 'b': // bezierCurveTo
  27138. cpx = outline[ i ++ ] * scale + offsetX;
  27139. cpy = outline[ i ++ ] * scale + offsetY;
  27140. cpx1 = outline[ i ++ ] * scale + offsetX;
  27141. cpy1 = outline[ i ++ ] * scale + offsetY;
  27142. cpx2 = outline[ i ++ ] * scale + offsetX;
  27143. cpy2 = outline[ i ++ ] * scale + offsetY;
  27144. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  27145. laste = pts[ pts.length - 1 ];
  27146. if ( laste ) {
  27147. cpx0 = laste.x;
  27148. cpy0 = laste.y;
  27149. }
  27150. break;
  27151. }
  27152. }
  27153. }
  27154. return { offsetX: glyph.ha * scale, path: path };
  27155. }
  27156. //
  27157. if ( size === undefined ) size = 100;
  27158. if ( divisions === undefined ) divisions = 4;
  27159. var data = this.data;
  27160. var paths = createPaths( text );
  27161. var shapes = [];
  27162. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  27163. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  27164. }
  27165. return shapes;
  27166. }
  27167. } );
  27168. /**
  27169. * @author mrdoob / http://mrdoob.com/
  27170. */
  27171. function FontLoader( manager ) {
  27172. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27173. }
  27174. Object.assign( FontLoader.prototype, {
  27175. load: function ( url, onLoad, onProgress, onError ) {
  27176. var scope = this;
  27177. var loader = new FileLoader( this.manager );
  27178. loader.setPath( this.path );
  27179. loader.load( url, function ( text ) {
  27180. var json;
  27181. try {
  27182. json = JSON.parse( text );
  27183. } catch ( e ) {
  27184. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  27185. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  27186. }
  27187. var font = scope.parse( json );
  27188. if ( onLoad ) onLoad( font );
  27189. }, onProgress, onError );
  27190. },
  27191. parse: function ( json ) {
  27192. return new Font( json );
  27193. },
  27194. setPath: function ( value ) {
  27195. this.path = value;
  27196. return this;
  27197. }
  27198. } );
  27199. /**
  27200. * @author mrdoob / http://mrdoob.com/
  27201. */
  27202. var context;
  27203. var AudioContext = {
  27204. getContext: function () {
  27205. if ( context === undefined ) {
  27206. context = new ( window.AudioContext || window.webkitAudioContext )();
  27207. }
  27208. return context;
  27209. },
  27210. setContext: function ( value ) {
  27211. context = value;
  27212. }
  27213. };
  27214. /**
  27215. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27216. */
  27217. function AudioLoader( manager ) {
  27218. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  27219. }
  27220. Object.assign( AudioLoader.prototype, {
  27221. load: function ( url, onLoad, onProgress, onError ) {
  27222. var loader = new FileLoader( this.manager );
  27223. loader.setResponseType( 'arraybuffer' );
  27224. loader.load( url, function ( buffer ) {
  27225. var context = AudioContext.getContext();
  27226. context.decodeAudioData( buffer, function ( audioBuffer ) {
  27227. onLoad( audioBuffer );
  27228. } );
  27229. }, onProgress, onError );
  27230. }
  27231. } );
  27232. /**
  27233. * @author mrdoob / http://mrdoob.com/
  27234. */
  27235. function StereoCamera() {
  27236. this.type = 'StereoCamera';
  27237. this.aspect = 1;
  27238. this.eyeSep = 0.064;
  27239. this.cameraL = new PerspectiveCamera();
  27240. this.cameraL.layers.enable( 1 );
  27241. this.cameraL.matrixAutoUpdate = false;
  27242. this.cameraR = new PerspectiveCamera();
  27243. this.cameraR.layers.enable( 2 );
  27244. this.cameraR.matrixAutoUpdate = false;
  27245. }
  27246. Object.assign( StereoCamera.prototype, {
  27247. update: ( function () {
  27248. var instance, focus, fov, aspect, near, far, zoom, eyeSep;
  27249. var eyeRight = new Matrix4();
  27250. var eyeLeft = new Matrix4();
  27251. return function update( camera ) {
  27252. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  27253. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  27254. far !== camera.far || zoom !== camera.zoom || eyeSep !== this.eyeSep;
  27255. if ( needsUpdate ) {
  27256. instance = this;
  27257. focus = camera.focus;
  27258. fov = camera.fov;
  27259. aspect = camera.aspect * this.aspect;
  27260. near = camera.near;
  27261. far = camera.far;
  27262. zoom = camera.zoom;
  27263. // Off-axis stereoscopic effect based on
  27264. // http://paulbourke.net/stereographics/stereorender/
  27265. var projectionMatrix = camera.projectionMatrix.clone();
  27266. eyeSep = this.eyeSep / 2;
  27267. var eyeSepOnProjection = eyeSep * near / focus;
  27268. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  27269. var xmin, xmax;
  27270. // translate xOffset
  27271. eyeLeft.elements[ 12 ] = - eyeSep;
  27272. eyeRight.elements[ 12 ] = eyeSep;
  27273. // for left eye
  27274. xmin = - ymax * aspect + eyeSepOnProjection;
  27275. xmax = ymax * aspect + eyeSepOnProjection;
  27276. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27277. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27278. this.cameraL.projectionMatrix.copy( projectionMatrix );
  27279. // for right eye
  27280. xmin = - ymax * aspect - eyeSepOnProjection;
  27281. xmax = ymax * aspect - eyeSepOnProjection;
  27282. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  27283. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  27284. this.cameraR.projectionMatrix.copy( projectionMatrix );
  27285. }
  27286. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  27287. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  27288. };
  27289. } )()
  27290. } );
  27291. /**
  27292. * Camera for rendering cube maps
  27293. * - renders scene into axis-aligned cube
  27294. *
  27295. * @author alteredq / http://alteredqualia.com/
  27296. */
  27297. function CubeCamera( near, far, cubeResolution ) {
  27298. Object3D.call( this );
  27299. this.type = 'CubeCamera';
  27300. var fov = 90, aspect = 1;
  27301. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  27302. cameraPX.up.set( 0, - 1, 0 );
  27303. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  27304. this.add( cameraPX );
  27305. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  27306. cameraNX.up.set( 0, - 1, 0 );
  27307. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  27308. this.add( cameraNX );
  27309. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  27310. cameraPY.up.set( 0, 0, 1 );
  27311. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  27312. this.add( cameraPY );
  27313. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  27314. cameraNY.up.set( 0, 0, - 1 );
  27315. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  27316. this.add( cameraNY );
  27317. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  27318. cameraPZ.up.set( 0, - 1, 0 );
  27319. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  27320. this.add( cameraPZ );
  27321. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  27322. cameraNZ.up.set( 0, - 1, 0 );
  27323. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  27324. this.add( cameraNZ );
  27325. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  27326. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  27327. this.renderTarget.texture.name = "CubeCamera";
  27328. this.update = function ( renderer, scene ) {
  27329. if ( this.parent === null ) this.updateMatrixWorld();
  27330. var renderTarget = this.renderTarget;
  27331. var generateMipmaps = renderTarget.texture.generateMipmaps;
  27332. renderTarget.texture.generateMipmaps = false;
  27333. renderTarget.activeCubeFace = 0;
  27334. renderer.render( scene, cameraPX, renderTarget );
  27335. renderTarget.activeCubeFace = 1;
  27336. renderer.render( scene, cameraNX, renderTarget );
  27337. renderTarget.activeCubeFace = 2;
  27338. renderer.render( scene, cameraPY, renderTarget );
  27339. renderTarget.activeCubeFace = 3;
  27340. renderer.render( scene, cameraNY, renderTarget );
  27341. renderTarget.activeCubeFace = 4;
  27342. renderer.render( scene, cameraPZ, renderTarget );
  27343. renderTarget.texture.generateMipmaps = generateMipmaps;
  27344. renderTarget.activeCubeFace = 5;
  27345. renderer.render( scene, cameraNZ, renderTarget );
  27346. renderer.setRenderTarget( null );
  27347. };
  27348. this.clear = function ( renderer, color, depth, stencil ) {
  27349. var renderTarget = this.renderTarget;
  27350. for ( var i = 0; i < 6; i ++ ) {
  27351. renderTarget.activeCubeFace = i;
  27352. renderer.setRenderTarget( renderTarget );
  27353. renderer.clear( color, depth, stencil );
  27354. }
  27355. renderer.setRenderTarget( null );
  27356. };
  27357. }
  27358. CubeCamera.prototype = Object.create( Object3D.prototype );
  27359. CubeCamera.prototype.constructor = CubeCamera;
  27360. /**
  27361. * @author mrdoob / http://mrdoob.com/
  27362. */
  27363. function AudioListener() {
  27364. Object3D.call( this );
  27365. this.type = 'AudioListener';
  27366. this.context = AudioContext.getContext();
  27367. this.gain = this.context.createGain();
  27368. this.gain.connect( this.context.destination );
  27369. this.filter = null;
  27370. }
  27371. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27372. constructor: AudioListener,
  27373. getInput: function () {
  27374. return this.gain;
  27375. },
  27376. removeFilter: function ( ) {
  27377. if ( this.filter !== null ) {
  27378. this.gain.disconnect( this.filter );
  27379. this.filter.disconnect( this.context.destination );
  27380. this.gain.connect( this.context.destination );
  27381. this.filter = null;
  27382. }
  27383. },
  27384. getFilter: function () {
  27385. return this.filter;
  27386. },
  27387. setFilter: function ( value ) {
  27388. if ( this.filter !== null ) {
  27389. this.gain.disconnect( this.filter );
  27390. this.filter.disconnect( this.context.destination );
  27391. } else {
  27392. this.gain.disconnect( this.context.destination );
  27393. }
  27394. this.filter = value;
  27395. this.gain.connect( this.filter );
  27396. this.filter.connect( this.context.destination );
  27397. },
  27398. getMasterVolume: function () {
  27399. return this.gain.gain.value;
  27400. },
  27401. setMasterVolume: function ( value ) {
  27402. this.gain.gain.value = value;
  27403. },
  27404. updateMatrixWorld: ( function () {
  27405. var position = new Vector3();
  27406. var quaternion = new Quaternion();
  27407. var scale = new Vector3();
  27408. var orientation = new Vector3();
  27409. return function updateMatrixWorld( force ) {
  27410. Object3D.prototype.updateMatrixWorld.call( this, force );
  27411. var listener = this.context.listener;
  27412. var up = this.up;
  27413. this.matrixWorld.decompose( position, quaternion, scale );
  27414. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  27415. if ( listener.positionX ) {
  27416. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  27417. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  27418. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  27419. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  27420. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  27421. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  27422. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  27423. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  27424. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  27425. } else {
  27426. listener.setPosition( position.x, position.y, position.z );
  27427. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  27428. }
  27429. };
  27430. } )()
  27431. } );
  27432. /**
  27433. * @author mrdoob / http://mrdoob.com/
  27434. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  27435. */
  27436. function Audio( listener ) {
  27437. Object3D.call( this );
  27438. this.type = 'Audio';
  27439. this.context = listener.context;
  27440. this.gain = this.context.createGain();
  27441. this.gain.connect( listener.getInput() );
  27442. this.autoplay = false;
  27443. this.buffer = null;
  27444. this.loop = false;
  27445. this.startTime = 0;
  27446. this.offset = 0;
  27447. this.playbackRate = 1;
  27448. this.isPlaying = false;
  27449. this.hasPlaybackControl = true;
  27450. this.sourceType = 'empty';
  27451. this.filters = [];
  27452. }
  27453. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  27454. constructor: Audio,
  27455. getOutput: function () {
  27456. return this.gain;
  27457. },
  27458. setNodeSource: function ( audioNode ) {
  27459. this.hasPlaybackControl = false;
  27460. this.sourceType = 'audioNode';
  27461. this.source = audioNode;
  27462. this.connect();
  27463. return this;
  27464. },
  27465. setBuffer: function ( audioBuffer ) {
  27466. this.buffer = audioBuffer;
  27467. this.sourceType = 'buffer';
  27468. if ( this.autoplay ) this.play();
  27469. return this;
  27470. },
  27471. play: function () {
  27472. if ( this.isPlaying === true ) {
  27473. console.warn( 'THREE.Audio: Audio is already playing.' );
  27474. return;
  27475. }
  27476. if ( this.hasPlaybackControl === false ) {
  27477. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27478. return;
  27479. }
  27480. var source = this.context.createBufferSource();
  27481. source.buffer = this.buffer;
  27482. source.loop = this.loop;
  27483. source.onended = this.onEnded.bind( this );
  27484. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  27485. this.startTime = this.context.currentTime;
  27486. source.start( this.startTime, this.offset );
  27487. this.isPlaying = true;
  27488. this.source = source;
  27489. return this.connect();
  27490. },
  27491. pause: function () {
  27492. if ( this.hasPlaybackControl === false ) {
  27493. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27494. return;
  27495. }
  27496. if ( this.isPlaying === true ) {
  27497. this.source.stop();
  27498. this.offset += ( this.context.currentTime - this.startTime ) * this.playbackRate;
  27499. this.isPlaying = false;
  27500. }
  27501. return this;
  27502. },
  27503. stop: function () {
  27504. if ( this.hasPlaybackControl === false ) {
  27505. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27506. return;
  27507. }
  27508. this.source.stop();
  27509. this.offset = 0;
  27510. this.isPlaying = false;
  27511. return this;
  27512. },
  27513. connect: function () {
  27514. if ( this.filters.length > 0 ) {
  27515. this.source.connect( this.filters[ 0 ] );
  27516. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27517. this.filters[ i - 1 ].connect( this.filters[ i ] );
  27518. }
  27519. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  27520. } else {
  27521. this.source.connect( this.getOutput() );
  27522. }
  27523. return this;
  27524. },
  27525. disconnect: function () {
  27526. if ( this.filters.length > 0 ) {
  27527. this.source.disconnect( this.filters[ 0 ] );
  27528. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  27529. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  27530. }
  27531. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  27532. } else {
  27533. this.source.disconnect( this.getOutput() );
  27534. }
  27535. return this;
  27536. },
  27537. getFilters: function () {
  27538. return this.filters;
  27539. },
  27540. setFilters: function ( value ) {
  27541. if ( ! value ) value = [];
  27542. if ( this.isPlaying === true ) {
  27543. this.disconnect();
  27544. this.filters = value;
  27545. this.connect();
  27546. } else {
  27547. this.filters = value;
  27548. }
  27549. return this;
  27550. },
  27551. getFilter: function () {
  27552. return this.getFilters()[ 0 ];
  27553. },
  27554. setFilter: function ( filter ) {
  27555. return this.setFilters( filter ? [ filter ] : [] );
  27556. },
  27557. setPlaybackRate: function ( value ) {
  27558. if ( this.hasPlaybackControl === false ) {
  27559. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27560. return;
  27561. }
  27562. this.playbackRate = value;
  27563. if ( this.isPlaying === true ) {
  27564. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  27565. }
  27566. return this;
  27567. },
  27568. getPlaybackRate: function () {
  27569. return this.playbackRate;
  27570. },
  27571. onEnded: function () {
  27572. this.isPlaying = false;
  27573. },
  27574. getLoop: function () {
  27575. if ( this.hasPlaybackControl === false ) {
  27576. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27577. return false;
  27578. }
  27579. return this.loop;
  27580. },
  27581. setLoop: function ( value ) {
  27582. if ( this.hasPlaybackControl === false ) {
  27583. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  27584. return;
  27585. }
  27586. this.loop = value;
  27587. if ( this.isPlaying === true ) {
  27588. this.source.loop = this.loop;
  27589. }
  27590. return this;
  27591. },
  27592. getVolume: function () {
  27593. return this.gain.gain.value;
  27594. },
  27595. setVolume: function ( value ) {
  27596. this.gain.gain.value = value;
  27597. return this;
  27598. }
  27599. } );
  27600. /**
  27601. * @author mrdoob / http://mrdoob.com/
  27602. */
  27603. function PositionalAudio( listener ) {
  27604. Audio.call( this, listener );
  27605. this.panner = this.context.createPanner();
  27606. this.panner.connect( this.gain );
  27607. }
  27608. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  27609. constructor: PositionalAudio,
  27610. getOutput: function () {
  27611. return this.panner;
  27612. },
  27613. getRefDistance: function () {
  27614. return this.panner.refDistance;
  27615. },
  27616. setRefDistance: function ( value ) {
  27617. this.panner.refDistance = value;
  27618. },
  27619. getRolloffFactor: function () {
  27620. return this.panner.rolloffFactor;
  27621. },
  27622. setRolloffFactor: function ( value ) {
  27623. this.panner.rolloffFactor = value;
  27624. },
  27625. getDistanceModel: function () {
  27626. return this.panner.distanceModel;
  27627. },
  27628. setDistanceModel: function ( value ) {
  27629. this.panner.distanceModel = value;
  27630. },
  27631. getMaxDistance: function () {
  27632. return this.panner.maxDistance;
  27633. },
  27634. setMaxDistance: function ( value ) {
  27635. this.panner.maxDistance = value;
  27636. },
  27637. updateMatrixWorld: ( function () {
  27638. var position = new Vector3();
  27639. return function updateMatrixWorld( force ) {
  27640. Object3D.prototype.updateMatrixWorld.call( this, force );
  27641. position.setFromMatrixPosition( this.matrixWorld );
  27642. this.panner.setPosition( position.x, position.y, position.z );
  27643. };
  27644. } )()
  27645. } );
  27646. /**
  27647. * @author mrdoob / http://mrdoob.com/
  27648. */
  27649. function AudioAnalyser( audio, fftSize ) {
  27650. this.analyser = audio.context.createAnalyser();
  27651. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  27652. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  27653. audio.getOutput().connect( this.analyser );
  27654. }
  27655. Object.assign( AudioAnalyser.prototype, {
  27656. getFrequencyData: function () {
  27657. this.analyser.getByteFrequencyData( this.data );
  27658. return this.data;
  27659. },
  27660. getAverageFrequency: function () {
  27661. var value = 0, data = this.getFrequencyData();
  27662. for ( var i = 0; i < data.length; i ++ ) {
  27663. value += data[ i ];
  27664. }
  27665. return value / data.length;
  27666. }
  27667. } );
  27668. /**
  27669. *
  27670. * Buffered scene graph property that allows weighted accumulation.
  27671. *
  27672. *
  27673. * @author Ben Houston / http://clara.io/
  27674. * @author David Sarno / http://lighthaus.us/
  27675. * @author tschw
  27676. */
  27677. function PropertyMixer( binding, typeName, valueSize ) {
  27678. this.binding = binding;
  27679. this.valueSize = valueSize;
  27680. var bufferType = Float64Array,
  27681. mixFunction;
  27682. switch ( typeName ) {
  27683. case 'quaternion':
  27684. mixFunction = this._slerp;
  27685. break;
  27686. case 'string':
  27687. case 'bool':
  27688. bufferType = Array;
  27689. mixFunction = this._select;
  27690. break;
  27691. default:
  27692. mixFunction = this._lerp;
  27693. }
  27694. this.buffer = new bufferType( valueSize * 4 );
  27695. // layout: [ incoming | accu0 | accu1 | orig ]
  27696. //
  27697. // interpolators can use .buffer as their .result
  27698. // the data then goes to 'incoming'
  27699. //
  27700. // 'accu0' and 'accu1' are used frame-interleaved for
  27701. // the cumulative result and are compared to detect
  27702. // changes
  27703. //
  27704. // 'orig' stores the original state of the property
  27705. this._mixBufferRegion = mixFunction;
  27706. this.cumulativeWeight = 0;
  27707. this.useCount = 0;
  27708. this.referenceCount = 0;
  27709. }
  27710. Object.assign( PropertyMixer.prototype, {
  27711. // accumulate data in the 'incoming' region into 'accu<i>'
  27712. accumulate: function ( accuIndex, weight ) {
  27713. // note: happily accumulating nothing when weight = 0, the caller knows
  27714. // the weight and shouldn't have made the call in the first place
  27715. var buffer = this.buffer,
  27716. stride = this.valueSize,
  27717. offset = accuIndex * stride + stride,
  27718. currentWeight = this.cumulativeWeight;
  27719. if ( currentWeight === 0 ) {
  27720. // accuN := incoming * weight
  27721. for ( var i = 0; i !== stride; ++ i ) {
  27722. buffer[ offset + i ] = buffer[ i ];
  27723. }
  27724. currentWeight = weight;
  27725. } else {
  27726. // accuN := accuN + incoming * weight
  27727. currentWeight += weight;
  27728. var mix = weight / currentWeight;
  27729. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  27730. }
  27731. this.cumulativeWeight = currentWeight;
  27732. },
  27733. // apply the state of 'accu<i>' to the binding when accus differ
  27734. apply: function ( accuIndex ) {
  27735. var stride = this.valueSize,
  27736. buffer = this.buffer,
  27737. offset = accuIndex * stride + stride,
  27738. weight = this.cumulativeWeight,
  27739. binding = this.binding;
  27740. this.cumulativeWeight = 0;
  27741. if ( weight < 1 ) {
  27742. // accuN := accuN + original * ( 1 - cumulativeWeight )
  27743. var originalValueOffset = stride * 3;
  27744. this._mixBufferRegion(
  27745. buffer, offset, originalValueOffset, 1 - weight, stride );
  27746. }
  27747. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  27748. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  27749. // value has changed -> update scene graph
  27750. binding.setValue( buffer, offset );
  27751. break;
  27752. }
  27753. }
  27754. },
  27755. // remember the state of the bound property and copy it to both accus
  27756. saveOriginalState: function () {
  27757. var binding = this.binding;
  27758. var buffer = this.buffer,
  27759. stride = this.valueSize,
  27760. originalValueOffset = stride * 3;
  27761. binding.getValue( buffer, originalValueOffset );
  27762. // accu[0..1] := orig -- initially detect changes against the original
  27763. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  27764. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  27765. }
  27766. this.cumulativeWeight = 0;
  27767. },
  27768. // apply the state previously taken via 'saveOriginalState' to the binding
  27769. restoreOriginalState: function () {
  27770. var originalValueOffset = this.valueSize * 3;
  27771. this.binding.setValue( this.buffer, originalValueOffset );
  27772. },
  27773. // mix functions
  27774. _select: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27775. if ( t >= 0.5 ) {
  27776. for ( var i = 0; i !== stride; ++ i ) {
  27777. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  27778. }
  27779. }
  27780. },
  27781. _slerp: function ( buffer, dstOffset, srcOffset, t ) {
  27782. Quaternion.slerpFlat( buffer, dstOffset, buffer, dstOffset, buffer, srcOffset, t );
  27783. },
  27784. _lerp: function ( buffer, dstOffset, srcOffset, t, stride ) {
  27785. var s = 1 - t;
  27786. for ( var i = 0; i !== stride; ++ i ) {
  27787. var j = dstOffset + i;
  27788. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  27789. }
  27790. }
  27791. } );
  27792. /**
  27793. *
  27794. * A reference to a real property in the scene graph.
  27795. *
  27796. *
  27797. * @author Ben Houston / http://clara.io/
  27798. * @author David Sarno / http://lighthaus.us/
  27799. * @author tschw
  27800. */
  27801. function Composite( targetGroup, path, optionalParsedPath ) {
  27802. var parsedPath = optionalParsedPath || PropertyBinding.parseTrackName( path );
  27803. this._targetGroup = targetGroup;
  27804. this._bindings = targetGroup.subscribe_( path, parsedPath );
  27805. }
  27806. Object.assign( Composite.prototype, {
  27807. getValue: function ( array, offset ) {
  27808. this.bind(); // bind all binding
  27809. var firstValidIndex = this._targetGroup.nCachedObjects_,
  27810. binding = this._bindings[ firstValidIndex ];
  27811. // and only call .getValue on the first
  27812. if ( binding !== undefined ) binding.getValue( array, offset );
  27813. },
  27814. setValue: function ( array, offset ) {
  27815. var bindings = this._bindings;
  27816. for ( var i = this._targetGroup.nCachedObjects_,
  27817. n = bindings.length; i !== n; ++ i ) {
  27818. bindings[ i ].setValue( array, offset );
  27819. }
  27820. },
  27821. bind: function () {
  27822. var bindings = this._bindings;
  27823. for ( var i = this._targetGroup.nCachedObjects_,
  27824. n = bindings.length; i !== n; ++ i ) {
  27825. bindings[ i ].bind();
  27826. }
  27827. },
  27828. unbind: function () {
  27829. var bindings = this._bindings;
  27830. for ( var i = this._targetGroup.nCachedObjects_,
  27831. n = bindings.length; i !== n; ++ i ) {
  27832. bindings[ i ].unbind();
  27833. }
  27834. }
  27835. } );
  27836. function PropertyBinding( rootNode, path, parsedPath ) {
  27837. this.path = path;
  27838. this.parsedPath = parsedPath || PropertyBinding.parseTrackName( path );
  27839. this.node = PropertyBinding.findNode( rootNode, this.parsedPath.nodeName ) || rootNode;
  27840. this.rootNode = rootNode;
  27841. }
  27842. Object.assign( PropertyBinding, {
  27843. Composite: Composite,
  27844. create: function ( root, path, parsedPath ) {
  27845. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  27846. return new PropertyBinding( root, path, parsedPath );
  27847. } else {
  27848. return new PropertyBinding.Composite( root, path, parsedPath );
  27849. }
  27850. },
  27851. /**
  27852. * Replaces spaces with underscores and removes unsupported characters from
  27853. * node names, to ensure compatibility with parseTrackName().
  27854. *
  27855. * @param {string} name Node name to be sanitized.
  27856. * @return {string}
  27857. */
  27858. sanitizeNodeName: function ( name ) {
  27859. return name.replace( /\s/g, '_' ).replace( /[^\w-]/g, '' );
  27860. },
  27861. parseTrackName: function () {
  27862. // Parent directories, delimited by '/' or ':'. Currently unused, but must
  27863. // be matched to parse the rest of the track name.
  27864. var directoryRe = /((?:[\w-]+[\/:])*)/;
  27865. // Target node. May contain word characters (a-zA-Z0-9_) and '.' or '-'.
  27866. var nodeRe = /([\w-\.]+)?/;
  27867. // Object on target node, and accessor. Name may contain only word
  27868. // characters. Accessor may contain any character except closing bracket.
  27869. var objectRe = /(?:\.([\w-]+)(?:\[(.+)\])?)?/;
  27870. // Property and accessor. May contain only word characters. Accessor may
  27871. // contain any non-bracket characters.
  27872. var propertyRe = /\.([\w-]+)(?:\[(.+)\])?/;
  27873. var trackRe = new RegExp( ''
  27874. + '^'
  27875. + directoryRe.source
  27876. + nodeRe.source
  27877. + objectRe.source
  27878. + propertyRe.source
  27879. + '$'
  27880. );
  27881. var supportedObjectNames = [ 'material', 'materials', 'bones' ];
  27882. return function ( trackName ) {
  27883. var matches = trackRe.exec( trackName );
  27884. if ( ! matches ) {
  27885. throw new Error( 'PropertyBinding: Cannot parse trackName: ' + trackName );
  27886. }
  27887. var results = {
  27888. // directoryName: matches[ 1 ], // (tschw) currently unused
  27889. nodeName: matches[ 2 ],
  27890. objectName: matches[ 3 ],
  27891. objectIndex: matches[ 4 ],
  27892. propertyName: matches[ 5 ], // required
  27893. propertyIndex: matches[ 6 ]
  27894. };
  27895. var lastDot = results.nodeName && results.nodeName.lastIndexOf( '.' );
  27896. if ( lastDot !== undefined && lastDot !== - 1 ) {
  27897. var objectName = results.nodeName.substring( lastDot + 1 );
  27898. // Object names must be checked against a whitelist. Otherwise, there
  27899. // is no way to parse 'foo.bar.baz': 'baz' must be a property, but
  27900. // 'bar' could be the objectName, or part of a nodeName (which can
  27901. // include '.' characters).
  27902. if ( supportedObjectNames.indexOf( objectName ) !== - 1 ) {
  27903. results.nodeName = results.nodeName.substring( 0, lastDot );
  27904. results.objectName = objectName;
  27905. }
  27906. }
  27907. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  27908. throw new Error( 'PropertyBinding: can not parse propertyName from trackName: ' + trackName );
  27909. }
  27910. return results;
  27911. };
  27912. }(),
  27913. findNode: function ( root, nodeName ) {
  27914. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === - 1 || nodeName === root.name || nodeName === root.uuid ) {
  27915. return root;
  27916. }
  27917. // search into skeleton bones.
  27918. if ( root.skeleton ) {
  27919. var searchSkeleton = function ( skeleton ) {
  27920. for ( var i = 0; i < skeleton.bones.length; i ++ ) {
  27921. var bone = skeleton.bones[ i ];
  27922. if ( bone.name === nodeName ) {
  27923. return bone;
  27924. }
  27925. }
  27926. return null;
  27927. };
  27928. var bone = searchSkeleton( root.skeleton );
  27929. if ( bone ) {
  27930. return bone;
  27931. }
  27932. }
  27933. // search into node subtree.
  27934. if ( root.children ) {
  27935. var searchNodeSubtree = function ( children ) {
  27936. for ( var i = 0; i < children.length; i ++ ) {
  27937. var childNode = children[ i ];
  27938. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  27939. return childNode;
  27940. }
  27941. var result = searchNodeSubtree( childNode.children );
  27942. if ( result ) return result;
  27943. }
  27944. return null;
  27945. };
  27946. var subTreeNode = searchNodeSubtree( root.children );
  27947. if ( subTreeNode ) {
  27948. return subTreeNode;
  27949. }
  27950. }
  27951. return null;
  27952. }
  27953. } );
  27954. Object.assign( PropertyBinding.prototype, { // prototype, continued
  27955. // these are used to "bind" a nonexistent property
  27956. _getValue_unavailable: function () {},
  27957. _setValue_unavailable: function () {},
  27958. BindingType: {
  27959. Direct: 0,
  27960. EntireArray: 1,
  27961. ArrayElement: 2,
  27962. HasFromToArray: 3
  27963. },
  27964. Versioning: {
  27965. None: 0,
  27966. NeedsUpdate: 1,
  27967. MatrixWorldNeedsUpdate: 2
  27968. },
  27969. GetterByBindingType: [
  27970. function getValue_direct( buffer, offset ) {
  27971. buffer[ offset ] = this.node[ this.propertyName ];
  27972. },
  27973. function getValue_array( buffer, offset ) {
  27974. var source = this.resolvedProperty;
  27975. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  27976. buffer[ offset ++ ] = source[ i ];
  27977. }
  27978. },
  27979. function getValue_arrayElement( buffer, offset ) {
  27980. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  27981. },
  27982. function getValue_toArray( buffer, offset ) {
  27983. this.resolvedProperty.toArray( buffer, offset );
  27984. }
  27985. ],
  27986. SetterByBindingTypeAndVersioning: [
  27987. [
  27988. // Direct
  27989. function setValue_direct( buffer, offset ) {
  27990. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27991. },
  27992. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  27993. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27994. this.targetObject.needsUpdate = true;
  27995. },
  27996. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  27997. this.targetObject[ this.propertyName ] = buffer[ offset ];
  27998. this.targetObject.matrixWorldNeedsUpdate = true;
  27999. }
  28000. ], [
  28001. // EntireArray
  28002. function setValue_array( 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. },
  28008. function setValue_array_setNeedsUpdate( buffer, offset ) {
  28009. var dest = this.resolvedProperty;
  28010. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28011. dest[ i ] = buffer[ offset ++ ];
  28012. }
  28013. this.targetObject.needsUpdate = true;
  28014. },
  28015. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28016. var dest = this.resolvedProperty;
  28017. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  28018. dest[ i ] = buffer[ offset ++ ];
  28019. }
  28020. this.targetObject.matrixWorldNeedsUpdate = true;
  28021. }
  28022. ], [
  28023. // ArrayElement
  28024. function setValue_arrayElement( buffer, offset ) {
  28025. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28026. },
  28027. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  28028. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28029. this.targetObject.needsUpdate = true;
  28030. },
  28031. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28032. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  28033. this.targetObject.matrixWorldNeedsUpdate = true;
  28034. }
  28035. ], [
  28036. // HasToFromArray
  28037. function setValue_fromArray( buffer, offset ) {
  28038. this.resolvedProperty.fromArray( buffer, offset );
  28039. },
  28040. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  28041. this.resolvedProperty.fromArray( buffer, offset );
  28042. this.targetObject.needsUpdate = true;
  28043. },
  28044. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  28045. this.resolvedProperty.fromArray( buffer, offset );
  28046. this.targetObject.matrixWorldNeedsUpdate = true;
  28047. }
  28048. ]
  28049. ],
  28050. getValue: function getValue_unbound( targetArray, offset ) {
  28051. this.bind();
  28052. this.getValue( targetArray, offset );
  28053. // Note: This class uses a State pattern on a per-method basis:
  28054. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  28055. // prototype version of these methods with one that represents
  28056. // the bound state. When the property is not found, the methods
  28057. // become no-ops.
  28058. },
  28059. setValue: function getValue_unbound( sourceArray, offset ) {
  28060. this.bind();
  28061. this.setValue( sourceArray, offset );
  28062. },
  28063. // create getter / setter pair for a property in the scene graph
  28064. bind: function () {
  28065. var targetObject = this.node,
  28066. parsedPath = this.parsedPath,
  28067. objectName = parsedPath.objectName,
  28068. propertyName = parsedPath.propertyName,
  28069. propertyIndex = parsedPath.propertyIndex;
  28070. if ( ! targetObject ) {
  28071. targetObject = PropertyBinding.findNode( this.rootNode, parsedPath.nodeName ) || this.rootNode;
  28072. this.node = targetObject;
  28073. }
  28074. // set fail state so we can just 'return' on error
  28075. this.getValue = this._getValue_unavailable;
  28076. this.setValue = this._setValue_unavailable;
  28077. // ensure there is a value node
  28078. if ( ! targetObject ) {
  28079. console.error( 'THREE.PropertyBinding: Trying to update node for track: ' + this.path + ' but it wasn\'t found.' );
  28080. return;
  28081. }
  28082. if ( objectName ) {
  28083. var objectIndex = parsedPath.objectIndex;
  28084. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  28085. switch ( objectName ) {
  28086. case 'materials':
  28087. if ( ! targetObject.material ) {
  28088. console.error( 'THREE.PropertyBinding: Can not bind to material as node does not have a material.', this );
  28089. return;
  28090. }
  28091. if ( ! targetObject.material.materials ) {
  28092. console.error( 'THREE.PropertyBinding: Can not bind to material.materials as node.material does not have a materials array.', this );
  28093. return;
  28094. }
  28095. targetObject = targetObject.material.materials;
  28096. break;
  28097. case 'bones':
  28098. if ( ! targetObject.skeleton ) {
  28099. console.error( 'THREE.PropertyBinding: Can not bind to bones as node does not have a skeleton.', this );
  28100. return;
  28101. }
  28102. // potential future optimization: skip this if propertyIndex is already an integer
  28103. // and convert the integer string to a true integer.
  28104. targetObject = targetObject.skeleton.bones;
  28105. // support resolving morphTarget names into indices.
  28106. for ( var i = 0; i < targetObject.length; i ++ ) {
  28107. if ( targetObject[ i ].name === objectIndex ) {
  28108. objectIndex = i;
  28109. break;
  28110. }
  28111. }
  28112. break;
  28113. default:
  28114. if ( targetObject[ objectName ] === undefined ) {
  28115. console.error( 'THREE.PropertyBinding: Can not bind to objectName of node undefined.', this );
  28116. return;
  28117. }
  28118. targetObject = targetObject[ objectName ];
  28119. }
  28120. if ( objectIndex !== undefined ) {
  28121. if ( targetObject[ objectIndex ] === undefined ) {
  28122. console.error( 'THREE.PropertyBinding: Trying to bind to objectIndex of objectName, but is undefined.', this, targetObject );
  28123. return;
  28124. }
  28125. targetObject = targetObject[ objectIndex ];
  28126. }
  28127. }
  28128. // resolve property
  28129. var nodeProperty = targetObject[ propertyName ];
  28130. if ( nodeProperty === undefined ) {
  28131. var nodeName = parsedPath.nodeName;
  28132. console.error( 'THREE.PropertyBinding: Trying to update property for track: ' + nodeName +
  28133. '.' + propertyName + ' but it wasn\'t found.', targetObject );
  28134. return;
  28135. }
  28136. // determine versioning scheme
  28137. var versioning = this.Versioning.None;
  28138. if ( targetObject.needsUpdate !== undefined ) { // material
  28139. versioning = this.Versioning.NeedsUpdate;
  28140. this.targetObject = targetObject;
  28141. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  28142. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  28143. this.targetObject = targetObject;
  28144. }
  28145. // determine how the property gets bound
  28146. var bindingType = this.BindingType.Direct;
  28147. if ( propertyIndex !== undefined ) {
  28148. // access a sub element of the property array (only primitives are supported right now)
  28149. if ( propertyName === "morphTargetInfluences" ) {
  28150. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  28151. // support resolving morphTarget names into indices.
  28152. if ( ! targetObject.geometry ) {
  28153. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.', this );
  28154. return;
  28155. }
  28156. if ( targetObject.geometry.isBufferGeometry ) {
  28157. if ( ! targetObject.geometry.morphAttributes ) {
  28158. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphAttributes.', this );
  28159. return;
  28160. }
  28161. for ( var i = 0; i < this.node.geometry.morphAttributes.position.length; i ++ ) {
  28162. if ( targetObject.geometry.morphAttributes.position[ i ].name === propertyIndex ) {
  28163. propertyIndex = i;
  28164. break;
  28165. }
  28166. }
  28167. } else {
  28168. if ( ! targetObject.geometry.morphTargets ) {
  28169. console.error( 'THREE.PropertyBinding: Can not bind to morphTargetInfluences because node does not have a geometry.morphTargets.', this );
  28170. return;
  28171. }
  28172. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  28173. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  28174. propertyIndex = i;
  28175. break;
  28176. }
  28177. }
  28178. }
  28179. }
  28180. bindingType = this.BindingType.ArrayElement;
  28181. this.resolvedProperty = nodeProperty;
  28182. this.propertyIndex = propertyIndex;
  28183. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  28184. // must use copy for Object3D.Euler/Quaternion
  28185. bindingType = this.BindingType.HasFromToArray;
  28186. this.resolvedProperty = nodeProperty;
  28187. } else if ( Array.isArray( nodeProperty ) ) {
  28188. bindingType = this.BindingType.EntireArray;
  28189. this.resolvedProperty = nodeProperty;
  28190. } else {
  28191. this.propertyName = propertyName;
  28192. }
  28193. // select getter / setter
  28194. this.getValue = this.GetterByBindingType[ bindingType ];
  28195. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  28196. },
  28197. unbind: function () {
  28198. this.node = null;
  28199. // back to the prototype version of getValue / setValue
  28200. // note: avoiding to mutate the shape of 'this' via 'delete'
  28201. this.getValue = this._getValue_unbound;
  28202. this.setValue = this._setValue_unbound;
  28203. }
  28204. } );
  28205. //!\ DECLARE ALIAS AFTER assign prototype !
  28206. Object.assign( PropertyBinding.prototype, {
  28207. // initial state of these methods that calls 'bind'
  28208. _getValue_unbound: PropertyBinding.prototype.getValue,
  28209. _setValue_unbound: PropertyBinding.prototype.setValue,
  28210. } );
  28211. /**
  28212. *
  28213. * A group of objects that receives a shared animation state.
  28214. *
  28215. * Usage:
  28216. *
  28217. * - Add objects you would otherwise pass as 'root' to the
  28218. * constructor or the .clipAction method of AnimationMixer.
  28219. *
  28220. * - Instead pass this object as 'root'.
  28221. *
  28222. * - You can also add and remove objects later when the mixer
  28223. * is running.
  28224. *
  28225. * Note:
  28226. *
  28227. * Objects of this class appear as one object to the mixer,
  28228. * so cache control of the individual objects must be done
  28229. * on the group.
  28230. *
  28231. * Limitation:
  28232. *
  28233. * - The animated properties must be compatible among the
  28234. * all objects in the group.
  28235. *
  28236. * - A single property can either be controlled through a
  28237. * target group or directly, but not both.
  28238. *
  28239. * @author tschw
  28240. */
  28241. function AnimationObjectGroup() {
  28242. this.uuid = _Math.generateUUID();
  28243. // cached objects followed by the active ones
  28244. this._objects = Array.prototype.slice.call( arguments );
  28245. this.nCachedObjects_ = 0; // threshold
  28246. // note: read by PropertyBinding.Composite
  28247. var indices = {};
  28248. this._indicesByUUID = indices; // for bookkeeping
  28249. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28250. indices[ arguments[ i ].uuid ] = i;
  28251. }
  28252. this._paths = []; // inside: string
  28253. this._parsedPaths = []; // inside: { we don't care, here }
  28254. this._bindings = []; // inside: Array< PropertyBinding >
  28255. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  28256. var scope = this;
  28257. this.stats = {
  28258. objects: {
  28259. get total() {
  28260. return scope._objects.length;
  28261. },
  28262. get inUse() {
  28263. return this.total - scope.nCachedObjects_;
  28264. }
  28265. },
  28266. get bindingsPerObject() {
  28267. return scope._bindings.length;
  28268. }
  28269. };
  28270. }
  28271. Object.assign( AnimationObjectGroup.prototype, {
  28272. isAnimationObjectGroup: true,
  28273. add: function () {
  28274. var objects = this._objects,
  28275. nObjects = objects.length,
  28276. nCachedObjects = this.nCachedObjects_,
  28277. indicesByUUID = this._indicesByUUID,
  28278. paths = this._paths,
  28279. parsedPaths = this._parsedPaths,
  28280. bindings = this._bindings,
  28281. nBindings = bindings.length;
  28282. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28283. var object = arguments[ i ],
  28284. uuid = object.uuid,
  28285. index = indicesByUUID[ uuid ],
  28286. knownObject = undefined;
  28287. if ( index === undefined ) {
  28288. // unknown object -> add it to the ACTIVE region
  28289. index = nObjects ++;
  28290. indicesByUUID[ uuid ] = index;
  28291. objects.push( object );
  28292. // accounting is done, now do the same for all bindings
  28293. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28294. bindings[ j ].push( new PropertyBinding( object, paths[ j ], parsedPaths[ j ] ) );
  28295. }
  28296. } else if ( index < nCachedObjects ) {
  28297. knownObject = objects[ index ];
  28298. // move existing object to the ACTIVE region
  28299. var firstActiveIndex = -- nCachedObjects,
  28300. lastCachedObject = objects[ firstActiveIndex ];
  28301. indicesByUUID[ lastCachedObject.uuid ] = index;
  28302. objects[ index ] = lastCachedObject;
  28303. indicesByUUID[ uuid ] = firstActiveIndex;
  28304. objects[ firstActiveIndex ] = object;
  28305. // accounting is done, now do the same for all bindings
  28306. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28307. var bindingsForPath = bindings[ j ],
  28308. lastCached = bindingsForPath[ firstActiveIndex ],
  28309. binding = bindingsForPath[ index ];
  28310. bindingsForPath[ index ] = lastCached;
  28311. if ( binding === undefined ) {
  28312. // since we do not bother to create new bindings
  28313. // for objects that are cached, the binding may
  28314. // or may not exist
  28315. binding = new PropertyBinding( object, paths[ j ], parsedPaths[ j ] );
  28316. }
  28317. bindingsForPath[ firstActiveIndex ] = binding;
  28318. }
  28319. } else if ( objects[ index ] !== knownObject ) {
  28320. console.error( 'THREE.AnimationObjectGroup: Different objects with the same UUID ' +
  28321. 'detected. Clean the caches or recreate your infrastructure when reloading scenes.' );
  28322. } // else the object is already where we want it to be
  28323. } // for arguments
  28324. this.nCachedObjects_ = nCachedObjects;
  28325. },
  28326. remove: function () {
  28327. var objects = this._objects,
  28328. nCachedObjects = this.nCachedObjects_,
  28329. indicesByUUID = this._indicesByUUID,
  28330. bindings = this._bindings,
  28331. nBindings = bindings.length;
  28332. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28333. var object = arguments[ i ],
  28334. uuid = object.uuid,
  28335. index = indicesByUUID[ uuid ];
  28336. if ( index !== undefined && index >= nCachedObjects ) {
  28337. // move existing object into the CACHED region
  28338. var lastCachedIndex = nCachedObjects ++,
  28339. firstActiveObject = objects[ lastCachedIndex ];
  28340. indicesByUUID[ firstActiveObject.uuid ] = index;
  28341. objects[ index ] = firstActiveObject;
  28342. indicesByUUID[ uuid ] = lastCachedIndex;
  28343. objects[ lastCachedIndex ] = object;
  28344. // accounting is done, now do the same for all bindings
  28345. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28346. var bindingsForPath = bindings[ j ],
  28347. firstActive = bindingsForPath[ lastCachedIndex ],
  28348. binding = bindingsForPath[ index ];
  28349. bindingsForPath[ index ] = firstActive;
  28350. bindingsForPath[ lastCachedIndex ] = binding;
  28351. }
  28352. }
  28353. } // for arguments
  28354. this.nCachedObjects_ = nCachedObjects;
  28355. },
  28356. // remove & forget
  28357. uncache: function () {
  28358. var objects = this._objects,
  28359. nObjects = objects.length,
  28360. nCachedObjects = this.nCachedObjects_,
  28361. indicesByUUID = this._indicesByUUID,
  28362. bindings = this._bindings,
  28363. nBindings = bindings.length;
  28364. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  28365. var object = arguments[ i ],
  28366. uuid = object.uuid,
  28367. index = indicesByUUID[ uuid ];
  28368. if ( index !== undefined ) {
  28369. delete indicesByUUID[ uuid ];
  28370. if ( index < nCachedObjects ) {
  28371. // object is cached, shrink the CACHED region
  28372. var firstActiveIndex = -- nCachedObjects,
  28373. lastCachedObject = objects[ firstActiveIndex ],
  28374. lastIndex = -- nObjects,
  28375. lastObject = objects[ lastIndex ];
  28376. // last cached object takes this object's place
  28377. indicesByUUID[ lastCachedObject.uuid ] = index;
  28378. objects[ index ] = lastCachedObject;
  28379. // last object goes to the activated slot and pop
  28380. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  28381. objects[ firstActiveIndex ] = lastObject;
  28382. objects.pop();
  28383. // accounting is done, now do the same for all bindings
  28384. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28385. var bindingsForPath = bindings[ j ],
  28386. lastCached = bindingsForPath[ firstActiveIndex ],
  28387. last = bindingsForPath[ lastIndex ];
  28388. bindingsForPath[ index ] = lastCached;
  28389. bindingsForPath[ firstActiveIndex ] = last;
  28390. bindingsForPath.pop();
  28391. }
  28392. } else {
  28393. // object is active, just swap with the last and pop
  28394. var lastIndex = -- nObjects,
  28395. lastObject = objects[ lastIndex ];
  28396. indicesByUUID[ lastObject.uuid ] = index;
  28397. objects[ index ] = lastObject;
  28398. objects.pop();
  28399. // accounting is done, now do the same for all bindings
  28400. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  28401. var bindingsForPath = bindings[ j ];
  28402. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  28403. bindingsForPath.pop();
  28404. }
  28405. } // cached or active
  28406. } // if object is known
  28407. } // for arguments
  28408. this.nCachedObjects_ = nCachedObjects;
  28409. },
  28410. // Internal interface used by befriended PropertyBinding.Composite:
  28411. subscribe_: function ( path, parsedPath ) {
  28412. // returns an array of bindings for the given path that is changed
  28413. // according to the contained objects in the group
  28414. var indicesByPath = this._bindingsIndicesByPath,
  28415. index = indicesByPath[ path ],
  28416. bindings = this._bindings;
  28417. if ( index !== undefined ) return bindings[ index ];
  28418. var paths = this._paths,
  28419. parsedPaths = this._parsedPaths,
  28420. objects = this._objects,
  28421. nObjects = objects.length,
  28422. nCachedObjects = this.nCachedObjects_,
  28423. bindingsForPath = new Array( nObjects );
  28424. index = bindings.length;
  28425. indicesByPath[ path ] = index;
  28426. paths.push( path );
  28427. parsedPaths.push( parsedPath );
  28428. bindings.push( bindingsForPath );
  28429. for ( var i = nCachedObjects, n = objects.length; i !== n; ++ i ) {
  28430. var object = objects[ i ];
  28431. bindingsForPath[ i ] = new PropertyBinding( object, path, parsedPath );
  28432. }
  28433. return bindingsForPath;
  28434. },
  28435. unsubscribe_: function ( path ) {
  28436. // tells the group to forget about a property path and no longer
  28437. // update the array previously obtained with 'subscribe_'
  28438. var indicesByPath = this._bindingsIndicesByPath,
  28439. index = indicesByPath[ path ];
  28440. if ( index !== undefined ) {
  28441. var paths = this._paths,
  28442. parsedPaths = this._parsedPaths,
  28443. bindings = this._bindings,
  28444. lastBindingsIndex = bindings.length - 1,
  28445. lastBindings = bindings[ lastBindingsIndex ],
  28446. lastBindingsPath = path[ lastBindingsIndex ];
  28447. indicesByPath[ lastBindingsPath ] = index;
  28448. bindings[ index ] = lastBindings;
  28449. bindings.pop();
  28450. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  28451. parsedPaths.pop();
  28452. paths[ index ] = paths[ lastBindingsIndex ];
  28453. paths.pop();
  28454. }
  28455. }
  28456. } );
  28457. /**
  28458. *
  28459. * Action provided by AnimationMixer for scheduling clip playback on specific
  28460. * objects.
  28461. *
  28462. * @author Ben Houston / http://clara.io/
  28463. * @author David Sarno / http://lighthaus.us/
  28464. * @author tschw
  28465. *
  28466. */
  28467. function AnimationAction( mixer, clip, localRoot ) {
  28468. this._mixer = mixer;
  28469. this._clip = clip;
  28470. this._localRoot = localRoot || null;
  28471. var tracks = clip.tracks,
  28472. nTracks = tracks.length,
  28473. interpolants = new Array( nTracks );
  28474. var interpolantSettings = {
  28475. endingStart: ZeroCurvatureEnding,
  28476. endingEnd: ZeroCurvatureEnding
  28477. };
  28478. for ( var i = 0; i !== nTracks; ++ i ) {
  28479. var interpolant = tracks[ i ].createInterpolant( null );
  28480. interpolants[ i ] = interpolant;
  28481. interpolant.settings = interpolantSettings;
  28482. }
  28483. this._interpolantSettings = interpolantSettings;
  28484. this._interpolants = interpolants; // bound by the mixer
  28485. // inside: PropertyMixer (managed by the mixer)
  28486. this._propertyBindings = new Array( nTracks );
  28487. this._cacheIndex = null; // for the memory manager
  28488. this._byClipCacheIndex = null; // for the memory manager
  28489. this._timeScaleInterpolant = null;
  28490. this._weightInterpolant = null;
  28491. this.loop = LoopRepeat;
  28492. this._loopCount = - 1;
  28493. // global mixer time when the action is to be started
  28494. // it's set back to 'null' upon start of the action
  28495. this._startTime = null;
  28496. // scaled local time of the action
  28497. // gets clamped or wrapped to 0..clip.duration according to loop
  28498. this.time = 0;
  28499. this.timeScale = 1;
  28500. this._effectiveTimeScale = 1;
  28501. this.weight = 1;
  28502. this._effectiveWeight = 1;
  28503. this.repetitions = Infinity; // no. of repetitions when looping
  28504. this.paused = false; // true -> zero effective time scale
  28505. this.enabled = true; // false -> zero effective weight
  28506. this.clampWhenFinished = false; // keep feeding the last frame?
  28507. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  28508. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  28509. }
  28510. Object.assign( AnimationAction.prototype, {
  28511. // State & Scheduling
  28512. play: function () {
  28513. this._mixer._activateAction( this );
  28514. return this;
  28515. },
  28516. stop: function () {
  28517. this._mixer._deactivateAction( this );
  28518. return this.reset();
  28519. },
  28520. reset: function () {
  28521. this.paused = false;
  28522. this.enabled = true;
  28523. this.time = 0; // restart clip
  28524. this._loopCount = - 1; // forget previous loops
  28525. this._startTime = null; // forget scheduling
  28526. return this.stopFading().stopWarping();
  28527. },
  28528. isRunning: function () {
  28529. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  28530. this._startTime === null && this._mixer._isActiveAction( this );
  28531. },
  28532. // return true when play has been called
  28533. isScheduled: function () {
  28534. return this._mixer._isActiveAction( this );
  28535. },
  28536. startAt: function ( time ) {
  28537. this._startTime = time;
  28538. return this;
  28539. },
  28540. setLoop: function ( mode, repetitions ) {
  28541. this.loop = mode;
  28542. this.repetitions = repetitions;
  28543. return this;
  28544. },
  28545. // Weight
  28546. // set the weight stopping any scheduled fading
  28547. // although .enabled = false yields an effective weight of zero, this
  28548. // method does *not* change .enabled, because it would be confusing
  28549. setEffectiveWeight: function ( weight ) {
  28550. this.weight = weight;
  28551. // note: same logic as when updated at runtime
  28552. this._effectiveWeight = this.enabled ? weight : 0;
  28553. return this.stopFading();
  28554. },
  28555. // return the weight considering fading and .enabled
  28556. getEffectiveWeight: function () {
  28557. return this._effectiveWeight;
  28558. },
  28559. fadeIn: function ( duration ) {
  28560. return this._scheduleFading( duration, 0, 1 );
  28561. },
  28562. fadeOut: function ( duration ) {
  28563. return this._scheduleFading( duration, 1, 0 );
  28564. },
  28565. crossFadeFrom: function ( fadeOutAction, duration, warp ) {
  28566. fadeOutAction.fadeOut( duration );
  28567. this.fadeIn( duration );
  28568. if ( warp ) {
  28569. var fadeInDuration = this._clip.duration,
  28570. fadeOutDuration = fadeOutAction._clip.duration,
  28571. startEndRatio = fadeOutDuration / fadeInDuration,
  28572. endStartRatio = fadeInDuration / fadeOutDuration;
  28573. fadeOutAction.warp( 1.0, startEndRatio, duration );
  28574. this.warp( endStartRatio, 1.0, duration );
  28575. }
  28576. return this;
  28577. },
  28578. crossFadeTo: function ( fadeInAction, duration, warp ) {
  28579. return fadeInAction.crossFadeFrom( this, duration, warp );
  28580. },
  28581. stopFading: function () {
  28582. var weightInterpolant = this._weightInterpolant;
  28583. if ( weightInterpolant !== null ) {
  28584. this._weightInterpolant = null;
  28585. this._mixer._takeBackControlInterpolant( weightInterpolant );
  28586. }
  28587. return this;
  28588. },
  28589. // Time Scale Control
  28590. // set the time scale stopping any scheduled warping
  28591. // although .paused = true yields an effective time scale of zero, this
  28592. // method does *not* change .paused, because it would be confusing
  28593. setEffectiveTimeScale: function ( timeScale ) {
  28594. this.timeScale = timeScale;
  28595. this._effectiveTimeScale = this.paused ? 0 : timeScale;
  28596. return this.stopWarping();
  28597. },
  28598. // return the time scale considering warping and .paused
  28599. getEffectiveTimeScale: function () {
  28600. return this._effectiveTimeScale;
  28601. },
  28602. setDuration: function ( duration ) {
  28603. this.timeScale = this._clip.duration / duration;
  28604. return this.stopWarping();
  28605. },
  28606. syncWith: function ( action ) {
  28607. this.time = action.time;
  28608. this.timeScale = action.timeScale;
  28609. return this.stopWarping();
  28610. },
  28611. halt: function ( duration ) {
  28612. return this.warp( this._effectiveTimeScale, 0, duration );
  28613. },
  28614. warp: function ( startTimeScale, endTimeScale, duration ) {
  28615. var mixer = this._mixer, now = mixer.time,
  28616. interpolant = this._timeScaleInterpolant,
  28617. timeScale = this.timeScale;
  28618. if ( interpolant === null ) {
  28619. interpolant = mixer._lendControlInterpolant();
  28620. this._timeScaleInterpolant = interpolant;
  28621. }
  28622. var times = interpolant.parameterPositions,
  28623. values = interpolant.sampleValues;
  28624. times[ 0 ] = now;
  28625. times[ 1 ] = now + duration;
  28626. values[ 0 ] = startTimeScale / timeScale;
  28627. values[ 1 ] = endTimeScale / timeScale;
  28628. return this;
  28629. },
  28630. stopWarping: function () {
  28631. var timeScaleInterpolant = this._timeScaleInterpolant;
  28632. if ( timeScaleInterpolant !== null ) {
  28633. this._timeScaleInterpolant = null;
  28634. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  28635. }
  28636. return this;
  28637. },
  28638. // Object Accessors
  28639. getMixer: function () {
  28640. return this._mixer;
  28641. },
  28642. getClip: function () {
  28643. return this._clip;
  28644. },
  28645. getRoot: function () {
  28646. return this._localRoot || this._mixer._root;
  28647. },
  28648. // Interna
  28649. _update: function ( time, deltaTime, timeDirection, accuIndex ) {
  28650. // called by the mixer
  28651. if ( ! this.enabled ) {
  28652. // call ._updateWeight() to update ._effectiveWeight
  28653. this._updateWeight( time );
  28654. return;
  28655. }
  28656. var startTime = this._startTime;
  28657. if ( startTime !== null ) {
  28658. // check for scheduled start of action
  28659. var timeRunning = ( time - startTime ) * timeDirection;
  28660. if ( timeRunning < 0 || timeDirection === 0 ) {
  28661. return; // yet to come / don't decide when delta = 0
  28662. }
  28663. // start
  28664. this._startTime = null; // unschedule
  28665. deltaTime = timeDirection * timeRunning;
  28666. }
  28667. // apply time scale and advance time
  28668. deltaTime *= this._updateTimeScale( time );
  28669. var clipTime = this._updateTime( deltaTime );
  28670. // note: _updateTime may disable the action resulting in
  28671. // an effective weight of 0
  28672. var weight = this._updateWeight( time );
  28673. if ( weight > 0 ) {
  28674. var interpolants = this._interpolants;
  28675. var propertyMixers = this._propertyBindings;
  28676. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  28677. interpolants[ j ].evaluate( clipTime );
  28678. propertyMixers[ j ].accumulate( accuIndex, weight );
  28679. }
  28680. }
  28681. },
  28682. _updateWeight: function ( time ) {
  28683. var weight = 0;
  28684. if ( this.enabled ) {
  28685. weight = this.weight;
  28686. var interpolant = this._weightInterpolant;
  28687. if ( interpolant !== null ) {
  28688. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28689. weight *= interpolantValue;
  28690. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28691. this.stopFading();
  28692. if ( interpolantValue === 0 ) {
  28693. // faded out, disable
  28694. this.enabled = false;
  28695. }
  28696. }
  28697. }
  28698. }
  28699. this._effectiveWeight = weight;
  28700. return weight;
  28701. },
  28702. _updateTimeScale: function ( time ) {
  28703. var timeScale = 0;
  28704. if ( ! this.paused ) {
  28705. timeScale = this.timeScale;
  28706. var interpolant = this._timeScaleInterpolant;
  28707. if ( interpolant !== null ) {
  28708. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  28709. timeScale *= interpolantValue;
  28710. if ( time > interpolant.parameterPositions[ 1 ] ) {
  28711. this.stopWarping();
  28712. if ( timeScale === 0 ) {
  28713. // motion has halted, pause
  28714. this.paused = true;
  28715. } else {
  28716. // warp done - apply final time scale
  28717. this.timeScale = timeScale;
  28718. }
  28719. }
  28720. }
  28721. }
  28722. this._effectiveTimeScale = timeScale;
  28723. return timeScale;
  28724. },
  28725. _updateTime: function ( deltaTime ) {
  28726. var time = this.time + deltaTime;
  28727. if ( deltaTime === 0 ) return time;
  28728. var duration = this._clip.duration,
  28729. loop = this.loop,
  28730. loopCount = this._loopCount;
  28731. if ( loop === LoopOnce ) {
  28732. if ( loopCount === - 1 ) {
  28733. // just started
  28734. this._loopCount = 0;
  28735. this._setEndings( true, true, false );
  28736. }
  28737. handle_stop: {
  28738. if ( time >= duration ) {
  28739. time = duration;
  28740. } else if ( time < 0 ) {
  28741. time = 0;
  28742. } else break handle_stop;
  28743. if ( this.clampWhenFinished ) this.paused = true;
  28744. else this.enabled = false;
  28745. this._mixer.dispatchEvent( {
  28746. type: 'finished', action: this,
  28747. direction: deltaTime < 0 ? - 1 : 1
  28748. } );
  28749. }
  28750. } else { // repetitive Repeat or PingPong
  28751. var pingPong = ( loop === LoopPingPong );
  28752. if ( loopCount === - 1 ) {
  28753. // just started
  28754. if ( deltaTime >= 0 ) {
  28755. loopCount = 0;
  28756. this._setEndings( true, this.repetitions === 0, pingPong );
  28757. } else {
  28758. // when looping in reverse direction, the initial
  28759. // transition through zero counts as a repetition,
  28760. // so leave loopCount at -1
  28761. this._setEndings( this.repetitions === 0, true, pingPong );
  28762. }
  28763. }
  28764. if ( time >= duration || time < 0 ) {
  28765. // wrap around
  28766. var loopDelta = Math.floor( time / duration ); // signed
  28767. time -= duration * loopDelta;
  28768. loopCount += Math.abs( loopDelta );
  28769. var pending = this.repetitions - loopCount;
  28770. if ( pending < 0 ) {
  28771. // have to stop (switch state, clamp time, fire event)
  28772. if ( this.clampWhenFinished ) this.paused = true;
  28773. else this.enabled = false;
  28774. time = deltaTime > 0 ? duration : 0;
  28775. this._mixer.dispatchEvent( {
  28776. type: 'finished', action: this,
  28777. direction: deltaTime > 0 ? 1 : - 1
  28778. } );
  28779. } else {
  28780. // keep running
  28781. if ( pending === 0 ) {
  28782. // entering the last round
  28783. var atStart = deltaTime < 0;
  28784. this._setEndings( atStart, ! atStart, pingPong );
  28785. } else {
  28786. this._setEndings( false, false, pingPong );
  28787. }
  28788. this._loopCount = loopCount;
  28789. this._mixer.dispatchEvent( {
  28790. type: 'loop', action: this, loopDelta: loopDelta
  28791. } );
  28792. }
  28793. }
  28794. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  28795. // invert time for the "pong round"
  28796. this.time = time;
  28797. return duration - time;
  28798. }
  28799. }
  28800. this.time = time;
  28801. return time;
  28802. },
  28803. _setEndings: function ( atStart, atEnd, pingPong ) {
  28804. var settings = this._interpolantSettings;
  28805. if ( pingPong ) {
  28806. settings.endingStart = ZeroSlopeEnding;
  28807. settings.endingEnd = ZeroSlopeEnding;
  28808. } else {
  28809. // assuming for LoopOnce atStart == atEnd == true
  28810. if ( atStart ) {
  28811. settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28812. } else {
  28813. settings.endingStart = WrapAroundEnding;
  28814. }
  28815. if ( atEnd ) {
  28816. settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
  28817. } else {
  28818. settings.endingEnd = WrapAroundEnding;
  28819. }
  28820. }
  28821. },
  28822. _scheduleFading: function ( duration, weightNow, weightThen ) {
  28823. var mixer = this._mixer, now = mixer.time,
  28824. interpolant = this._weightInterpolant;
  28825. if ( interpolant === null ) {
  28826. interpolant = mixer._lendControlInterpolant();
  28827. this._weightInterpolant = interpolant;
  28828. }
  28829. var times = interpolant.parameterPositions,
  28830. values = interpolant.sampleValues;
  28831. times[ 0 ] = now; values[ 0 ] = weightNow;
  28832. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  28833. return this;
  28834. }
  28835. } );
  28836. /**
  28837. *
  28838. * Player for AnimationClips.
  28839. *
  28840. *
  28841. * @author Ben Houston / http://clara.io/
  28842. * @author David Sarno / http://lighthaus.us/
  28843. * @author tschw
  28844. */
  28845. function AnimationMixer( root ) {
  28846. this._root = root;
  28847. this._initMemoryManager();
  28848. this._accuIndex = 0;
  28849. this.time = 0;
  28850. this.timeScale = 1.0;
  28851. }
  28852. AnimationMixer.prototype = Object.assign( Object.create( EventDispatcher.prototype ), {
  28853. constructor: AnimationMixer,
  28854. _bindAction: function ( action, prototypeAction ) {
  28855. var root = action._localRoot || this._root,
  28856. tracks = action._clip.tracks,
  28857. nTracks = tracks.length,
  28858. bindings = action._propertyBindings,
  28859. interpolants = action._interpolants,
  28860. rootUuid = root.uuid,
  28861. bindingsByRoot = this._bindingsByRootAndName,
  28862. bindingsByName = bindingsByRoot[ rootUuid ];
  28863. if ( bindingsByName === undefined ) {
  28864. bindingsByName = {};
  28865. bindingsByRoot[ rootUuid ] = bindingsByName;
  28866. }
  28867. for ( var i = 0; i !== nTracks; ++ i ) {
  28868. var track = tracks[ i ],
  28869. trackName = track.name,
  28870. binding = bindingsByName[ trackName ];
  28871. if ( binding !== undefined ) {
  28872. bindings[ i ] = binding;
  28873. } else {
  28874. binding = bindings[ i ];
  28875. if ( binding !== undefined ) {
  28876. // existing binding, make sure the cache knows
  28877. if ( binding._cacheIndex === null ) {
  28878. ++ binding.referenceCount;
  28879. this._addInactiveBinding( binding, rootUuid, trackName );
  28880. }
  28881. continue;
  28882. }
  28883. var path = prototypeAction && prototypeAction.
  28884. _propertyBindings[ i ].binding.parsedPath;
  28885. binding = new PropertyMixer(
  28886. PropertyBinding.create( root, trackName, path ),
  28887. track.ValueTypeName, track.getValueSize() );
  28888. ++ binding.referenceCount;
  28889. this._addInactiveBinding( binding, rootUuid, trackName );
  28890. bindings[ i ] = binding;
  28891. }
  28892. interpolants[ i ].resultBuffer = binding.buffer;
  28893. }
  28894. },
  28895. _activateAction: function ( action ) {
  28896. if ( ! this._isActiveAction( action ) ) {
  28897. if ( action._cacheIndex === null ) {
  28898. // this action has been forgotten by the cache, but the user
  28899. // appears to be still using it -> rebind
  28900. var rootUuid = ( action._localRoot || this._root ).uuid,
  28901. clipUuid = action._clip.uuid,
  28902. actionsForClip = this._actionsByClip[ clipUuid ];
  28903. this._bindAction( action,
  28904. actionsForClip && actionsForClip.knownActions[ 0 ] );
  28905. this._addInactiveAction( action, clipUuid, rootUuid );
  28906. }
  28907. var bindings = action._propertyBindings;
  28908. // increment reference counts / sort out state
  28909. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  28910. var binding = bindings[ i ];
  28911. if ( binding.useCount ++ === 0 ) {
  28912. this._lendBinding( binding );
  28913. binding.saveOriginalState();
  28914. }
  28915. }
  28916. this._lendAction( action );
  28917. }
  28918. },
  28919. _deactivateAction: function ( action ) {
  28920. if ( this._isActiveAction( action ) ) {
  28921. var bindings = action._propertyBindings;
  28922. // decrement reference counts / sort out state
  28923. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  28924. var binding = bindings[ i ];
  28925. if ( -- binding.useCount === 0 ) {
  28926. binding.restoreOriginalState();
  28927. this._takeBackBinding( binding );
  28928. }
  28929. }
  28930. this._takeBackAction( action );
  28931. }
  28932. },
  28933. // Memory manager
  28934. _initMemoryManager: function () {
  28935. this._actions = []; // 'nActiveActions' followed by inactive ones
  28936. this._nActiveActions = 0;
  28937. this._actionsByClip = {};
  28938. // inside:
  28939. // {
  28940. // knownActions: Array< AnimationAction > - used as prototypes
  28941. // actionByRoot: AnimationAction - lookup
  28942. // }
  28943. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  28944. this._nActiveBindings = 0;
  28945. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  28946. this._controlInterpolants = []; // same game as above
  28947. this._nActiveControlInterpolants = 0;
  28948. var scope = this;
  28949. this.stats = {
  28950. actions: {
  28951. get total() {
  28952. return scope._actions.length;
  28953. },
  28954. get inUse() {
  28955. return scope._nActiveActions;
  28956. }
  28957. },
  28958. bindings: {
  28959. get total() {
  28960. return scope._bindings.length;
  28961. },
  28962. get inUse() {
  28963. return scope._nActiveBindings;
  28964. }
  28965. },
  28966. controlInterpolants: {
  28967. get total() {
  28968. return scope._controlInterpolants.length;
  28969. },
  28970. get inUse() {
  28971. return scope._nActiveControlInterpolants;
  28972. }
  28973. }
  28974. };
  28975. },
  28976. // Memory management for AnimationAction objects
  28977. _isActiveAction: function ( action ) {
  28978. var index = action._cacheIndex;
  28979. return index !== null && index < this._nActiveActions;
  28980. },
  28981. _addInactiveAction: function ( action, clipUuid, rootUuid ) {
  28982. var actions = this._actions,
  28983. actionsByClip = this._actionsByClip,
  28984. actionsForClip = actionsByClip[ clipUuid ];
  28985. if ( actionsForClip === undefined ) {
  28986. actionsForClip = {
  28987. knownActions: [ action ],
  28988. actionByRoot: {}
  28989. };
  28990. action._byClipCacheIndex = 0;
  28991. actionsByClip[ clipUuid ] = actionsForClip;
  28992. } else {
  28993. var knownActions = actionsForClip.knownActions;
  28994. action._byClipCacheIndex = knownActions.length;
  28995. knownActions.push( action );
  28996. }
  28997. action._cacheIndex = actions.length;
  28998. actions.push( action );
  28999. actionsForClip.actionByRoot[ rootUuid ] = action;
  29000. },
  29001. _removeInactiveAction: function ( action ) {
  29002. var actions = this._actions,
  29003. lastInactiveAction = actions[ actions.length - 1 ],
  29004. cacheIndex = action._cacheIndex;
  29005. lastInactiveAction._cacheIndex = cacheIndex;
  29006. actions[ cacheIndex ] = lastInactiveAction;
  29007. actions.pop();
  29008. action._cacheIndex = null;
  29009. var clipUuid = action._clip.uuid,
  29010. actionsByClip = this._actionsByClip,
  29011. actionsForClip = actionsByClip[ clipUuid ],
  29012. knownActionsForClip = actionsForClip.knownActions,
  29013. lastKnownAction =
  29014. knownActionsForClip[ knownActionsForClip.length - 1 ],
  29015. byClipCacheIndex = action._byClipCacheIndex;
  29016. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  29017. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  29018. knownActionsForClip.pop();
  29019. action._byClipCacheIndex = null;
  29020. var actionByRoot = actionsForClip.actionByRoot,
  29021. rootUuid = ( action._localRoot || this._root ).uuid;
  29022. delete actionByRoot[ rootUuid ];
  29023. if ( knownActionsForClip.length === 0 ) {
  29024. delete actionsByClip[ clipUuid ];
  29025. }
  29026. this._removeInactiveBindingsForAction( action );
  29027. },
  29028. _removeInactiveBindingsForAction: function ( action ) {
  29029. var bindings = action._propertyBindings;
  29030. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  29031. var binding = bindings[ i ];
  29032. if ( -- binding.referenceCount === 0 ) {
  29033. this._removeInactiveBinding( binding );
  29034. }
  29035. }
  29036. },
  29037. _lendAction: function ( action ) {
  29038. // [ active actions | inactive actions ]
  29039. // [ active actions >| inactive actions ]
  29040. // s a
  29041. // <-swap->
  29042. // a s
  29043. var actions = this._actions,
  29044. prevIndex = action._cacheIndex,
  29045. lastActiveIndex = this._nActiveActions ++,
  29046. firstInactiveAction = actions[ lastActiveIndex ];
  29047. action._cacheIndex = lastActiveIndex;
  29048. actions[ lastActiveIndex ] = action;
  29049. firstInactiveAction._cacheIndex = prevIndex;
  29050. actions[ prevIndex ] = firstInactiveAction;
  29051. },
  29052. _takeBackAction: function ( action ) {
  29053. // [ active actions | inactive actions ]
  29054. // [ active actions |< inactive actions ]
  29055. // a s
  29056. // <-swap->
  29057. // s a
  29058. var actions = this._actions,
  29059. prevIndex = action._cacheIndex,
  29060. firstInactiveIndex = -- this._nActiveActions,
  29061. lastActiveAction = actions[ firstInactiveIndex ];
  29062. action._cacheIndex = firstInactiveIndex;
  29063. actions[ firstInactiveIndex ] = action;
  29064. lastActiveAction._cacheIndex = prevIndex;
  29065. actions[ prevIndex ] = lastActiveAction;
  29066. },
  29067. // Memory management for PropertyMixer objects
  29068. _addInactiveBinding: function ( binding, rootUuid, trackName ) {
  29069. var bindingsByRoot = this._bindingsByRootAndName,
  29070. bindingByName = bindingsByRoot[ rootUuid ],
  29071. bindings = this._bindings;
  29072. if ( bindingByName === undefined ) {
  29073. bindingByName = {};
  29074. bindingsByRoot[ rootUuid ] = bindingByName;
  29075. }
  29076. bindingByName[ trackName ] = binding;
  29077. binding._cacheIndex = bindings.length;
  29078. bindings.push( binding );
  29079. },
  29080. _removeInactiveBinding: function ( binding ) {
  29081. var bindings = this._bindings,
  29082. propBinding = binding.binding,
  29083. rootUuid = propBinding.rootNode.uuid,
  29084. trackName = propBinding.path,
  29085. bindingsByRoot = this._bindingsByRootAndName,
  29086. bindingByName = bindingsByRoot[ rootUuid ],
  29087. lastInactiveBinding = bindings[ bindings.length - 1 ],
  29088. cacheIndex = binding._cacheIndex;
  29089. lastInactiveBinding._cacheIndex = cacheIndex;
  29090. bindings[ cacheIndex ] = lastInactiveBinding;
  29091. bindings.pop();
  29092. delete bindingByName[ trackName ];
  29093. remove_empty_map: {
  29094. for ( var _ in bindingByName ) break remove_empty_map; // eslint-disable-line no-unused-vars
  29095. delete bindingsByRoot[ rootUuid ];
  29096. }
  29097. },
  29098. _lendBinding: function ( binding ) {
  29099. var bindings = this._bindings,
  29100. prevIndex = binding._cacheIndex,
  29101. lastActiveIndex = this._nActiveBindings ++,
  29102. firstInactiveBinding = bindings[ lastActiveIndex ];
  29103. binding._cacheIndex = lastActiveIndex;
  29104. bindings[ lastActiveIndex ] = binding;
  29105. firstInactiveBinding._cacheIndex = prevIndex;
  29106. bindings[ prevIndex ] = firstInactiveBinding;
  29107. },
  29108. _takeBackBinding: function ( binding ) {
  29109. var bindings = this._bindings,
  29110. prevIndex = binding._cacheIndex,
  29111. firstInactiveIndex = -- this._nActiveBindings,
  29112. lastActiveBinding = bindings[ firstInactiveIndex ];
  29113. binding._cacheIndex = firstInactiveIndex;
  29114. bindings[ firstInactiveIndex ] = binding;
  29115. lastActiveBinding._cacheIndex = prevIndex;
  29116. bindings[ prevIndex ] = lastActiveBinding;
  29117. },
  29118. // Memory management of Interpolants for weight and time scale
  29119. _lendControlInterpolant: function () {
  29120. var interpolants = this._controlInterpolants,
  29121. lastActiveIndex = this._nActiveControlInterpolants ++,
  29122. interpolant = interpolants[ lastActiveIndex ];
  29123. if ( interpolant === undefined ) {
  29124. interpolant = new LinearInterpolant(
  29125. new Float32Array( 2 ), new Float32Array( 2 ),
  29126. 1, this._controlInterpolantsResultBuffer );
  29127. interpolant.__cacheIndex = lastActiveIndex;
  29128. interpolants[ lastActiveIndex ] = interpolant;
  29129. }
  29130. return interpolant;
  29131. },
  29132. _takeBackControlInterpolant: function ( interpolant ) {
  29133. var interpolants = this._controlInterpolants,
  29134. prevIndex = interpolant.__cacheIndex,
  29135. firstInactiveIndex = -- this._nActiveControlInterpolants,
  29136. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  29137. interpolant.__cacheIndex = firstInactiveIndex;
  29138. interpolants[ firstInactiveIndex ] = interpolant;
  29139. lastActiveInterpolant.__cacheIndex = prevIndex;
  29140. interpolants[ prevIndex ] = lastActiveInterpolant;
  29141. },
  29142. _controlInterpolantsResultBuffer: new Float32Array( 1 ),
  29143. // return an action for a clip optionally using a custom root target
  29144. // object (this method allocates a lot of dynamic memory in case a
  29145. // previously unknown clip/root combination is specified)
  29146. clipAction: function ( clip, optionalRoot ) {
  29147. var root = optionalRoot || this._root,
  29148. rootUuid = root.uuid,
  29149. clipObject = typeof clip === 'string' ?
  29150. AnimationClip.findByName( root, clip ) : clip,
  29151. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  29152. actionsForClip = this._actionsByClip[ clipUuid ],
  29153. prototypeAction = null;
  29154. if ( actionsForClip !== undefined ) {
  29155. var existingAction =
  29156. actionsForClip.actionByRoot[ rootUuid ];
  29157. if ( existingAction !== undefined ) {
  29158. return existingAction;
  29159. }
  29160. // we know the clip, so we don't have to parse all
  29161. // the bindings again but can just copy
  29162. prototypeAction = actionsForClip.knownActions[ 0 ];
  29163. // also, take the clip from the prototype action
  29164. if ( clipObject === null )
  29165. clipObject = prototypeAction._clip;
  29166. }
  29167. // clip must be known when specified via string
  29168. if ( clipObject === null ) return null;
  29169. // allocate all resources required to run it
  29170. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  29171. this._bindAction( newAction, prototypeAction );
  29172. // and make the action known to the memory manager
  29173. this._addInactiveAction( newAction, clipUuid, rootUuid );
  29174. return newAction;
  29175. },
  29176. // get an existing action
  29177. existingAction: function ( clip, optionalRoot ) {
  29178. var root = optionalRoot || this._root,
  29179. rootUuid = root.uuid,
  29180. clipObject = typeof clip === 'string' ?
  29181. AnimationClip.findByName( root, clip ) : clip,
  29182. clipUuid = clipObject ? clipObject.uuid : clip,
  29183. actionsForClip = this._actionsByClip[ clipUuid ];
  29184. if ( actionsForClip !== undefined ) {
  29185. return actionsForClip.actionByRoot[ rootUuid ] || null;
  29186. }
  29187. return null;
  29188. },
  29189. // deactivates all previously scheduled actions
  29190. stopAllAction: function () {
  29191. var actions = this._actions,
  29192. nActions = this._nActiveActions,
  29193. bindings = this._bindings,
  29194. nBindings = this._nActiveBindings;
  29195. this._nActiveActions = 0;
  29196. this._nActiveBindings = 0;
  29197. for ( var i = 0; i !== nActions; ++ i ) {
  29198. actions[ i ].reset();
  29199. }
  29200. for ( var i = 0; i !== nBindings; ++ i ) {
  29201. bindings[ i ].useCount = 0;
  29202. }
  29203. return this;
  29204. },
  29205. // advance the time and update apply the animation
  29206. update: function ( deltaTime ) {
  29207. deltaTime *= this.timeScale;
  29208. var actions = this._actions,
  29209. nActions = this._nActiveActions,
  29210. time = this.time += deltaTime,
  29211. timeDirection = Math.sign( deltaTime ),
  29212. accuIndex = this._accuIndex ^= 1;
  29213. // run active actions
  29214. for ( var i = 0; i !== nActions; ++ i ) {
  29215. var action = actions[ i ];
  29216. action._update( time, deltaTime, timeDirection, accuIndex );
  29217. }
  29218. // update scene graph
  29219. var bindings = this._bindings,
  29220. nBindings = this._nActiveBindings;
  29221. for ( var i = 0; i !== nBindings; ++ i ) {
  29222. bindings[ i ].apply( accuIndex );
  29223. }
  29224. return this;
  29225. },
  29226. // return this mixer's root target object
  29227. getRoot: function () {
  29228. return this._root;
  29229. },
  29230. // free all resources specific to a particular clip
  29231. uncacheClip: function ( clip ) {
  29232. var actions = this._actions,
  29233. clipUuid = clip.uuid,
  29234. actionsByClip = this._actionsByClip,
  29235. actionsForClip = actionsByClip[ clipUuid ];
  29236. if ( actionsForClip !== undefined ) {
  29237. // note: just calling _removeInactiveAction would mess up the
  29238. // iteration state and also require updating the state we can
  29239. // just throw away
  29240. var actionsToRemove = actionsForClip.knownActions;
  29241. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  29242. var action = actionsToRemove[ i ];
  29243. this._deactivateAction( action );
  29244. var cacheIndex = action._cacheIndex,
  29245. lastInactiveAction = actions[ actions.length - 1 ];
  29246. action._cacheIndex = null;
  29247. action._byClipCacheIndex = null;
  29248. lastInactiveAction._cacheIndex = cacheIndex;
  29249. actions[ cacheIndex ] = lastInactiveAction;
  29250. actions.pop();
  29251. this._removeInactiveBindingsForAction( action );
  29252. }
  29253. delete actionsByClip[ clipUuid ];
  29254. }
  29255. },
  29256. // free all resources specific to a particular root target object
  29257. uncacheRoot: function ( root ) {
  29258. var rootUuid = root.uuid,
  29259. actionsByClip = this._actionsByClip;
  29260. for ( var clipUuid in actionsByClip ) {
  29261. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  29262. action = actionByRoot[ rootUuid ];
  29263. if ( action !== undefined ) {
  29264. this._deactivateAction( action );
  29265. this._removeInactiveAction( action );
  29266. }
  29267. }
  29268. var bindingsByRoot = this._bindingsByRootAndName,
  29269. bindingByName = bindingsByRoot[ rootUuid ];
  29270. if ( bindingByName !== undefined ) {
  29271. for ( var trackName in bindingByName ) {
  29272. var binding = bindingByName[ trackName ];
  29273. binding.restoreOriginalState();
  29274. this._removeInactiveBinding( binding );
  29275. }
  29276. }
  29277. },
  29278. // remove a targeted clip from the cache
  29279. uncacheAction: function ( clip, optionalRoot ) {
  29280. var action = this.existingAction( clip, optionalRoot );
  29281. if ( action !== null ) {
  29282. this._deactivateAction( action );
  29283. this._removeInactiveAction( action );
  29284. }
  29285. }
  29286. } );
  29287. /**
  29288. * @author mrdoob / http://mrdoob.com/
  29289. */
  29290. function Uniform( value ) {
  29291. if ( typeof value === 'string' ) {
  29292. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  29293. value = arguments[ 1 ];
  29294. }
  29295. this.value = value;
  29296. }
  29297. Uniform.prototype.clone = function () {
  29298. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  29299. };
  29300. /**
  29301. * @author benaadams / https://twitter.com/ben_a_adams
  29302. */
  29303. function InstancedBufferGeometry() {
  29304. BufferGeometry.call( this );
  29305. this.type = 'InstancedBufferGeometry';
  29306. this.maxInstancedCount = undefined;
  29307. }
  29308. InstancedBufferGeometry.prototype = Object.assign( Object.create( BufferGeometry.prototype ), {
  29309. constructor: InstancedBufferGeometry,
  29310. isInstancedBufferGeometry: true,
  29311. copy: function ( source ) {
  29312. BufferGeometry.prototype.copy.call( this, source );
  29313. this.maxInstancedCount = source.maxInstancedCount;
  29314. return this;
  29315. },
  29316. clone: function () {
  29317. return new this.constructor().copy( this );
  29318. }
  29319. } );
  29320. /**
  29321. * @author benaadams / https://twitter.com/ben_a_adams
  29322. */
  29323. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  29324. this.uuid = _Math.generateUUID();
  29325. this.data = interleavedBuffer;
  29326. this.itemSize = itemSize;
  29327. this.offset = offset;
  29328. this.normalized = normalized === true;
  29329. }
  29330. Object.defineProperties( InterleavedBufferAttribute.prototype, {
  29331. count: {
  29332. get: function () {
  29333. return this.data.count;
  29334. }
  29335. },
  29336. array: {
  29337. get: function () {
  29338. return this.data.array;
  29339. }
  29340. }
  29341. } );
  29342. Object.assign( InterleavedBufferAttribute.prototype, {
  29343. isInterleavedBufferAttribute: true,
  29344. setX: function ( index, x ) {
  29345. this.data.array[ index * this.data.stride + this.offset ] = x;
  29346. return this;
  29347. },
  29348. setY: function ( index, y ) {
  29349. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  29350. return this;
  29351. },
  29352. setZ: function ( index, z ) {
  29353. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  29354. return this;
  29355. },
  29356. setW: function ( index, w ) {
  29357. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  29358. return this;
  29359. },
  29360. getX: function ( index ) {
  29361. return this.data.array[ index * this.data.stride + this.offset ];
  29362. },
  29363. getY: function ( index ) {
  29364. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  29365. },
  29366. getZ: function ( index ) {
  29367. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  29368. },
  29369. getW: function ( index ) {
  29370. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  29371. },
  29372. setXY: function ( index, x, y ) {
  29373. index = index * this.data.stride + this.offset;
  29374. this.data.array[ index + 0 ] = x;
  29375. this.data.array[ index + 1 ] = y;
  29376. return this;
  29377. },
  29378. setXYZ: function ( index, x, y, z ) {
  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. return this;
  29384. },
  29385. setXYZW: function ( index, x, y, z, w ) {
  29386. index = index * this.data.stride + this.offset;
  29387. this.data.array[ index + 0 ] = x;
  29388. this.data.array[ index + 1 ] = y;
  29389. this.data.array[ index + 2 ] = z;
  29390. this.data.array[ index + 3 ] = w;
  29391. return this;
  29392. }
  29393. } );
  29394. /**
  29395. * @author benaadams / https://twitter.com/ben_a_adams
  29396. */
  29397. function InterleavedBuffer( array, stride ) {
  29398. this.uuid = _Math.generateUUID();
  29399. this.array = array;
  29400. this.stride = stride;
  29401. this.count = array !== undefined ? array.length / stride : 0;
  29402. this.dynamic = false;
  29403. this.updateRange = { offset: 0, count: - 1 };
  29404. this.onUploadCallback = function () {};
  29405. this.version = 0;
  29406. }
  29407. Object.defineProperty( InterleavedBuffer.prototype, 'needsUpdate', {
  29408. set: function ( value ) {
  29409. if ( value === true ) this.version ++;
  29410. }
  29411. } );
  29412. Object.assign( InterleavedBuffer.prototype, {
  29413. isInterleavedBuffer: true,
  29414. setArray: function ( array ) {
  29415. if ( Array.isArray( array ) ) {
  29416. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  29417. }
  29418. this.count = array !== undefined ? array.length / this.stride : 0;
  29419. this.array = array;
  29420. },
  29421. setDynamic: function ( value ) {
  29422. this.dynamic = value;
  29423. return this;
  29424. },
  29425. copy: function ( source ) {
  29426. this.array = new source.array.constructor( source.array );
  29427. this.count = source.count;
  29428. this.stride = source.stride;
  29429. this.dynamic = source.dynamic;
  29430. return this;
  29431. },
  29432. copyAt: function ( index1, attribute, index2 ) {
  29433. index1 *= this.stride;
  29434. index2 *= attribute.stride;
  29435. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  29436. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  29437. }
  29438. return this;
  29439. },
  29440. set: function ( value, offset ) {
  29441. if ( offset === undefined ) offset = 0;
  29442. this.array.set( value, offset );
  29443. return this;
  29444. },
  29445. clone: function () {
  29446. return new this.constructor().copy( this );
  29447. },
  29448. onUpload: function ( callback ) {
  29449. this.onUploadCallback = callback;
  29450. return this;
  29451. }
  29452. } );
  29453. /**
  29454. * @author benaadams / https://twitter.com/ben_a_adams
  29455. */
  29456. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  29457. InterleavedBuffer.call( this, array, stride );
  29458. this.meshPerAttribute = meshPerAttribute || 1;
  29459. }
  29460. InstancedInterleavedBuffer.prototype = Object.assign( Object.create( InterleavedBuffer.prototype ), {
  29461. constructor: InstancedInterleavedBuffer,
  29462. isInstancedInterleavedBuffer: true,
  29463. copy: function ( source ) {
  29464. InterleavedBuffer.prototype.copy.call( this, source );
  29465. this.meshPerAttribute = source.meshPerAttribute;
  29466. return this;
  29467. }
  29468. } );
  29469. /**
  29470. * @author benaadams / https://twitter.com/ben_a_adams
  29471. */
  29472. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  29473. BufferAttribute.call( this, array, itemSize );
  29474. this.meshPerAttribute = meshPerAttribute || 1;
  29475. }
  29476. InstancedBufferAttribute.prototype = Object.assign( Object.create( BufferAttribute.prototype ), {
  29477. constructor: InstancedBufferAttribute,
  29478. isInstancedBufferAttribute: true,
  29479. copy: function ( source ) {
  29480. BufferAttribute.prototype.copy.call( this, source );
  29481. this.meshPerAttribute = source.meshPerAttribute;
  29482. return this;
  29483. }
  29484. } );
  29485. /**
  29486. * @author mrdoob / http://mrdoob.com/
  29487. * @author bhouston / http://clara.io/
  29488. * @author stephomi / http://stephaneginier.com/
  29489. */
  29490. function Raycaster( origin, direction, near, far ) {
  29491. this.ray = new Ray( origin, direction );
  29492. // direction is assumed to be normalized (for accurate distance calculations)
  29493. this.near = near || 0;
  29494. this.far = far || Infinity;
  29495. this.params = {
  29496. Mesh: {},
  29497. Line: {},
  29498. LOD: {},
  29499. Points: { threshold: 1 },
  29500. Sprite: {}
  29501. };
  29502. Object.defineProperties( this.params, {
  29503. PointCloud: {
  29504. get: function () {
  29505. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  29506. return this.Points;
  29507. }
  29508. }
  29509. } );
  29510. }
  29511. function ascSort( a, b ) {
  29512. return a.distance - b.distance;
  29513. }
  29514. function intersectObject( object, raycaster, intersects, recursive ) {
  29515. if ( object.visible === false ) return;
  29516. object.raycast( raycaster, intersects );
  29517. if ( recursive === true ) {
  29518. var children = object.children;
  29519. for ( var i = 0, l = children.length; i < l; i ++ ) {
  29520. intersectObject( children[ i ], raycaster, intersects, true );
  29521. }
  29522. }
  29523. }
  29524. Object.assign( Raycaster.prototype, {
  29525. linePrecision: 1,
  29526. set: function ( origin, direction ) {
  29527. // direction is assumed to be normalized (for accurate distance calculations)
  29528. this.ray.set( origin, direction );
  29529. },
  29530. setFromCamera: function ( coords, camera ) {
  29531. if ( ( camera && camera.isPerspectiveCamera ) ) {
  29532. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  29533. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  29534. } else if ( ( camera && camera.isOrthographicCamera ) ) {
  29535. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  29536. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  29537. } else {
  29538. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  29539. }
  29540. },
  29541. intersectObject: function ( object, recursive ) {
  29542. var intersects = [];
  29543. intersectObject( object, this, intersects, recursive );
  29544. intersects.sort( ascSort );
  29545. return intersects;
  29546. },
  29547. intersectObjects: function ( objects, recursive ) {
  29548. var intersects = [];
  29549. if ( Array.isArray( objects ) === false ) {
  29550. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  29551. return intersects;
  29552. }
  29553. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  29554. intersectObject( objects[ i ], this, intersects, recursive );
  29555. }
  29556. intersects.sort( ascSort );
  29557. return intersects;
  29558. }
  29559. } );
  29560. /**
  29561. * @author alteredq / http://alteredqualia.com/
  29562. */
  29563. function Clock( autoStart ) {
  29564. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  29565. this.startTime = 0;
  29566. this.oldTime = 0;
  29567. this.elapsedTime = 0;
  29568. this.running = false;
  29569. }
  29570. Object.assign( Clock.prototype, {
  29571. start: function () {
  29572. this.startTime = ( typeof performance === 'undefined' ? Date : performance ).now(); // see #10732
  29573. this.oldTime = this.startTime;
  29574. this.elapsedTime = 0;
  29575. this.running = true;
  29576. },
  29577. stop: function () {
  29578. this.getElapsedTime();
  29579. this.running = false;
  29580. this.autoStart = false;
  29581. },
  29582. getElapsedTime: function () {
  29583. this.getDelta();
  29584. return this.elapsedTime;
  29585. },
  29586. getDelta: function () {
  29587. var diff = 0;
  29588. if ( this.autoStart && ! this.running ) {
  29589. this.start();
  29590. return 0;
  29591. }
  29592. if ( this.running ) {
  29593. var newTime = ( typeof performance === 'undefined' ? Date : performance ).now();
  29594. diff = ( newTime - this.oldTime ) / 1000;
  29595. this.oldTime = newTime;
  29596. this.elapsedTime += diff;
  29597. }
  29598. return diff;
  29599. }
  29600. } );
  29601. /**
  29602. * @author bhouston / http://clara.io
  29603. * @author WestLangley / http://github.com/WestLangley
  29604. *
  29605. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  29606. *
  29607. * The poles (phi) are at the positive and negative y axis.
  29608. * The equator starts at positive z.
  29609. */
  29610. function Spherical( radius, phi, theta ) {
  29611. this.radius = ( radius !== undefined ) ? radius : 1.0;
  29612. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  29613. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  29614. return this;
  29615. }
  29616. Object.assign( Spherical.prototype, {
  29617. set: function ( radius, phi, theta ) {
  29618. this.radius = radius;
  29619. this.phi = phi;
  29620. this.theta = theta;
  29621. return this;
  29622. },
  29623. clone: function () {
  29624. return new this.constructor().copy( this );
  29625. },
  29626. copy: function ( other ) {
  29627. this.radius = other.radius;
  29628. this.phi = other.phi;
  29629. this.theta = other.theta;
  29630. return this;
  29631. },
  29632. // restrict phi to be betwee EPS and PI-EPS
  29633. makeSafe: function () {
  29634. var EPS = 0.000001;
  29635. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  29636. return this;
  29637. },
  29638. setFromVector3: function ( vec3 ) {
  29639. this.radius = vec3.length();
  29640. if ( this.radius === 0 ) {
  29641. this.theta = 0;
  29642. this.phi = 0;
  29643. } else {
  29644. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  29645. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  29646. }
  29647. return this;
  29648. }
  29649. } );
  29650. /**
  29651. * @author Mugen87 / https://github.com/Mugen87
  29652. *
  29653. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  29654. *
  29655. */
  29656. function Cylindrical( radius, theta, y ) {
  29657. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  29658. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  29659. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  29660. return this;
  29661. }
  29662. Object.assign( Cylindrical.prototype, {
  29663. set: function ( radius, theta, y ) {
  29664. this.radius = radius;
  29665. this.theta = theta;
  29666. this.y = y;
  29667. return this;
  29668. },
  29669. clone: function () {
  29670. return new this.constructor().copy( this );
  29671. },
  29672. copy: function ( other ) {
  29673. this.radius = other.radius;
  29674. this.theta = other.theta;
  29675. this.y = other.y;
  29676. return this;
  29677. },
  29678. setFromVector3: function ( vec3 ) {
  29679. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  29680. this.theta = Math.atan2( vec3.x, vec3.z );
  29681. this.y = vec3.y;
  29682. return this;
  29683. }
  29684. } );
  29685. /**
  29686. * @author alteredq / http://alteredqualia.com/
  29687. */
  29688. function ImmediateRenderObject( material ) {
  29689. Object3D.call( this );
  29690. this.material = material;
  29691. this.render = function ( /* renderCallback */ ) {};
  29692. }
  29693. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  29694. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  29695. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  29696. /**
  29697. * @author mrdoob / http://mrdoob.com/
  29698. * @author WestLangley / http://github.com/WestLangley
  29699. */
  29700. function VertexNormalsHelper( object, size, hex, linewidth ) {
  29701. this.object = object;
  29702. this.size = ( size !== undefined ) ? size : 1;
  29703. var color = ( hex !== undefined ) ? hex : 0xff0000;
  29704. var width = ( linewidth !== undefined ) ? linewidth : 1;
  29705. //
  29706. var nNormals = 0;
  29707. var objGeometry = this.object.geometry;
  29708. if ( objGeometry && objGeometry.isGeometry ) {
  29709. nNormals = objGeometry.faces.length * 3;
  29710. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29711. nNormals = objGeometry.attributes.normal.count;
  29712. }
  29713. //
  29714. var geometry = new BufferGeometry();
  29715. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  29716. geometry.addAttribute( 'position', positions );
  29717. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  29718. //
  29719. this.matrixAutoUpdate = false;
  29720. this.update();
  29721. }
  29722. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  29723. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  29724. VertexNormalsHelper.prototype.update = ( function () {
  29725. var v1 = new Vector3();
  29726. var v2 = new Vector3();
  29727. var normalMatrix = new Matrix3();
  29728. return function update() {
  29729. var keys = [ 'a', 'b', 'c' ];
  29730. this.object.updateMatrixWorld( true );
  29731. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  29732. var matrixWorld = this.object.matrixWorld;
  29733. var position = this.geometry.attributes.position;
  29734. //
  29735. var objGeometry = this.object.geometry;
  29736. if ( objGeometry && objGeometry.isGeometry ) {
  29737. var vertices = objGeometry.vertices;
  29738. var faces = objGeometry.faces;
  29739. var idx = 0;
  29740. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  29741. var face = faces[ i ];
  29742. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  29743. var vertex = vertices[ face[ keys[ j ] ] ];
  29744. var normal = face.vertexNormals[ j ];
  29745. v1.copy( vertex ).applyMatrix4( matrixWorld );
  29746. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29747. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29748. idx = idx + 1;
  29749. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29750. idx = idx + 1;
  29751. }
  29752. }
  29753. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  29754. var objPos = objGeometry.attributes.position;
  29755. var objNorm = objGeometry.attributes.normal;
  29756. var idx = 0;
  29757. // for simplicity, ignore index and drawcalls, and render every normal
  29758. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  29759. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  29760. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  29761. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  29762. position.setXYZ( idx, v1.x, v1.y, v1.z );
  29763. idx = idx + 1;
  29764. position.setXYZ( idx, v2.x, v2.y, v2.z );
  29765. idx = idx + 1;
  29766. }
  29767. }
  29768. position.needsUpdate = true;
  29769. };
  29770. }() );
  29771. /**
  29772. * @author alteredq / http://alteredqualia.com/
  29773. * @author mrdoob / http://mrdoob.com/
  29774. * @author WestLangley / http://github.com/WestLangley
  29775. */
  29776. function SpotLightHelper( light, color ) {
  29777. Object3D.call( this );
  29778. this.light = light;
  29779. this.light.updateMatrixWorld();
  29780. this.matrix = light.matrixWorld;
  29781. this.matrixAutoUpdate = false;
  29782. this.color = color;
  29783. var geometry = new BufferGeometry();
  29784. var positions = [
  29785. 0, 0, 0, 0, 0, 1,
  29786. 0, 0, 0, 1, 0, 1,
  29787. 0, 0, 0, - 1, 0, 1,
  29788. 0, 0, 0, 0, 1, 1,
  29789. 0, 0, 0, 0, - 1, 1
  29790. ];
  29791. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  29792. var p1 = ( i / l ) * Math.PI * 2;
  29793. var p2 = ( j / l ) * Math.PI * 2;
  29794. positions.push(
  29795. Math.cos( p1 ), Math.sin( p1 ), 1,
  29796. Math.cos( p2 ), Math.sin( p2 ), 1
  29797. );
  29798. }
  29799. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  29800. var material = new LineBasicMaterial( { fog: false } );
  29801. this.cone = new LineSegments( geometry, material );
  29802. this.add( this.cone );
  29803. this.update();
  29804. }
  29805. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  29806. SpotLightHelper.prototype.constructor = SpotLightHelper;
  29807. SpotLightHelper.prototype.dispose = function () {
  29808. this.cone.geometry.dispose();
  29809. this.cone.material.dispose();
  29810. };
  29811. SpotLightHelper.prototype.update = function () {
  29812. var vector = new Vector3();
  29813. var vector2 = new Vector3();
  29814. return function update() {
  29815. this.light.updateMatrixWorld();
  29816. var coneLength = this.light.distance ? this.light.distance : 1000;
  29817. var coneWidth = coneLength * Math.tan( this.light.angle );
  29818. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  29819. vector.setFromMatrixPosition( this.light.matrixWorld );
  29820. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  29821. this.cone.lookAt( vector2.sub( vector ) );
  29822. if ( this.color !== undefined ) {
  29823. this.cone.material.color.set( this.color );
  29824. } else {
  29825. this.cone.material.color.copy( this.light.color );
  29826. }
  29827. };
  29828. }();
  29829. /**
  29830. * @author Sean Griffin / http://twitter.com/sgrif
  29831. * @author Michael Guerrero / http://realitymeltdown.com
  29832. * @author mrdoob / http://mrdoob.com/
  29833. * @author ikerr / http://verold.com
  29834. * @author Mugen87 / https://github.com/Mugen87
  29835. */
  29836. function getBoneList( object ) {
  29837. var boneList = [];
  29838. if ( object && object.isBone ) {
  29839. boneList.push( object );
  29840. }
  29841. for ( var i = 0; i < object.children.length; i ++ ) {
  29842. boneList.push.apply( boneList, getBoneList( object.children[ i ] ) );
  29843. }
  29844. return boneList;
  29845. }
  29846. function SkeletonHelper( object ) {
  29847. var bones = getBoneList( object );
  29848. var geometry = new BufferGeometry();
  29849. var vertices = [];
  29850. var colors = [];
  29851. var color1 = new Color( 0, 0, 1 );
  29852. var color2 = new Color( 0, 1, 0 );
  29853. for ( var i = 0; i < bones.length; i ++ ) {
  29854. var bone = bones[ i ];
  29855. if ( bone.parent && bone.parent.isBone ) {
  29856. vertices.push( 0, 0, 0 );
  29857. vertices.push( 0, 0, 0 );
  29858. colors.push( color1.r, color1.g, color1.b );
  29859. colors.push( color2.r, color2.g, color2.b );
  29860. }
  29861. }
  29862. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29863. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29864. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  29865. LineSegments.call( this, geometry, material );
  29866. this.root = object;
  29867. this.bones = bones;
  29868. this.matrix = object.matrixWorld;
  29869. this.matrixAutoUpdate = false;
  29870. }
  29871. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  29872. SkeletonHelper.prototype.constructor = SkeletonHelper;
  29873. SkeletonHelper.prototype.updateMatrixWorld = function () {
  29874. var vector = new Vector3();
  29875. var boneMatrix = new Matrix4();
  29876. var matrixWorldInv = new Matrix4();
  29877. return function updateMatrixWorld( force ) {
  29878. var bones = this.bones;
  29879. var geometry = this.geometry;
  29880. var position = geometry.getAttribute( 'position' );
  29881. matrixWorldInv.getInverse( this.root.matrixWorld );
  29882. for ( var i = 0, j = 0; i < bones.length; i ++ ) {
  29883. var bone = bones[ i ];
  29884. if ( bone.parent && bone.parent.isBone ) {
  29885. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  29886. vector.setFromMatrixPosition( boneMatrix );
  29887. position.setXYZ( j, vector.x, vector.y, vector.z );
  29888. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  29889. vector.setFromMatrixPosition( boneMatrix );
  29890. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  29891. j += 2;
  29892. }
  29893. }
  29894. geometry.getAttribute( 'position' ).needsUpdate = true;
  29895. Object3D.prototype.updateMatrixWorld.call( this, force );
  29896. };
  29897. }();
  29898. /**
  29899. * @author alteredq / http://alteredqualia.com/
  29900. * @author mrdoob / http://mrdoob.com/
  29901. */
  29902. function PointLightHelper( light, sphereSize, color ) {
  29903. this.light = light;
  29904. this.light.updateMatrixWorld();
  29905. this.color = color;
  29906. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  29907. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  29908. Mesh.call( this, geometry, material );
  29909. this.matrix = this.light.matrixWorld;
  29910. this.matrixAutoUpdate = false;
  29911. this.update();
  29912. /*
  29913. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  29914. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  29915. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  29916. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  29917. var d = light.distance;
  29918. if ( d === 0.0 ) {
  29919. this.lightDistance.visible = false;
  29920. } else {
  29921. this.lightDistance.scale.set( d, d, d );
  29922. }
  29923. this.add( this.lightDistance );
  29924. */
  29925. }
  29926. PointLightHelper.prototype = Object.create( Mesh.prototype );
  29927. PointLightHelper.prototype.constructor = PointLightHelper;
  29928. PointLightHelper.prototype.dispose = function () {
  29929. this.geometry.dispose();
  29930. this.material.dispose();
  29931. };
  29932. PointLightHelper.prototype.update = function () {
  29933. if ( this.color !== undefined ) {
  29934. this.material.color.set( this.color );
  29935. } else {
  29936. this.material.color.copy( this.light.color );
  29937. }
  29938. /*
  29939. var d = this.light.distance;
  29940. if ( d === 0.0 ) {
  29941. this.lightDistance.visible = false;
  29942. } else {
  29943. this.lightDistance.visible = true;
  29944. this.lightDistance.scale.set( d, d, d );
  29945. }
  29946. */
  29947. };
  29948. /**
  29949. * @author abelnation / http://github.com/abelnation
  29950. * @author Mugen87 / http://github.com/Mugen87
  29951. * @author WestLangley / http://github.com/WestLangley
  29952. */
  29953. function RectAreaLightHelper( light, color ) {
  29954. Object3D.call( this );
  29955. this.light = light;
  29956. this.light.updateMatrixWorld();
  29957. this.matrix = light.matrixWorld;
  29958. this.matrixAutoUpdate = false;
  29959. this.color = color;
  29960. var material = new LineBasicMaterial( { fog: false } );
  29961. var geometry = new BufferGeometry();
  29962. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 5 * 3 ), 3 ) );
  29963. this.line = new Line( geometry, material );
  29964. this.add( this.line );
  29965. this.update();
  29966. }
  29967. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  29968. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  29969. RectAreaLightHelper.prototype.dispose = function () {
  29970. this.children[ 0 ].geometry.dispose();
  29971. this.children[ 0 ].material.dispose();
  29972. };
  29973. RectAreaLightHelper.prototype.update = function () {
  29974. // calculate new dimensions of the helper
  29975. var hx = this.light.width * 0.5;
  29976. var hy = this.light.height * 0.5;
  29977. var position = this.line.geometry.attributes.position;
  29978. var array = position.array;
  29979. // update vertices
  29980. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  29981. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  29982. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  29983. array[ 9 ] = - hx; array[ 10 ] = - hy; array[ 11 ] = 0;
  29984. array[ 12 ] = hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  29985. position.needsUpdate = true;
  29986. if ( this.color !== undefined ) {
  29987. this.line.material.color.set( this.color );
  29988. } else {
  29989. this.line.material.color.copy( this.light.color );
  29990. }
  29991. };
  29992. /**
  29993. * @author alteredq / http://alteredqualia.com/
  29994. * @author mrdoob / http://mrdoob.com/
  29995. * @author Mugen87 / https://github.com/Mugen87
  29996. */
  29997. function HemisphereLightHelper( light, size, color ) {
  29998. Object3D.call( this );
  29999. this.light = light;
  30000. this.light.updateMatrixWorld();
  30001. this.matrix = light.matrixWorld;
  30002. this.matrixAutoUpdate = false;
  30003. this.color = color;
  30004. var geometry = new OctahedronBufferGeometry( size );
  30005. geometry.rotateY( Math.PI * 0.5 );
  30006. this.material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  30007. if ( this.color === undefined ) this.material.vertexColors = VertexColors;
  30008. var position = geometry.getAttribute( 'position' );
  30009. var colors = new Float32Array( position.count * 3 );
  30010. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  30011. this.add( new Mesh( geometry, this.material ) );
  30012. this.update();
  30013. }
  30014. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  30015. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  30016. HemisphereLightHelper.prototype.dispose = function () {
  30017. this.children[ 0 ].geometry.dispose();
  30018. this.children[ 0 ].material.dispose();
  30019. };
  30020. HemisphereLightHelper.prototype.update = function () {
  30021. var vector = new Vector3();
  30022. var color1 = new Color();
  30023. var color2 = new Color();
  30024. return function update() {
  30025. var mesh = this.children[ 0 ];
  30026. if ( this.color !== undefined ) {
  30027. this.material.color.set( this.color );
  30028. } else {
  30029. var colors = mesh.geometry.getAttribute( 'color' );
  30030. color1.copy( this.light.color );
  30031. color2.copy( this.light.groundColor );
  30032. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  30033. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  30034. colors.setXYZ( i, color.r, color.g, color.b );
  30035. }
  30036. colors.needsUpdate = true;
  30037. }
  30038. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  30039. };
  30040. }();
  30041. /**
  30042. * @author mrdoob / http://mrdoob.com/
  30043. */
  30044. function GridHelper( size, divisions, color1, color2 ) {
  30045. size = size || 10;
  30046. divisions = divisions || 10;
  30047. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30048. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30049. var center = divisions / 2;
  30050. var step = size / divisions;
  30051. var halfSize = size / 2;
  30052. var vertices = [], colors = [];
  30053. for ( var i = 0, j = 0, k = - halfSize; i <= divisions; i ++, k += step ) {
  30054. vertices.push( - halfSize, 0, k, halfSize, 0, k );
  30055. vertices.push( k, 0, - halfSize, k, 0, halfSize );
  30056. var color = i === center ? color1 : color2;
  30057. color.toArray( colors, j ); j += 3;
  30058. color.toArray( colors, j ); j += 3;
  30059. color.toArray( colors, j ); j += 3;
  30060. color.toArray( colors, j ); j += 3;
  30061. }
  30062. var geometry = new BufferGeometry();
  30063. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30064. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30065. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30066. LineSegments.call( this, geometry, material );
  30067. }
  30068. GridHelper.prototype = Object.create( LineSegments.prototype );
  30069. GridHelper.prototype.constructor = GridHelper;
  30070. /**
  30071. * @author mrdoob / http://mrdoob.com/
  30072. * @author Mugen87 / http://github.com/Mugen87
  30073. * @author Hectate / http://www.github.com/Hectate
  30074. */
  30075. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  30076. radius = radius || 10;
  30077. radials = radials || 16;
  30078. circles = circles || 8;
  30079. divisions = divisions || 64;
  30080. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  30081. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  30082. var vertices = [];
  30083. var colors = [];
  30084. var x, z;
  30085. var v, i, j, r, color;
  30086. // create the radials
  30087. for ( i = 0; i <= radials; i ++ ) {
  30088. v = ( i / radials ) * ( Math.PI * 2 );
  30089. x = Math.sin( v ) * radius;
  30090. z = Math.cos( v ) * radius;
  30091. vertices.push( 0, 0, 0 );
  30092. vertices.push( x, 0, z );
  30093. color = ( i & 1 ) ? color1 : color2;
  30094. colors.push( color.r, color.g, color.b );
  30095. colors.push( color.r, color.g, color.b );
  30096. }
  30097. // create the circles
  30098. for ( i = 0; i <= circles; i ++ ) {
  30099. color = ( i & 1 ) ? color1 : color2;
  30100. r = radius - ( radius / circles * i );
  30101. for ( j = 0; j < divisions; j ++ ) {
  30102. // first vertex
  30103. v = ( j / divisions ) * ( Math.PI * 2 );
  30104. x = Math.sin( v ) * r;
  30105. z = Math.cos( v ) * r;
  30106. vertices.push( x, 0, z );
  30107. colors.push( color.r, color.g, color.b );
  30108. // second vertex
  30109. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  30110. x = Math.sin( v ) * r;
  30111. z = Math.cos( v ) * r;
  30112. vertices.push( x, 0, z );
  30113. colors.push( color.r, color.g, color.b );
  30114. }
  30115. }
  30116. var geometry = new BufferGeometry();
  30117. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30118. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30119. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30120. LineSegments.call( this, geometry, material );
  30121. }
  30122. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  30123. PolarGridHelper.prototype.constructor = PolarGridHelper;
  30124. /**
  30125. * @author mrdoob / http://mrdoob.com/
  30126. * @author WestLangley / http://github.com/WestLangley
  30127. */
  30128. function FaceNormalsHelper( object, size, hex, linewidth ) {
  30129. // FaceNormalsHelper only supports THREE.Geometry
  30130. this.object = object;
  30131. this.size = ( size !== undefined ) ? size : 1;
  30132. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30133. var width = ( linewidth !== undefined ) ? linewidth : 1;
  30134. //
  30135. var nNormals = 0;
  30136. var objGeometry = this.object.geometry;
  30137. if ( objGeometry && objGeometry.isGeometry ) {
  30138. nNormals = objGeometry.faces.length;
  30139. } else {
  30140. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  30141. }
  30142. //
  30143. var geometry = new BufferGeometry();
  30144. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  30145. geometry.addAttribute( 'position', positions );
  30146. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  30147. //
  30148. this.matrixAutoUpdate = false;
  30149. this.update();
  30150. }
  30151. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  30152. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  30153. FaceNormalsHelper.prototype.update = ( function () {
  30154. var v1 = new Vector3();
  30155. var v2 = new Vector3();
  30156. var normalMatrix = new Matrix3();
  30157. return function update() {
  30158. this.object.updateMatrixWorld( true );
  30159. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  30160. var matrixWorld = this.object.matrixWorld;
  30161. var position = this.geometry.attributes.position;
  30162. //
  30163. var objGeometry = this.object.geometry;
  30164. var vertices = objGeometry.vertices;
  30165. var faces = objGeometry.faces;
  30166. var idx = 0;
  30167. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  30168. var face = faces[ i ];
  30169. var normal = face.normal;
  30170. v1.copy( vertices[ face.a ] )
  30171. .add( vertices[ face.b ] )
  30172. .add( vertices[ face.c ] )
  30173. .divideScalar( 3 )
  30174. .applyMatrix4( matrixWorld );
  30175. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  30176. position.setXYZ( idx, v1.x, v1.y, v1.z );
  30177. idx = idx + 1;
  30178. position.setXYZ( idx, v2.x, v2.y, v2.z );
  30179. idx = idx + 1;
  30180. }
  30181. position.needsUpdate = true;
  30182. };
  30183. }() );
  30184. /**
  30185. * @author alteredq / http://alteredqualia.com/
  30186. * @author mrdoob / http://mrdoob.com/
  30187. * @author WestLangley / http://github.com/WestLangley
  30188. */
  30189. function DirectionalLightHelper( light, size, color ) {
  30190. Object3D.call( this );
  30191. this.light = light;
  30192. this.light.updateMatrixWorld();
  30193. this.matrix = light.matrixWorld;
  30194. this.matrixAutoUpdate = false;
  30195. this.color = color;
  30196. if ( size === undefined ) size = 1;
  30197. var geometry = new BufferGeometry();
  30198. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  30199. - size, size, 0,
  30200. size, size, 0,
  30201. size, - size, 0,
  30202. - size, - size, 0,
  30203. - size, size, 0
  30204. ], 3 ) );
  30205. var material = new LineBasicMaterial( { fog: false } );
  30206. this.lightPlane = new Line( geometry, material );
  30207. this.add( this.lightPlane );
  30208. geometry = new BufferGeometry();
  30209. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  30210. this.targetLine = new Line( geometry, material );
  30211. this.add( this.targetLine );
  30212. this.update();
  30213. }
  30214. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  30215. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  30216. DirectionalLightHelper.prototype.dispose = function () {
  30217. this.lightPlane.geometry.dispose();
  30218. this.lightPlane.material.dispose();
  30219. this.targetLine.geometry.dispose();
  30220. this.targetLine.material.dispose();
  30221. };
  30222. DirectionalLightHelper.prototype.update = function () {
  30223. var v1 = new Vector3();
  30224. var v2 = new Vector3();
  30225. var v3 = new Vector3();
  30226. return function update() {
  30227. v1.setFromMatrixPosition( this.light.matrixWorld );
  30228. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  30229. v3.subVectors( v2, v1 );
  30230. this.lightPlane.lookAt( v3 );
  30231. if ( this.color !== undefined ) {
  30232. this.lightPlane.material.color.set( this.color );
  30233. this.targetLine.material.color.set( this.color );
  30234. } else {
  30235. this.lightPlane.material.color.copy( this.light.color );
  30236. this.targetLine.material.color.copy( this.light.color );
  30237. }
  30238. this.targetLine.lookAt( v3 );
  30239. this.targetLine.scale.z = v3.length();
  30240. };
  30241. }();
  30242. /**
  30243. * @author alteredq / http://alteredqualia.com/
  30244. * @author Mugen87 / https://github.com/Mugen87
  30245. *
  30246. * - shows frustum, line of sight and up of the camera
  30247. * - suitable for fast updates
  30248. * - based on frustum visualization in lightgl.js shadowmap example
  30249. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  30250. */
  30251. function CameraHelper( camera ) {
  30252. var geometry = new BufferGeometry();
  30253. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  30254. var vertices = [];
  30255. var colors = [];
  30256. var pointMap = {};
  30257. // colors
  30258. var colorFrustum = new Color( 0xffaa00 );
  30259. var colorCone = new Color( 0xff0000 );
  30260. var colorUp = new Color( 0x00aaff );
  30261. var colorTarget = new Color( 0xffffff );
  30262. var colorCross = new Color( 0x333333 );
  30263. // near
  30264. addLine( 'n1', 'n2', colorFrustum );
  30265. addLine( 'n2', 'n4', colorFrustum );
  30266. addLine( 'n4', 'n3', colorFrustum );
  30267. addLine( 'n3', 'n1', colorFrustum );
  30268. // far
  30269. addLine( 'f1', 'f2', colorFrustum );
  30270. addLine( 'f2', 'f4', colorFrustum );
  30271. addLine( 'f4', 'f3', colorFrustum );
  30272. addLine( 'f3', 'f1', colorFrustum );
  30273. // sides
  30274. addLine( 'n1', 'f1', colorFrustum );
  30275. addLine( 'n2', 'f2', colorFrustum );
  30276. addLine( 'n3', 'f3', colorFrustum );
  30277. addLine( 'n4', 'f4', colorFrustum );
  30278. // cone
  30279. addLine( 'p', 'n1', colorCone );
  30280. addLine( 'p', 'n2', colorCone );
  30281. addLine( 'p', 'n3', colorCone );
  30282. addLine( 'p', 'n4', colorCone );
  30283. // up
  30284. addLine( 'u1', 'u2', colorUp );
  30285. addLine( 'u2', 'u3', colorUp );
  30286. addLine( 'u3', 'u1', colorUp );
  30287. // target
  30288. addLine( 'c', 't', colorTarget );
  30289. addLine( 'p', 'c', colorCross );
  30290. // cross
  30291. addLine( 'cn1', 'cn2', colorCross );
  30292. addLine( 'cn3', 'cn4', colorCross );
  30293. addLine( 'cf1', 'cf2', colorCross );
  30294. addLine( 'cf3', 'cf4', colorCross );
  30295. function addLine( a, b, color ) {
  30296. addPoint( a, color );
  30297. addPoint( b, color );
  30298. }
  30299. function addPoint( id, color ) {
  30300. vertices.push( 0, 0, 0 );
  30301. colors.push( color.r, color.g, color.b );
  30302. if ( pointMap[ id ] === undefined ) {
  30303. pointMap[ id ] = [];
  30304. }
  30305. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  30306. }
  30307. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30308. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30309. LineSegments.call( this, geometry, material );
  30310. this.camera = camera;
  30311. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  30312. this.matrix = camera.matrixWorld;
  30313. this.matrixAutoUpdate = false;
  30314. this.pointMap = pointMap;
  30315. this.update();
  30316. }
  30317. CameraHelper.prototype = Object.create( LineSegments.prototype );
  30318. CameraHelper.prototype.constructor = CameraHelper;
  30319. CameraHelper.prototype.update = function () {
  30320. var geometry, pointMap;
  30321. var vector = new Vector3();
  30322. var camera = new Camera();
  30323. function setPoint( point, x, y, z ) {
  30324. vector.set( x, y, z ).unproject( camera );
  30325. var points = pointMap[ point ];
  30326. if ( points !== undefined ) {
  30327. var position = geometry.getAttribute( 'position' );
  30328. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30329. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  30330. }
  30331. }
  30332. }
  30333. return function update() {
  30334. geometry = this.geometry;
  30335. pointMap = this.pointMap;
  30336. var w = 1, h = 1;
  30337. // we need just camera projection matrix
  30338. // world matrix must be identity
  30339. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  30340. // center / target
  30341. setPoint( 'c', 0, 0, - 1 );
  30342. setPoint( 't', 0, 0, 1 );
  30343. // near
  30344. setPoint( 'n1', - w, - h, - 1 );
  30345. setPoint( 'n2', w, - h, - 1 );
  30346. setPoint( 'n3', - w, h, - 1 );
  30347. setPoint( 'n4', w, h, - 1 );
  30348. // far
  30349. setPoint( 'f1', - w, - h, 1 );
  30350. setPoint( 'f2', w, - h, 1 );
  30351. setPoint( 'f3', - w, h, 1 );
  30352. setPoint( 'f4', w, h, 1 );
  30353. // up
  30354. setPoint( 'u1', w * 0.7, h * 1.1, - 1 );
  30355. setPoint( 'u2', - w * 0.7, h * 1.1, - 1 );
  30356. setPoint( 'u3', 0, h * 2, - 1 );
  30357. // cross
  30358. setPoint( 'cf1', - w, 0, 1 );
  30359. setPoint( 'cf2', w, 0, 1 );
  30360. setPoint( 'cf3', 0, - h, 1 );
  30361. setPoint( 'cf4', 0, h, 1 );
  30362. setPoint( 'cn1', - w, 0, - 1 );
  30363. setPoint( 'cn2', w, 0, - 1 );
  30364. setPoint( 'cn3', 0, - h, - 1 );
  30365. setPoint( 'cn4', 0, h, - 1 );
  30366. geometry.getAttribute( 'position' ).needsUpdate = true;
  30367. };
  30368. }();
  30369. /**
  30370. * @author mrdoob / http://mrdoob.com/
  30371. * @author Mugen87 / http://github.com/Mugen87
  30372. */
  30373. function BoxHelper( object, color ) {
  30374. this.object = object;
  30375. if ( color === undefined ) color = 0xffff00;
  30376. 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 ] );
  30377. var positions = new Float32Array( 8 * 3 );
  30378. var geometry = new BufferGeometry();
  30379. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30380. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  30381. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30382. this.matrixAutoUpdate = false;
  30383. this.update();
  30384. }
  30385. BoxHelper.prototype = Object.create( LineSegments.prototype );
  30386. BoxHelper.prototype.constructor = BoxHelper;
  30387. BoxHelper.prototype.update = ( function () {
  30388. var box = new Box3();
  30389. return function update( object ) {
  30390. if ( object !== undefined ) {
  30391. console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );
  30392. }
  30393. if ( this.object !== undefined ) {
  30394. box.setFromObject( this.object );
  30395. }
  30396. if ( box.isEmpty() ) return;
  30397. var min = box.min;
  30398. var max = box.max;
  30399. /*
  30400. 5____4
  30401. 1/___0/|
  30402. | 6__|_7
  30403. 2/___3/
  30404. 0: max.x, max.y, max.z
  30405. 1: min.x, max.y, max.z
  30406. 2: min.x, min.y, max.z
  30407. 3: max.x, min.y, max.z
  30408. 4: max.x, max.y, min.z
  30409. 5: min.x, max.y, min.z
  30410. 6: min.x, min.y, min.z
  30411. 7: max.x, min.y, min.z
  30412. */
  30413. var position = this.geometry.attributes.position;
  30414. var array = position.array;
  30415. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  30416. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  30417. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  30418. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  30419. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  30420. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  30421. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  30422. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  30423. position.needsUpdate = true;
  30424. this.geometry.computeBoundingSphere();
  30425. };
  30426. } )();
  30427. BoxHelper.prototype.setFromObject = function ( object ) {
  30428. this.object = object;
  30429. this.update();
  30430. return this;
  30431. };
  30432. /**
  30433. * @author WestLangley / http://github.com/WestLangley
  30434. */
  30435. function Box3Helper( box, hex ) {
  30436. this.type = 'Box3Helper';
  30437. this.box = box;
  30438. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30439. 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 ] );
  30440. 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 ];
  30441. var geometry = new BufferGeometry();
  30442. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  30443. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30444. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30445. this.geometry.computeBoundingSphere();
  30446. }
  30447. Box3Helper.prototype = Object.create( LineSegments.prototype );
  30448. Box3Helper.prototype.constructor = Box3Helper;
  30449. Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  30450. var box = this.box;
  30451. if ( box.isEmpty() ) return;
  30452. box.getCenter( this.position );
  30453. box.getSize( this.scale );
  30454. this.scale.multiplyScalar( 0.5 );
  30455. Object3D.prototype.updateMatrixWorld.call( this, force );
  30456. };
  30457. /**
  30458. * @author WestLangley / http://github.com/WestLangley
  30459. */
  30460. function PlaneHelper( plane, size, hex ) {
  30461. this.type = 'PlaneHelper';
  30462. this.plane = plane;
  30463. this.size = ( size === undefined ) ? 1 : size;
  30464. var color = ( hex !== undefined ) ? hex : 0xffff00;
  30465. 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 ];
  30466. var geometry = new BufferGeometry();
  30467. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  30468. geometry.computeBoundingSphere();
  30469. Line.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  30470. //
  30471. var positions2 = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, 1, 1, - 1, - 1, 1, 1, - 1, 1 ];
  30472. var geometry2 = new BufferGeometry();
  30473. geometry2.addAttribute( 'position', new Float32BufferAttribute( positions2, 3 ) );
  30474. geometry2.computeBoundingSphere();
  30475. this.add( new Mesh( geometry2, new MeshBasicMaterial( { color: color, opacity: 0.2, transparent: true, depthWrite: false } ) ) );
  30476. }
  30477. PlaneHelper.prototype = Object.create( Line.prototype );
  30478. PlaneHelper.prototype.constructor = PlaneHelper;
  30479. PlaneHelper.prototype.updateMatrixWorld = function ( force ) {
  30480. var scale = - this.plane.constant;
  30481. if ( Math.abs( scale ) < 1e-8 ) scale = 1e-8; // sign does not matter
  30482. this.scale.set( 0.5 * this.size, 0.5 * this.size, scale );
  30483. this.lookAt( this.plane.normal );
  30484. Object3D.prototype.updateMatrixWorld.call( this, force );
  30485. };
  30486. /**
  30487. * @author WestLangley / http://github.com/WestLangley
  30488. * @author zz85 / http://github.com/zz85
  30489. * @author bhouston / http://clara.io
  30490. *
  30491. * Creates an arrow for visualizing directions
  30492. *
  30493. * Parameters:
  30494. * dir - Vector3
  30495. * origin - Vector3
  30496. * length - Number
  30497. * color - color in hex value
  30498. * headLength - Number
  30499. * headWidth - Number
  30500. */
  30501. var lineGeometry;
  30502. var coneGeometry;
  30503. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  30504. // dir is assumed to be normalized
  30505. Object3D.call( this );
  30506. if ( color === undefined ) color = 0xffff00;
  30507. if ( length === undefined ) length = 1;
  30508. if ( headLength === undefined ) headLength = 0.2 * length;
  30509. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30510. if ( lineGeometry === undefined ) {
  30511. lineGeometry = new BufferGeometry();
  30512. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  30513. coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  30514. coneGeometry.translate( 0, - 0.5, 0 );
  30515. }
  30516. this.position.copy( origin );
  30517. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  30518. this.line.matrixAutoUpdate = false;
  30519. this.add( this.line );
  30520. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  30521. this.cone.matrixAutoUpdate = false;
  30522. this.add( this.cone );
  30523. this.setDirection( dir );
  30524. this.setLength( length, headLength, headWidth );
  30525. }
  30526. ArrowHelper.prototype = Object.create( Object3D.prototype );
  30527. ArrowHelper.prototype.constructor = ArrowHelper;
  30528. ArrowHelper.prototype.setDirection = ( function () {
  30529. var axis = new Vector3();
  30530. var radians;
  30531. return function setDirection( dir ) {
  30532. // dir is assumed to be normalized
  30533. if ( dir.y > 0.99999 ) {
  30534. this.quaternion.set( 0, 0, 0, 1 );
  30535. } else if ( dir.y < - 0.99999 ) {
  30536. this.quaternion.set( 1, 0, 0, 0 );
  30537. } else {
  30538. axis.set( dir.z, 0, - dir.x ).normalize();
  30539. radians = Math.acos( dir.y );
  30540. this.quaternion.setFromAxisAngle( axis, radians );
  30541. }
  30542. };
  30543. }() );
  30544. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  30545. if ( headLength === undefined ) headLength = 0.2 * length;
  30546. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  30547. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  30548. this.line.updateMatrix();
  30549. this.cone.scale.set( headWidth, headLength, headWidth );
  30550. this.cone.position.y = length;
  30551. this.cone.updateMatrix();
  30552. };
  30553. ArrowHelper.prototype.setColor = function ( color ) {
  30554. this.line.material.color.copy( color );
  30555. this.cone.material.color.copy( color );
  30556. };
  30557. /**
  30558. * @author sroucheray / http://sroucheray.org/
  30559. * @author mrdoob / http://mrdoob.com/
  30560. */
  30561. function AxesHelper( size ) {
  30562. size = size || 1;
  30563. var vertices = [
  30564. 0, 0, 0, size, 0, 0,
  30565. 0, 0, 0, 0, size, 0,
  30566. 0, 0, 0, 0, 0, size
  30567. ];
  30568. var colors = [
  30569. 1, 0, 0, 1, 0.6, 0,
  30570. 0, 1, 0, 0.6, 1, 0,
  30571. 0, 0, 1, 0, 0.6, 1
  30572. ];
  30573. var geometry = new BufferGeometry();
  30574. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  30575. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  30576. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  30577. LineSegments.call( this, geometry, material );
  30578. }
  30579. AxesHelper.prototype = Object.create( LineSegments.prototype );
  30580. AxesHelper.prototype.constructor = AxesHelper;
  30581. /**
  30582. * @author alteredq / http://alteredqualia.com/
  30583. */
  30584. var SceneUtils = {
  30585. createMultiMaterialObject: function ( geometry, materials ) {
  30586. var group = new Group();
  30587. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  30588. group.add( new Mesh( geometry, materials[ i ] ) );
  30589. }
  30590. return group;
  30591. },
  30592. detach: function ( child, parent, scene ) {
  30593. child.applyMatrix( parent.matrixWorld );
  30594. parent.remove( child );
  30595. scene.add( child );
  30596. },
  30597. attach: function ( child, scene, parent ) {
  30598. child.applyMatrix( new Matrix4().getInverse( parent.matrixWorld ) );
  30599. scene.remove( child );
  30600. parent.add( child );
  30601. }
  30602. };
  30603. /**
  30604. * @author mrdoob / http://mrdoob.com/
  30605. */
  30606. function Face4( a, b, c, d, normal, color, materialIndex ) {
  30607. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  30608. return new Face3( a, b, c, normal, color, materialIndex );
  30609. }
  30610. var LineStrip = 0;
  30611. var LinePieces = 1;
  30612. function MeshFaceMaterial( materials ) {
  30613. console.warn( 'THREE.MeshFaceMaterial has been removed. Use an Array instead.' );
  30614. return materials;
  30615. }
  30616. function MultiMaterial( materials ) {
  30617. if ( materials === undefined ) materials = [];
  30618. console.warn( 'THREE.MultiMaterial has been removed. Use an Array instead.' );
  30619. materials.isMultiMaterial = true;
  30620. materials.materials = materials;
  30621. materials.clone = function () {
  30622. return materials.slice();
  30623. };
  30624. return materials;
  30625. }
  30626. function PointCloud( geometry, material ) {
  30627. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  30628. return new Points( geometry, material );
  30629. }
  30630. function Particle( material ) {
  30631. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  30632. return new Sprite( material );
  30633. }
  30634. function ParticleSystem( geometry, material ) {
  30635. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  30636. return new Points( geometry, material );
  30637. }
  30638. function PointCloudMaterial( parameters ) {
  30639. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  30640. return new PointsMaterial( parameters );
  30641. }
  30642. function ParticleBasicMaterial( parameters ) {
  30643. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  30644. return new PointsMaterial( parameters );
  30645. }
  30646. function ParticleSystemMaterial( parameters ) {
  30647. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  30648. return new PointsMaterial( parameters );
  30649. }
  30650. function Vertex( x, y, z ) {
  30651. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  30652. return new Vector3( x, y, z );
  30653. }
  30654. //
  30655. function DynamicBufferAttribute( array, itemSize ) {
  30656. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  30657. return new BufferAttribute( array, itemSize ).setDynamic( true );
  30658. }
  30659. function Int8Attribute( array, itemSize ) {
  30660. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  30661. return new Int8BufferAttribute( array, itemSize );
  30662. }
  30663. function Uint8Attribute( array, itemSize ) {
  30664. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  30665. return new Uint8BufferAttribute( array, itemSize );
  30666. }
  30667. function Uint8ClampedAttribute( array, itemSize ) {
  30668. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  30669. return new Uint8ClampedBufferAttribute( array, itemSize );
  30670. }
  30671. function Int16Attribute( array, itemSize ) {
  30672. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  30673. return new Int16BufferAttribute( array, itemSize );
  30674. }
  30675. function Uint16Attribute( array, itemSize ) {
  30676. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  30677. return new Uint16BufferAttribute( array, itemSize );
  30678. }
  30679. function Int32Attribute( array, itemSize ) {
  30680. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  30681. return new Int32BufferAttribute( array, itemSize );
  30682. }
  30683. function Uint32Attribute( array, itemSize ) {
  30684. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  30685. return new Uint32BufferAttribute( array, itemSize );
  30686. }
  30687. function Float32Attribute( array, itemSize ) {
  30688. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  30689. return new Float32BufferAttribute( array, itemSize );
  30690. }
  30691. function Float64Attribute( array, itemSize ) {
  30692. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  30693. return new Float64BufferAttribute( array, itemSize );
  30694. }
  30695. //
  30696. Curve.create = function ( construct, getPoint ) {
  30697. console.log( 'THREE.Curve.create() has been deprecated' );
  30698. construct.prototype = Object.create( Curve.prototype );
  30699. construct.prototype.constructor = construct;
  30700. construct.prototype.getPoint = getPoint;
  30701. return construct;
  30702. };
  30703. //
  30704. Object.assign( CurvePath.prototype, {
  30705. createPointsGeometry: function ( divisions ) {
  30706. console.warn( 'THREE.CurvePath: .createPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30707. // generate geometry from path points (for Line or Points objects)
  30708. var pts = this.getPoints( divisions );
  30709. return this.createGeometry( pts );
  30710. },
  30711. createSpacedPointsGeometry: function ( divisions ) {
  30712. console.warn( 'THREE.CurvePath: .createSpacedPointsGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30713. // generate geometry from equidistant sampling along the path
  30714. var pts = this.getSpacedPoints( divisions );
  30715. return this.createGeometry( pts );
  30716. },
  30717. createGeometry: function ( points ) {
  30718. console.warn( 'THREE.CurvePath: .createGeometry() has been removed. Use new THREE.Geometry().setFromPoints( points ) instead.' );
  30719. var geometry = new Geometry();
  30720. for ( var i = 0, l = points.length; i < l; i ++ ) {
  30721. var point = points[ i ];
  30722. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  30723. }
  30724. return geometry;
  30725. }
  30726. } );
  30727. //
  30728. Object.assign( Path.prototype, {
  30729. fromPoints: function ( points ) {
  30730. console.warn( 'THREE.Path: .fromPoints() has been renamed to .setFromPoints().' );
  30731. this.setFromPoints( points );
  30732. }
  30733. } );
  30734. //
  30735. function ClosedSplineCurve3( points ) {
  30736. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30737. CatmullRomCurve3.call( this, points );
  30738. this.type = 'catmullrom';
  30739. this.closed = true;
  30740. }
  30741. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30742. //
  30743. function SplineCurve3( points ) {
  30744. console.warn( 'THREE.SplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  30745. CatmullRomCurve3.call( this, points );
  30746. this.type = 'catmullrom';
  30747. }
  30748. SplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  30749. //
  30750. function Spline( points ) {
  30751. console.warn( 'THREE.Spline has been removed. Use THREE.CatmullRomCurve3 instead.' );
  30752. CatmullRomCurve3.call( this, points );
  30753. this.type = 'catmullrom';
  30754. }
  30755. Spline.prototype = Object.create( CatmullRomCurve3.prototype );
  30756. Object.assign( Spline.prototype, {
  30757. initFromArray: function ( /* a */ ) {
  30758. console.error( 'THREE.Spline: .initFromArray() has been removed.' );
  30759. },
  30760. getControlPointsArray: function ( /* optionalTarget */ ) {
  30761. console.error( 'THREE.Spline: .getControlPointsArray() has been removed.' );
  30762. },
  30763. reparametrizeByArcLength: function ( /* samplingCoef */ ) {
  30764. console.error( 'THREE.Spline: .reparametrizeByArcLength() has been removed.' );
  30765. }
  30766. } );
  30767. //
  30768. function AxisHelper( size ) {
  30769. console.warn( 'THREE.AxisHelper has been renamed to THREE.AxesHelper.' );
  30770. return new AxesHelper( size );
  30771. }
  30772. function BoundingBoxHelper( object, color ) {
  30773. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  30774. return new BoxHelper( object, color );
  30775. }
  30776. function EdgesHelper( object, hex ) {
  30777. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  30778. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30779. }
  30780. GridHelper.prototype.setColors = function () {
  30781. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  30782. };
  30783. SkeletonHelper.prototype.update = function () {
  30784. console.error( 'THREE.SkeletonHelper: update() no longer needs to be called.' );
  30785. };
  30786. function WireframeHelper( object, hex ) {
  30787. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  30788. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  30789. }
  30790. //
  30791. Object.assign( Loader.prototype, {
  30792. extractUrlBase: function ( url ) {
  30793. console.warn( 'THREE.Loader: .extractUrlBase() has been deprecated. Use THREE.LoaderUtils.extractUrlBase() instead.' );
  30794. return LoaderUtils.extractUrlBase( url );
  30795. }
  30796. } );
  30797. function XHRLoader( manager ) {
  30798. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  30799. return new FileLoader( manager );
  30800. }
  30801. function BinaryTextureLoader( manager ) {
  30802. console.warn( 'THREE.BinaryTextureLoader has been renamed to THREE.DataTextureLoader.' );
  30803. return new DataTextureLoader( manager );
  30804. }
  30805. //
  30806. Object.assign( Box2.prototype, {
  30807. center: function ( optionalTarget ) {
  30808. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  30809. return this.getCenter( optionalTarget );
  30810. },
  30811. empty: function () {
  30812. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  30813. return this.isEmpty();
  30814. },
  30815. isIntersectionBox: function ( box ) {
  30816. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30817. return this.intersectsBox( box );
  30818. },
  30819. size: function ( optionalTarget ) {
  30820. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  30821. return this.getSize( optionalTarget );
  30822. }
  30823. } );
  30824. Object.assign( Box3.prototype, {
  30825. center: function ( optionalTarget ) {
  30826. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  30827. return this.getCenter( optionalTarget );
  30828. },
  30829. empty: function () {
  30830. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  30831. return this.isEmpty();
  30832. },
  30833. isIntersectionBox: function ( box ) {
  30834. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30835. return this.intersectsBox( box );
  30836. },
  30837. isIntersectionSphere: function ( sphere ) {
  30838. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30839. return this.intersectsSphere( sphere );
  30840. },
  30841. size: function ( optionalTarget ) {
  30842. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  30843. return this.getSize( optionalTarget );
  30844. }
  30845. } );
  30846. Line3.prototype.center = function ( optionalTarget ) {
  30847. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  30848. return this.getCenter( optionalTarget );
  30849. };
  30850. Object.assign( _Math, {
  30851. random16: function () {
  30852. console.warn( 'THREE.Math: .random16() has been deprecated. Use Math.random() instead.' );
  30853. return Math.random();
  30854. },
  30855. nearestPowerOfTwo: function ( value ) {
  30856. console.warn( 'THREE.Math: .nearestPowerOfTwo() has been renamed to .floorPowerOfTwo().' );
  30857. return _Math.floorPowerOfTwo( value );
  30858. },
  30859. nextPowerOfTwo: function ( value ) {
  30860. console.warn( 'THREE.Math: .nextPowerOfTwo() has been renamed to .ceilPowerOfTwo().' );
  30861. return _Math.ceilPowerOfTwo( value );
  30862. }
  30863. } );
  30864. Object.assign( Matrix3.prototype, {
  30865. flattenToArrayOffset: function ( array, offset ) {
  30866. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  30867. return this.toArray( array, offset );
  30868. },
  30869. multiplyVector3: function ( vector ) {
  30870. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  30871. return vector.applyMatrix3( this );
  30872. },
  30873. multiplyVector3Array: function ( /* a */ ) {
  30874. console.error( 'THREE.Matrix3: .multiplyVector3Array() has been removed.' );
  30875. },
  30876. applyToBuffer: function ( buffer /*, offset, length */ ) {
  30877. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  30878. return this.applyToBufferAttribute( buffer );
  30879. },
  30880. applyToVector3Array: function ( /* array, offset, length */ ) {
  30881. console.error( 'THREE.Matrix3: .applyToVector3Array() has been removed.' );
  30882. }
  30883. } );
  30884. Object.assign( Matrix4.prototype, {
  30885. extractPosition: function ( m ) {
  30886. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  30887. return this.copyPosition( m );
  30888. },
  30889. flattenToArrayOffset: function ( array, offset ) {
  30890. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  30891. return this.toArray( array, offset );
  30892. },
  30893. getPosition: function () {
  30894. var v1;
  30895. return function getPosition() {
  30896. if ( v1 === undefined ) v1 = new Vector3();
  30897. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  30898. return v1.setFromMatrixColumn( this, 3 );
  30899. };
  30900. }(),
  30901. setRotationFromQuaternion: function ( q ) {
  30902. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  30903. return this.makeRotationFromQuaternion( q );
  30904. },
  30905. multiplyToArray: function () {
  30906. console.warn( 'THREE.Matrix4: .multiplyToArray() has been removed.' );
  30907. },
  30908. multiplyVector3: function ( vector ) {
  30909. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30910. return vector.applyMatrix4( this );
  30911. },
  30912. multiplyVector4: function ( vector ) {
  30913. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30914. return vector.applyMatrix4( this );
  30915. },
  30916. multiplyVector3Array: function ( /* a */ ) {
  30917. console.error( 'THREE.Matrix4: .multiplyVector3Array() has been removed.' );
  30918. },
  30919. rotateAxis: function ( v ) {
  30920. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  30921. v.transformDirection( this );
  30922. },
  30923. crossVector: function ( vector ) {
  30924. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  30925. return vector.applyMatrix4( this );
  30926. },
  30927. translate: function () {
  30928. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  30929. },
  30930. rotateX: function () {
  30931. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  30932. },
  30933. rotateY: function () {
  30934. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  30935. },
  30936. rotateZ: function () {
  30937. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  30938. },
  30939. rotateByAxis: function () {
  30940. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  30941. },
  30942. applyToBuffer: function ( buffer /*, offset, length */ ) {
  30943. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  30944. return this.applyToBufferAttribute( buffer );
  30945. },
  30946. applyToVector3Array: function ( /* array, offset, length */ ) {
  30947. console.error( 'THREE.Matrix4: .applyToVector3Array() has been removed.' );
  30948. },
  30949. makeFrustum: function ( left, right, bottom, top, near, far ) {
  30950. console.warn( 'THREE.Matrix4: .makeFrustum() has been removed. Use .makePerspective( left, right, top, bottom, near, far ) instead.' );
  30951. return this.makePerspective( left, right, top, bottom, near, far );
  30952. }
  30953. } );
  30954. Plane.prototype.isIntersectionLine = function ( line ) {
  30955. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  30956. return this.intersectsLine( line );
  30957. };
  30958. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  30959. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  30960. return vector.applyQuaternion( this );
  30961. };
  30962. Object.assign( Ray.prototype, {
  30963. isIntersectionBox: function ( box ) {
  30964. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  30965. return this.intersectsBox( box );
  30966. },
  30967. isIntersectionPlane: function ( plane ) {
  30968. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  30969. return this.intersectsPlane( plane );
  30970. },
  30971. isIntersectionSphere: function ( sphere ) {
  30972. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  30973. return this.intersectsSphere( sphere );
  30974. }
  30975. } );
  30976. Object.assign( Shape.prototype, {
  30977. extractAllPoints: function ( divisions ) {
  30978. console.warn( 'THREE.Shape: .extractAllPoints() has been removed. Use .extractPoints() instead.' );
  30979. return this.extractPoints( divisions );
  30980. },
  30981. extrude: function ( options ) {
  30982. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  30983. return new ExtrudeGeometry( this, options );
  30984. },
  30985. makeGeometry: function ( options ) {
  30986. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  30987. return new ShapeGeometry( this, options );
  30988. }
  30989. } );
  30990. Object.assign( Vector2.prototype, {
  30991. fromAttribute: function ( attribute, index, offset ) {
  30992. console.warn( 'THREE.Vector2: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  30993. return this.fromBufferAttribute( attribute, index, offset );
  30994. },
  30995. distanceToManhattan: function ( v ) {
  30996. console.warn( 'THREE.Vector2: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  30997. return this.manhattanDistanceTo( v );
  30998. },
  30999. lengthManhattan: function () {
  31000. console.warn( 'THREE.Vector2: .lengthManhattan() has been renamed to .manhattanLength().' );
  31001. return this.manhattanLength();
  31002. }
  31003. } );
  31004. Object.assign( Vector3.prototype, {
  31005. setEulerFromRotationMatrix: function () {
  31006. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  31007. },
  31008. setEulerFromQuaternion: function () {
  31009. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  31010. },
  31011. getPositionFromMatrix: function ( m ) {
  31012. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  31013. return this.setFromMatrixPosition( m );
  31014. },
  31015. getScaleFromMatrix: function ( m ) {
  31016. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  31017. return this.setFromMatrixScale( m );
  31018. },
  31019. getColumnFromMatrix: function ( index, matrix ) {
  31020. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  31021. return this.setFromMatrixColumn( matrix, index );
  31022. },
  31023. applyProjection: function ( m ) {
  31024. console.warn( 'THREE.Vector3: .applyProjection() has been removed. Use .applyMatrix4( m ) instead.' );
  31025. return this.applyMatrix4( m );
  31026. },
  31027. fromAttribute: function ( attribute, index, offset ) {
  31028. console.warn( 'THREE.Vector3: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31029. return this.fromBufferAttribute( attribute, index, offset );
  31030. },
  31031. distanceToManhattan: function ( v ) {
  31032. console.warn( 'THREE.Vector3: .distanceToManhattan() has been renamed to .manhattanDistanceTo().' );
  31033. return this.manhattanDistanceTo( v );
  31034. },
  31035. lengthManhattan: function () {
  31036. console.warn( 'THREE.Vector3: .lengthManhattan() has been renamed to .manhattanLength().' );
  31037. return this.manhattanLength();
  31038. }
  31039. } );
  31040. Object.assign( Vector4.prototype, {
  31041. fromAttribute: function ( attribute, index, offset ) {
  31042. console.warn( 'THREE.Vector4: .fromAttribute() has been renamed to .fromBufferAttribute().' );
  31043. return this.fromBufferAttribute( attribute, index, offset );
  31044. },
  31045. lengthManhattan: function () {
  31046. console.warn( 'THREE.Vector4: .lengthManhattan() has been renamed to .manhattanLength().' );
  31047. return this.manhattanLength();
  31048. }
  31049. } );
  31050. //
  31051. Geometry.prototype.computeTangents = function () {
  31052. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  31053. };
  31054. Object.assign( Object3D.prototype, {
  31055. getChildByName: function ( name ) {
  31056. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  31057. return this.getObjectByName( name );
  31058. },
  31059. renderDepth: function () {
  31060. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  31061. },
  31062. translate: function ( distance, axis ) {
  31063. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  31064. return this.translateOnAxis( axis, distance );
  31065. }
  31066. } );
  31067. Object.defineProperties( Object3D.prototype, {
  31068. eulerOrder: {
  31069. get: function () {
  31070. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31071. return this.rotation.order;
  31072. },
  31073. set: function ( value ) {
  31074. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  31075. this.rotation.order = value;
  31076. }
  31077. },
  31078. useQuaternion: {
  31079. get: function () {
  31080. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31081. },
  31082. set: function () {
  31083. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  31084. }
  31085. }
  31086. } );
  31087. Object.defineProperties( LOD.prototype, {
  31088. objects: {
  31089. get: function () {
  31090. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  31091. return this.levels;
  31092. }
  31093. }
  31094. } );
  31095. Object.defineProperty( Skeleton.prototype, 'useVertexTexture', {
  31096. get: function () {
  31097. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31098. },
  31099. set: function () {
  31100. console.warn( 'THREE.Skeleton: useVertexTexture has been removed.' );
  31101. }
  31102. } );
  31103. Object.defineProperty( Curve.prototype, '__arcLengthDivisions', {
  31104. get: function () {
  31105. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31106. return this.arcLengthDivisions;
  31107. },
  31108. set: function ( value ) {
  31109. console.warn( 'THREE.Curve: .__arcLengthDivisions is now .arcLengthDivisions.' );
  31110. this.arcLengthDivisions = value;
  31111. }
  31112. } );
  31113. //
  31114. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  31115. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  31116. "Use .setFocalLength and .filmGauge for a photographic setup." );
  31117. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  31118. this.setFocalLength( focalLength );
  31119. };
  31120. //
  31121. Object.defineProperties( Light.prototype, {
  31122. onlyShadow: {
  31123. set: function () {
  31124. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  31125. }
  31126. },
  31127. shadowCameraFov: {
  31128. set: function ( value ) {
  31129. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  31130. this.shadow.camera.fov = value;
  31131. }
  31132. },
  31133. shadowCameraLeft: {
  31134. set: function ( value ) {
  31135. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  31136. this.shadow.camera.left = value;
  31137. }
  31138. },
  31139. shadowCameraRight: {
  31140. set: function ( value ) {
  31141. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  31142. this.shadow.camera.right = value;
  31143. }
  31144. },
  31145. shadowCameraTop: {
  31146. set: function ( value ) {
  31147. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  31148. this.shadow.camera.top = value;
  31149. }
  31150. },
  31151. shadowCameraBottom: {
  31152. set: function ( value ) {
  31153. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  31154. this.shadow.camera.bottom = value;
  31155. }
  31156. },
  31157. shadowCameraNear: {
  31158. set: function ( value ) {
  31159. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  31160. this.shadow.camera.near = value;
  31161. }
  31162. },
  31163. shadowCameraFar: {
  31164. set: function ( value ) {
  31165. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  31166. this.shadow.camera.far = value;
  31167. }
  31168. },
  31169. shadowCameraVisible: {
  31170. set: function () {
  31171. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  31172. }
  31173. },
  31174. shadowBias: {
  31175. set: function ( value ) {
  31176. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  31177. this.shadow.bias = value;
  31178. }
  31179. },
  31180. shadowDarkness: {
  31181. set: function () {
  31182. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  31183. }
  31184. },
  31185. shadowMapWidth: {
  31186. set: function ( value ) {
  31187. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  31188. this.shadow.mapSize.width = value;
  31189. }
  31190. },
  31191. shadowMapHeight: {
  31192. set: function ( value ) {
  31193. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  31194. this.shadow.mapSize.height = value;
  31195. }
  31196. }
  31197. } );
  31198. //
  31199. Object.defineProperties( BufferAttribute.prototype, {
  31200. length: {
  31201. get: function () {
  31202. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  31203. return this.array.length;
  31204. }
  31205. }
  31206. } );
  31207. Object.assign( BufferGeometry.prototype, {
  31208. addIndex: function ( index ) {
  31209. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  31210. this.setIndex( index );
  31211. },
  31212. addDrawCall: function ( start, count, indexOffset ) {
  31213. if ( indexOffset !== undefined ) {
  31214. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  31215. }
  31216. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  31217. this.addGroup( start, count );
  31218. },
  31219. clearDrawCalls: function () {
  31220. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  31221. this.clearGroups();
  31222. },
  31223. computeTangents: function () {
  31224. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  31225. },
  31226. computeOffsets: function () {
  31227. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  31228. }
  31229. } );
  31230. Object.defineProperties( BufferGeometry.prototype, {
  31231. drawcalls: {
  31232. get: function () {
  31233. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  31234. return this.groups;
  31235. }
  31236. },
  31237. offsets: {
  31238. get: function () {
  31239. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  31240. return this.groups;
  31241. }
  31242. }
  31243. } );
  31244. //
  31245. Object.defineProperties( Uniform.prototype, {
  31246. dynamic: {
  31247. set: function () {
  31248. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  31249. }
  31250. },
  31251. onUpdate: {
  31252. value: function () {
  31253. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  31254. return this;
  31255. }
  31256. }
  31257. } );
  31258. //
  31259. Object.defineProperties( Material.prototype, {
  31260. wrapAround: {
  31261. get: function () {
  31262. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31263. },
  31264. set: function () {
  31265. console.warn( 'THREE.Material: .wrapAround has been removed.' );
  31266. }
  31267. },
  31268. wrapRGB: {
  31269. get: function () {
  31270. console.warn( 'THREE.Material: .wrapRGB has been removed.' );
  31271. return new Color();
  31272. }
  31273. },
  31274. shading: {
  31275. get: function () {
  31276. console.error( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31277. },
  31278. set: function ( value ) {
  31279. console.warn( 'THREE.' + this.type + ': .shading has been removed. Use the boolean .flatShading instead.' );
  31280. this.flatShading = ( value === FlatShading );
  31281. }
  31282. }
  31283. } );
  31284. Object.defineProperties( MeshPhongMaterial.prototype, {
  31285. metal: {
  31286. get: function () {
  31287. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  31288. return false;
  31289. },
  31290. set: function () {
  31291. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  31292. }
  31293. }
  31294. } );
  31295. Object.defineProperties( ShaderMaterial.prototype, {
  31296. derivatives: {
  31297. get: function () {
  31298. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31299. return this.extensions.derivatives;
  31300. },
  31301. set: function ( value ) {
  31302. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  31303. this.extensions.derivatives = value;
  31304. }
  31305. }
  31306. } );
  31307. //
  31308. Object.assign( WebGLRenderer.prototype, {
  31309. getCurrentRenderTarget: function () {
  31310. console.warn( 'THREE.WebGLRenderer: .getCurrentRenderTarget() is now .getRenderTarget().' );
  31311. return this.getRenderTarget();
  31312. },
  31313. getMaxAnisotropy: function () {
  31314. console.warn( 'THREE.WebGLRenderer: .getMaxAnisotropy() is now .capabilities.getMaxAnisotropy().' );
  31315. return this.capabilities.getMaxAnisotropy();
  31316. },
  31317. getPrecision: function () {
  31318. console.warn( 'THREE.WebGLRenderer: .getPrecision() is now .capabilities.precision.' );
  31319. return this.capabilities.precision;
  31320. },
  31321. resetGLState: function () {
  31322. console.warn( 'THREE.WebGLRenderer: .resetGLState() is now .state.reset().' );
  31323. return this.state.reset();
  31324. },
  31325. supportsFloatTextures: function () {
  31326. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  31327. return this.extensions.get( 'OES_texture_float' );
  31328. },
  31329. supportsHalfFloatTextures: function () {
  31330. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  31331. return this.extensions.get( 'OES_texture_half_float' );
  31332. },
  31333. supportsStandardDerivatives: function () {
  31334. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  31335. return this.extensions.get( 'OES_standard_derivatives' );
  31336. },
  31337. supportsCompressedTextureS3TC: function () {
  31338. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  31339. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  31340. },
  31341. supportsCompressedTexturePVRTC: function () {
  31342. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  31343. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  31344. },
  31345. supportsBlendMinMax: function () {
  31346. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  31347. return this.extensions.get( 'EXT_blend_minmax' );
  31348. },
  31349. supportsVertexTextures: function () {
  31350. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  31351. return this.capabilities.vertexTextures;
  31352. },
  31353. supportsInstancedArrays: function () {
  31354. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  31355. return this.extensions.get( 'ANGLE_instanced_arrays' );
  31356. },
  31357. enableScissorTest: function ( boolean ) {
  31358. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  31359. this.setScissorTest( boolean );
  31360. },
  31361. initMaterial: function () {
  31362. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  31363. },
  31364. addPrePlugin: function () {
  31365. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  31366. },
  31367. addPostPlugin: function () {
  31368. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  31369. },
  31370. updateShadowMap: function () {
  31371. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  31372. }
  31373. } );
  31374. Object.defineProperties( WebGLRenderer.prototype, {
  31375. shadowMapEnabled: {
  31376. get: function () {
  31377. return this.shadowMap.enabled;
  31378. },
  31379. set: function ( value ) {
  31380. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  31381. this.shadowMap.enabled = value;
  31382. }
  31383. },
  31384. shadowMapType: {
  31385. get: function () {
  31386. return this.shadowMap.type;
  31387. },
  31388. set: function ( value ) {
  31389. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  31390. this.shadowMap.type = value;
  31391. }
  31392. },
  31393. shadowMapCullFace: {
  31394. get: function () {
  31395. return this.shadowMap.cullFace;
  31396. },
  31397. set: function ( value ) {
  31398. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  31399. this.shadowMap.cullFace = value;
  31400. }
  31401. }
  31402. } );
  31403. Object.defineProperties( WebGLShadowMap.prototype, {
  31404. cullFace: {
  31405. get: function () {
  31406. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  31407. },
  31408. set: function ( cullFace ) {
  31409. var value = ( cullFace !== CullFaceBack );
  31410. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  31411. this.renderReverseSided = value;
  31412. }
  31413. }
  31414. } );
  31415. //
  31416. Object.defineProperties( WebGLRenderTarget.prototype, {
  31417. wrapS: {
  31418. get: function () {
  31419. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31420. return this.texture.wrapS;
  31421. },
  31422. set: function ( value ) {
  31423. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  31424. this.texture.wrapS = value;
  31425. }
  31426. },
  31427. wrapT: {
  31428. get: function () {
  31429. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31430. return this.texture.wrapT;
  31431. },
  31432. set: function ( value ) {
  31433. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  31434. this.texture.wrapT = value;
  31435. }
  31436. },
  31437. magFilter: {
  31438. get: function () {
  31439. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31440. return this.texture.magFilter;
  31441. },
  31442. set: function ( value ) {
  31443. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  31444. this.texture.magFilter = value;
  31445. }
  31446. },
  31447. minFilter: {
  31448. get: function () {
  31449. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31450. return this.texture.minFilter;
  31451. },
  31452. set: function ( value ) {
  31453. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  31454. this.texture.minFilter = value;
  31455. }
  31456. },
  31457. anisotropy: {
  31458. get: function () {
  31459. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31460. return this.texture.anisotropy;
  31461. },
  31462. set: function ( value ) {
  31463. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  31464. this.texture.anisotropy = value;
  31465. }
  31466. },
  31467. offset: {
  31468. get: function () {
  31469. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31470. return this.texture.offset;
  31471. },
  31472. set: function ( value ) {
  31473. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  31474. this.texture.offset = value;
  31475. }
  31476. },
  31477. repeat: {
  31478. get: function () {
  31479. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31480. return this.texture.repeat;
  31481. },
  31482. set: function ( value ) {
  31483. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  31484. this.texture.repeat = value;
  31485. }
  31486. },
  31487. format: {
  31488. get: function () {
  31489. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31490. return this.texture.format;
  31491. },
  31492. set: function ( value ) {
  31493. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  31494. this.texture.format = value;
  31495. }
  31496. },
  31497. type: {
  31498. get: function () {
  31499. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31500. return this.texture.type;
  31501. },
  31502. set: function ( value ) {
  31503. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  31504. this.texture.type = value;
  31505. }
  31506. },
  31507. generateMipmaps: {
  31508. get: function () {
  31509. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31510. return this.texture.generateMipmaps;
  31511. },
  31512. set: function ( value ) {
  31513. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  31514. this.texture.generateMipmaps = value;
  31515. }
  31516. }
  31517. } );
  31518. //
  31519. Object.defineProperties( WebVRManager.prototype, {
  31520. standing: {
  31521. set: function ( /* value */ ) {
  31522. console.warn( 'THREE.WebVRManager: .standing has been removed.' );
  31523. }
  31524. }
  31525. } );
  31526. //
  31527. Audio.prototype.load = function ( file ) {
  31528. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  31529. var scope = this;
  31530. var audioLoader = new AudioLoader();
  31531. audioLoader.load( file, function ( buffer ) {
  31532. scope.setBuffer( buffer );
  31533. } );
  31534. return this;
  31535. };
  31536. AudioAnalyser.prototype.getData = function () {
  31537. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  31538. return this.getFrequencyData();
  31539. };
  31540. //
  31541. CubeCamera.prototype.updateCubeMap = function ( renderer, scene ) {
  31542. console.warn( 'THREE.CubeCamera: .updateCubeMap() is now .update().' );
  31543. return this.update( renderer, scene );
  31544. };
  31545. //
  31546. var GeometryUtils = {
  31547. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  31548. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  31549. var matrix;
  31550. if ( geometry2.isMesh ) {
  31551. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  31552. matrix = geometry2.matrix;
  31553. geometry2 = geometry2.geometry;
  31554. }
  31555. geometry1.merge( geometry2, matrix, materialIndexOffset );
  31556. },
  31557. center: function ( geometry ) {
  31558. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  31559. return geometry.center();
  31560. }
  31561. };
  31562. var ImageUtils = {
  31563. crossOrigin: undefined,
  31564. loadTexture: function ( url, mapping, onLoad, onError ) {
  31565. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  31566. var loader = new TextureLoader();
  31567. loader.setCrossOrigin( this.crossOrigin );
  31568. var texture = loader.load( url, onLoad, undefined, onError );
  31569. if ( mapping ) texture.mapping = mapping;
  31570. return texture;
  31571. },
  31572. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  31573. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  31574. var loader = new CubeTextureLoader();
  31575. loader.setCrossOrigin( this.crossOrigin );
  31576. var texture = loader.load( urls, onLoad, undefined, onError );
  31577. if ( mapping ) texture.mapping = mapping;
  31578. return texture;
  31579. },
  31580. loadCompressedTexture: function () {
  31581. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  31582. },
  31583. loadCompressedTextureCube: function () {
  31584. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  31585. }
  31586. };
  31587. //
  31588. function Projector() {
  31589. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  31590. this.projectVector = function ( vector, camera ) {
  31591. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  31592. vector.project( camera );
  31593. };
  31594. this.unprojectVector = function ( vector, camera ) {
  31595. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  31596. vector.unproject( camera );
  31597. };
  31598. this.pickingRay = function () {
  31599. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  31600. };
  31601. }
  31602. //
  31603. function CanvasRenderer() {
  31604. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  31605. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  31606. this.clear = function () {};
  31607. this.render = function () {};
  31608. this.setClearColor = function () {};
  31609. this.setSize = function () {};
  31610. }
  31611. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  31612. exports.WebGLRenderTarget = WebGLRenderTarget;
  31613. exports.WebGLRenderer = WebGLRenderer;
  31614. exports.ShaderLib = ShaderLib;
  31615. exports.UniformsLib = UniformsLib;
  31616. exports.UniformsUtils = UniformsUtils;
  31617. exports.ShaderChunk = ShaderChunk;
  31618. exports.FogExp2 = FogExp2;
  31619. exports.Fog = Fog;
  31620. exports.Scene = Scene;
  31621. exports.LensFlare = LensFlare;
  31622. exports.Sprite = Sprite;
  31623. exports.LOD = LOD;
  31624. exports.SkinnedMesh = SkinnedMesh;
  31625. exports.Skeleton = Skeleton;
  31626. exports.Bone = Bone;
  31627. exports.Mesh = Mesh;
  31628. exports.LineSegments = LineSegments;
  31629. exports.LineLoop = LineLoop;
  31630. exports.Line = Line;
  31631. exports.Points = Points;
  31632. exports.Group = Group;
  31633. exports.VideoTexture = VideoTexture;
  31634. exports.DataTexture = DataTexture;
  31635. exports.CompressedTexture = CompressedTexture;
  31636. exports.CubeTexture = CubeTexture;
  31637. exports.CanvasTexture = CanvasTexture;
  31638. exports.DepthTexture = DepthTexture;
  31639. exports.Texture = Texture;
  31640. exports.CompressedTextureLoader = CompressedTextureLoader;
  31641. exports.DataTextureLoader = DataTextureLoader;
  31642. exports.CubeTextureLoader = CubeTextureLoader;
  31643. exports.TextureLoader = TextureLoader;
  31644. exports.ObjectLoader = ObjectLoader;
  31645. exports.MaterialLoader = MaterialLoader;
  31646. exports.BufferGeometryLoader = BufferGeometryLoader;
  31647. exports.DefaultLoadingManager = DefaultLoadingManager;
  31648. exports.LoadingManager = LoadingManager;
  31649. exports.JSONLoader = JSONLoader;
  31650. exports.ImageLoader = ImageLoader;
  31651. exports.ImageBitmapLoader = ImageBitmapLoader;
  31652. exports.FontLoader = FontLoader;
  31653. exports.FileLoader = FileLoader;
  31654. exports.Loader = Loader;
  31655. exports.LoaderUtils = LoaderUtils;
  31656. exports.Cache = Cache;
  31657. exports.AudioLoader = AudioLoader;
  31658. exports.SpotLightShadow = SpotLightShadow;
  31659. exports.SpotLight = SpotLight;
  31660. exports.PointLight = PointLight;
  31661. exports.RectAreaLight = RectAreaLight;
  31662. exports.HemisphereLight = HemisphereLight;
  31663. exports.DirectionalLightShadow = DirectionalLightShadow;
  31664. exports.DirectionalLight = DirectionalLight;
  31665. exports.AmbientLight = AmbientLight;
  31666. exports.LightShadow = LightShadow;
  31667. exports.Light = Light;
  31668. exports.StereoCamera = StereoCamera;
  31669. exports.PerspectiveCamera = PerspectiveCamera;
  31670. exports.OrthographicCamera = OrthographicCamera;
  31671. exports.CubeCamera = CubeCamera;
  31672. exports.ArrayCamera = ArrayCamera;
  31673. exports.Camera = Camera;
  31674. exports.AudioListener = AudioListener;
  31675. exports.PositionalAudio = PositionalAudio;
  31676. exports.AudioContext = AudioContext;
  31677. exports.AudioAnalyser = AudioAnalyser;
  31678. exports.Audio = Audio;
  31679. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  31680. exports.StringKeyframeTrack = StringKeyframeTrack;
  31681. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  31682. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  31683. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  31684. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  31685. exports.PropertyMixer = PropertyMixer;
  31686. exports.PropertyBinding = PropertyBinding;
  31687. exports.KeyframeTrack = KeyframeTrack;
  31688. exports.AnimationUtils = AnimationUtils;
  31689. exports.AnimationObjectGroup = AnimationObjectGroup;
  31690. exports.AnimationMixer = AnimationMixer;
  31691. exports.AnimationClip = AnimationClip;
  31692. exports.Uniform = Uniform;
  31693. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  31694. exports.BufferGeometry = BufferGeometry;
  31695. exports.Geometry = Geometry;
  31696. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  31697. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  31698. exports.InterleavedBuffer = InterleavedBuffer;
  31699. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  31700. exports.Face3 = Face3;
  31701. exports.Object3D = Object3D;
  31702. exports.Raycaster = Raycaster;
  31703. exports.Layers = Layers;
  31704. exports.EventDispatcher = EventDispatcher;
  31705. exports.Clock = Clock;
  31706. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  31707. exports.LinearInterpolant = LinearInterpolant;
  31708. exports.DiscreteInterpolant = DiscreteInterpolant;
  31709. exports.CubicInterpolant = CubicInterpolant;
  31710. exports.Interpolant = Interpolant;
  31711. exports.Triangle = Triangle;
  31712. exports.Math = _Math;
  31713. exports.Spherical = Spherical;
  31714. exports.Cylindrical = Cylindrical;
  31715. exports.Plane = Plane;
  31716. exports.Frustum = Frustum;
  31717. exports.Sphere = Sphere;
  31718. exports.Ray = Ray;
  31719. exports.Matrix4 = Matrix4;
  31720. exports.Matrix3 = Matrix3;
  31721. exports.Box3 = Box3;
  31722. exports.Box2 = Box2;
  31723. exports.Line3 = Line3;
  31724. exports.Euler = Euler;
  31725. exports.Vector4 = Vector4;
  31726. exports.Vector3 = Vector3;
  31727. exports.Vector2 = Vector2;
  31728. exports.Quaternion = Quaternion;
  31729. exports.Color = Color;
  31730. exports.ImmediateRenderObject = ImmediateRenderObject;
  31731. exports.VertexNormalsHelper = VertexNormalsHelper;
  31732. exports.SpotLightHelper = SpotLightHelper;
  31733. exports.SkeletonHelper = SkeletonHelper;
  31734. exports.PointLightHelper = PointLightHelper;
  31735. exports.RectAreaLightHelper = RectAreaLightHelper;
  31736. exports.HemisphereLightHelper = HemisphereLightHelper;
  31737. exports.GridHelper = GridHelper;
  31738. exports.PolarGridHelper = PolarGridHelper;
  31739. exports.FaceNormalsHelper = FaceNormalsHelper;
  31740. exports.DirectionalLightHelper = DirectionalLightHelper;
  31741. exports.CameraHelper = CameraHelper;
  31742. exports.BoxHelper = BoxHelper;
  31743. exports.Box3Helper = Box3Helper;
  31744. exports.PlaneHelper = PlaneHelper;
  31745. exports.ArrowHelper = ArrowHelper;
  31746. exports.AxesHelper = AxesHelper;
  31747. exports.Shape = Shape;
  31748. exports.Path = Path;
  31749. exports.ShapePath = ShapePath;
  31750. exports.Font = Font;
  31751. exports.CurvePath = CurvePath;
  31752. exports.Curve = Curve;
  31753. exports.ShapeUtils = ShapeUtils;
  31754. exports.SceneUtils = SceneUtils;
  31755. exports.WebGLUtils = WebGLUtils;
  31756. exports.WireframeGeometry = WireframeGeometry;
  31757. exports.ParametricGeometry = ParametricGeometry;
  31758. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  31759. exports.TetrahedronGeometry = TetrahedronGeometry;
  31760. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  31761. exports.OctahedronGeometry = OctahedronGeometry;
  31762. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  31763. exports.IcosahedronGeometry = IcosahedronGeometry;
  31764. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  31765. exports.DodecahedronGeometry = DodecahedronGeometry;
  31766. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  31767. exports.PolyhedronGeometry = PolyhedronGeometry;
  31768. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  31769. exports.TubeGeometry = TubeGeometry;
  31770. exports.TubeBufferGeometry = TubeBufferGeometry;
  31771. exports.TorusKnotGeometry = TorusKnotGeometry;
  31772. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  31773. exports.TorusGeometry = TorusGeometry;
  31774. exports.TorusBufferGeometry = TorusBufferGeometry;
  31775. exports.TextGeometry = TextGeometry;
  31776. exports.TextBufferGeometry = TextBufferGeometry;
  31777. exports.SphereGeometry = SphereGeometry;
  31778. exports.SphereBufferGeometry = SphereBufferGeometry;
  31779. exports.RingGeometry = RingGeometry;
  31780. exports.RingBufferGeometry = RingBufferGeometry;
  31781. exports.PlaneGeometry = PlaneGeometry;
  31782. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  31783. exports.LatheGeometry = LatheGeometry;
  31784. exports.LatheBufferGeometry = LatheBufferGeometry;
  31785. exports.ShapeGeometry = ShapeGeometry;
  31786. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  31787. exports.ExtrudeGeometry = ExtrudeGeometry;
  31788. exports.ExtrudeBufferGeometry = ExtrudeBufferGeometry;
  31789. exports.EdgesGeometry = EdgesGeometry;
  31790. exports.ConeGeometry = ConeGeometry;
  31791. exports.ConeBufferGeometry = ConeBufferGeometry;
  31792. exports.CylinderGeometry = CylinderGeometry;
  31793. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  31794. exports.CircleGeometry = CircleGeometry;
  31795. exports.CircleBufferGeometry = CircleBufferGeometry;
  31796. exports.BoxGeometry = BoxGeometry;
  31797. exports.BoxBufferGeometry = BoxBufferGeometry;
  31798. exports.ShadowMaterial = ShadowMaterial;
  31799. exports.SpriteMaterial = SpriteMaterial;
  31800. exports.RawShaderMaterial = RawShaderMaterial;
  31801. exports.ShaderMaterial = ShaderMaterial;
  31802. exports.PointsMaterial = PointsMaterial;
  31803. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  31804. exports.MeshStandardMaterial = MeshStandardMaterial;
  31805. exports.MeshPhongMaterial = MeshPhongMaterial;
  31806. exports.MeshToonMaterial = MeshToonMaterial;
  31807. exports.MeshNormalMaterial = MeshNormalMaterial;
  31808. exports.MeshLambertMaterial = MeshLambertMaterial;
  31809. exports.MeshDepthMaterial = MeshDepthMaterial;
  31810. exports.MeshDistanceMaterial = MeshDistanceMaterial;
  31811. exports.MeshBasicMaterial = MeshBasicMaterial;
  31812. exports.LineDashedMaterial = LineDashedMaterial;
  31813. exports.LineBasicMaterial = LineBasicMaterial;
  31814. exports.Material = Material;
  31815. exports.Float64BufferAttribute = Float64BufferAttribute;
  31816. exports.Float32BufferAttribute = Float32BufferAttribute;
  31817. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  31818. exports.Int32BufferAttribute = Int32BufferAttribute;
  31819. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  31820. exports.Int16BufferAttribute = Int16BufferAttribute;
  31821. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  31822. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  31823. exports.Int8BufferAttribute = Int8BufferAttribute;
  31824. exports.BufferAttribute = BufferAttribute;
  31825. exports.ArcCurve = ArcCurve;
  31826. exports.CatmullRomCurve3 = CatmullRomCurve3;
  31827. exports.CubicBezierCurve = CubicBezierCurve;
  31828. exports.CubicBezierCurve3 = CubicBezierCurve3;
  31829. exports.EllipseCurve = EllipseCurve;
  31830. exports.LineCurve = LineCurve;
  31831. exports.LineCurve3 = LineCurve3;
  31832. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  31833. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  31834. exports.SplineCurve = SplineCurve;
  31835. exports.REVISION = REVISION;
  31836. exports.MOUSE = MOUSE;
  31837. exports.CullFaceNone = CullFaceNone;
  31838. exports.CullFaceBack = CullFaceBack;
  31839. exports.CullFaceFront = CullFaceFront;
  31840. exports.CullFaceFrontBack = CullFaceFrontBack;
  31841. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  31842. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  31843. exports.BasicShadowMap = BasicShadowMap;
  31844. exports.PCFShadowMap = PCFShadowMap;
  31845. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  31846. exports.FrontSide = FrontSide;
  31847. exports.BackSide = BackSide;
  31848. exports.DoubleSide = DoubleSide;
  31849. exports.FlatShading = FlatShading;
  31850. exports.SmoothShading = SmoothShading;
  31851. exports.NoColors = NoColors;
  31852. exports.FaceColors = FaceColors;
  31853. exports.VertexColors = VertexColors;
  31854. exports.NoBlending = NoBlending;
  31855. exports.NormalBlending = NormalBlending;
  31856. exports.AdditiveBlending = AdditiveBlending;
  31857. exports.SubtractiveBlending = SubtractiveBlending;
  31858. exports.MultiplyBlending = MultiplyBlending;
  31859. exports.CustomBlending = CustomBlending;
  31860. exports.AddEquation = AddEquation;
  31861. exports.SubtractEquation = SubtractEquation;
  31862. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  31863. exports.MinEquation = MinEquation;
  31864. exports.MaxEquation = MaxEquation;
  31865. exports.ZeroFactor = ZeroFactor;
  31866. exports.OneFactor = OneFactor;
  31867. exports.SrcColorFactor = SrcColorFactor;
  31868. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  31869. exports.SrcAlphaFactor = SrcAlphaFactor;
  31870. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  31871. exports.DstAlphaFactor = DstAlphaFactor;
  31872. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  31873. exports.DstColorFactor = DstColorFactor;
  31874. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  31875. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  31876. exports.NeverDepth = NeverDepth;
  31877. exports.AlwaysDepth = AlwaysDepth;
  31878. exports.LessDepth = LessDepth;
  31879. exports.LessEqualDepth = LessEqualDepth;
  31880. exports.EqualDepth = EqualDepth;
  31881. exports.GreaterEqualDepth = GreaterEqualDepth;
  31882. exports.GreaterDepth = GreaterDepth;
  31883. exports.NotEqualDepth = NotEqualDepth;
  31884. exports.MultiplyOperation = MultiplyOperation;
  31885. exports.MixOperation = MixOperation;
  31886. exports.AddOperation = AddOperation;
  31887. exports.NoToneMapping = NoToneMapping;
  31888. exports.LinearToneMapping = LinearToneMapping;
  31889. exports.ReinhardToneMapping = ReinhardToneMapping;
  31890. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  31891. exports.CineonToneMapping = CineonToneMapping;
  31892. exports.UVMapping = UVMapping;
  31893. exports.CubeReflectionMapping = CubeReflectionMapping;
  31894. exports.CubeRefractionMapping = CubeRefractionMapping;
  31895. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  31896. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  31897. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  31898. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  31899. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  31900. exports.RepeatWrapping = RepeatWrapping;
  31901. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  31902. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  31903. exports.NearestFilter = NearestFilter;
  31904. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  31905. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  31906. exports.LinearFilter = LinearFilter;
  31907. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  31908. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  31909. exports.UnsignedByteType = UnsignedByteType;
  31910. exports.ByteType = ByteType;
  31911. exports.ShortType = ShortType;
  31912. exports.UnsignedShortType = UnsignedShortType;
  31913. exports.IntType = IntType;
  31914. exports.UnsignedIntType = UnsignedIntType;
  31915. exports.FloatType = FloatType;
  31916. exports.HalfFloatType = HalfFloatType;
  31917. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  31918. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  31919. exports.UnsignedShort565Type = UnsignedShort565Type;
  31920. exports.UnsignedInt248Type = UnsignedInt248Type;
  31921. exports.AlphaFormat = AlphaFormat;
  31922. exports.RGBFormat = RGBFormat;
  31923. exports.RGBAFormat = RGBAFormat;
  31924. exports.LuminanceFormat = LuminanceFormat;
  31925. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  31926. exports.RGBEFormat = RGBEFormat;
  31927. exports.DepthFormat = DepthFormat;
  31928. exports.DepthStencilFormat = DepthStencilFormat;
  31929. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  31930. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  31931. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  31932. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  31933. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  31934. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  31935. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  31936. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  31937. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  31938. exports.LoopOnce = LoopOnce;
  31939. exports.LoopRepeat = LoopRepeat;
  31940. exports.LoopPingPong = LoopPingPong;
  31941. exports.InterpolateDiscrete = InterpolateDiscrete;
  31942. exports.InterpolateLinear = InterpolateLinear;
  31943. exports.InterpolateSmooth = InterpolateSmooth;
  31944. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  31945. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  31946. exports.WrapAroundEnding = WrapAroundEnding;
  31947. exports.TrianglesDrawMode = TrianglesDrawMode;
  31948. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  31949. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  31950. exports.LinearEncoding = LinearEncoding;
  31951. exports.sRGBEncoding = sRGBEncoding;
  31952. exports.GammaEncoding = GammaEncoding;
  31953. exports.RGBEEncoding = RGBEEncoding;
  31954. exports.LogLuvEncoding = LogLuvEncoding;
  31955. exports.RGBM7Encoding = RGBM7Encoding;
  31956. exports.RGBM16Encoding = RGBM16Encoding;
  31957. exports.RGBDEncoding = RGBDEncoding;
  31958. exports.BasicDepthPacking = BasicDepthPacking;
  31959. exports.RGBADepthPacking = RGBADepthPacking;
  31960. exports.CubeGeometry = BoxGeometry;
  31961. exports.Face4 = Face4;
  31962. exports.LineStrip = LineStrip;
  31963. exports.LinePieces = LinePieces;
  31964. exports.MeshFaceMaterial = MeshFaceMaterial;
  31965. exports.MultiMaterial = MultiMaterial;
  31966. exports.PointCloud = PointCloud;
  31967. exports.Particle = Particle;
  31968. exports.ParticleSystem = ParticleSystem;
  31969. exports.PointCloudMaterial = PointCloudMaterial;
  31970. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  31971. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  31972. exports.Vertex = Vertex;
  31973. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  31974. exports.Int8Attribute = Int8Attribute;
  31975. exports.Uint8Attribute = Uint8Attribute;
  31976. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  31977. exports.Int16Attribute = Int16Attribute;
  31978. exports.Uint16Attribute = Uint16Attribute;
  31979. exports.Int32Attribute = Int32Attribute;
  31980. exports.Uint32Attribute = Uint32Attribute;
  31981. exports.Float32Attribute = Float32Attribute;
  31982. exports.Float64Attribute = Float64Attribute;
  31983. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  31984. exports.SplineCurve3 = SplineCurve3;
  31985. exports.Spline = Spline;
  31986. exports.AxisHelper = AxisHelper;
  31987. exports.BoundingBoxHelper = BoundingBoxHelper;
  31988. exports.EdgesHelper = EdgesHelper;
  31989. exports.WireframeHelper = WireframeHelper;
  31990. exports.XHRLoader = XHRLoader;
  31991. exports.BinaryTextureLoader = BinaryTextureLoader;
  31992. exports.GeometryUtils = GeometryUtils;
  31993. exports.ImageUtils = ImageUtils;
  31994. exports.Projector = Projector;
  31995. exports.CanvasRenderer = CanvasRenderer;
  31996. Object.defineProperty(exports, '__esModule', { value: true });
  31997. })));
  31998. },{}],42:[function(_dereq_,module,exports){
  31999. /**
  32000. * @author mrdoob / http://mrdoob.com/
  32001. * @author Mugen87 / https://github.com/Mugen87
  32002. */
  32003. THREE.ColladaLoader = function ( manager ) {
  32004. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  32005. };
  32006. THREE.ColladaLoader.prototype = {
  32007. constructor: THREE.ColladaLoader,
  32008. crossOrigin: 'Anonymous',
  32009. load: function ( url, onLoad, onProgress, onError ) {
  32010. var scope = this;
  32011. var path = scope.path === undefined ? THREE.LoaderUtils.extractUrlBase( url ) : scope.path;
  32012. var loader = new THREE.FileLoader( scope.manager );
  32013. loader.load( url, function ( text ) {
  32014. onLoad( scope.parse( text, path ) );
  32015. }, onProgress, onError );
  32016. },
  32017. setPath: function ( value ) {
  32018. this.path = value;
  32019. },
  32020. options: {
  32021. set convertUpAxis( value ) {
  32022. console.warn( 'THREE.ColladaLoader: options.convertUpAxis() has been removed. Up axis is converted automatically.' );
  32023. }
  32024. },
  32025. setCrossOrigin: function ( value ) {
  32026. this.crossOrigin = value;
  32027. },
  32028. parse: function ( text, path ) {
  32029. function getElementsByTagName( xml, name ) {
  32030. // Non recursive xml.getElementsByTagName() ...
  32031. var array = [];
  32032. var childNodes = xml.childNodes;
  32033. for ( var i = 0, l = childNodes.length; i < l; i ++ ) {
  32034. var child = childNodes[ i ];
  32035. if ( child.nodeName === name ) {
  32036. array.push( child );
  32037. }
  32038. }
  32039. return array;
  32040. }
  32041. function parseStrings( text ) {
  32042. if ( text.length === 0 ) return [];
  32043. var parts = text.trim().split( /\s+/ );
  32044. var array = new Array( parts.length );
  32045. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32046. array[ i ] = parts[ i ];
  32047. }
  32048. return array;
  32049. }
  32050. function parseFloats( text ) {
  32051. if ( text.length === 0 ) return [];
  32052. var parts = text.trim().split( /\s+/ );
  32053. var array = new Array( parts.length );
  32054. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32055. array[ i ] = parseFloat( parts[ i ] );
  32056. }
  32057. return array;
  32058. }
  32059. function parseInts( text ) {
  32060. if ( text.length === 0 ) return [];
  32061. var parts = text.trim().split( /\s+/ );
  32062. var array = new Array( parts.length );
  32063. for ( var i = 0, l = parts.length; i < l; i ++ ) {
  32064. array[ i ] = parseInt( parts[ i ] );
  32065. }
  32066. return array;
  32067. }
  32068. function parseId( text ) {
  32069. return text.substring( 1 );
  32070. }
  32071. function generateId() {
  32072. return 'three_default_' + ( count ++ );
  32073. }
  32074. function isEmpty( object ) {
  32075. return Object.keys( object ).length === 0;
  32076. }
  32077. // asset
  32078. function parseAsset( xml ) {
  32079. return {
  32080. unit: parseAssetUnit( getElementsByTagName( xml, 'unit' )[ 0 ] ),
  32081. upAxis: parseAssetUpAxis( getElementsByTagName( xml, 'up_axis' )[ 0 ] )
  32082. };
  32083. }
  32084. function parseAssetUnit( xml ) {
  32085. return xml !== undefined ? parseFloat( xml.getAttribute( 'meter' ) ) : 1;
  32086. }
  32087. function parseAssetUpAxis( xml ) {
  32088. return xml !== undefined ? xml.textContent : 'Y_UP';
  32089. }
  32090. // library
  32091. function parseLibrary( xml, libraryName, nodeName, parser ) {
  32092. var library = getElementsByTagName( xml, libraryName )[ 0 ];
  32093. if ( library !== undefined ) {
  32094. var elements = getElementsByTagName( library, nodeName );
  32095. for ( var i = 0; i < elements.length; i ++ ) {
  32096. parser( elements[ i ] );
  32097. }
  32098. }
  32099. }
  32100. function buildLibrary( data, builder ) {
  32101. for ( var name in data ) {
  32102. var object = data[ name ];
  32103. object.build = builder( data[ name ] );
  32104. }
  32105. }
  32106. // get
  32107. function getBuild( data, builder ) {
  32108. if ( data.build !== undefined ) return data.build;
  32109. data.build = builder( data );
  32110. return data.build;
  32111. }
  32112. // animation
  32113. function parseAnimation( xml ) {
  32114. var data = {
  32115. sources: {},
  32116. samplers: {},
  32117. channels: {}
  32118. };
  32119. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32120. var child = xml.childNodes[ i ];
  32121. if ( child.nodeType !== 1 ) continue;
  32122. var id;
  32123. switch ( child.nodeName ) {
  32124. case 'source':
  32125. id = child.getAttribute( 'id' );
  32126. data.sources[ id ] = parseSource( child );
  32127. break;
  32128. case 'sampler':
  32129. id = child.getAttribute( 'id' );
  32130. data.samplers[ id ] = parseAnimationSampler( child );
  32131. break;
  32132. case 'channel':
  32133. id = child.getAttribute( 'target' );
  32134. data.channels[ id ] = parseAnimationChannel( child );
  32135. break;
  32136. default:
  32137. console.log( child );
  32138. }
  32139. }
  32140. library.animations[ xml.getAttribute( 'id' ) ] = data;
  32141. }
  32142. function parseAnimationSampler( xml ) {
  32143. var data = {
  32144. inputs: {},
  32145. };
  32146. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32147. var child = xml.childNodes[ i ];
  32148. if ( child.nodeType !== 1 ) continue;
  32149. switch ( child.nodeName ) {
  32150. case 'input':
  32151. var id = parseId( child.getAttribute( 'source' ) );
  32152. var semantic = child.getAttribute( 'semantic' );
  32153. data.inputs[ semantic ] = id;
  32154. break;
  32155. }
  32156. }
  32157. return data;
  32158. }
  32159. function parseAnimationChannel( xml ) {
  32160. var data = {};
  32161. var target = xml.getAttribute( 'target' );
  32162. // parsing SID Addressing Syntax
  32163. var parts = target.split( '/' );
  32164. var id = parts.shift();
  32165. var sid = parts.shift();
  32166. // check selection syntax
  32167. var arraySyntax = ( sid.indexOf( '(' ) !== - 1 );
  32168. var memberSyntax = ( sid.indexOf( '.' ) !== - 1 );
  32169. if ( memberSyntax ) {
  32170. // member selection access
  32171. parts = sid.split( '.' );
  32172. sid = parts.shift();
  32173. data.member = parts.shift();
  32174. } else if ( arraySyntax ) {
  32175. // array-access syntax. can be used to express fields in one-dimensional vectors or two-dimensional matrices.
  32176. var indices = sid.split( '(' );
  32177. sid = indices.shift();
  32178. for ( var i = 0; i < indices.length; i ++ ) {
  32179. indices[ i ] = parseInt( indices[ i ].replace( /\)/, '' ) );
  32180. }
  32181. data.indices = indices;
  32182. }
  32183. data.id = id;
  32184. data.sid = sid;
  32185. data.arraySyntax = arraySyntax;
  32186. data.memberSyntax = memberSyntax;
  32187. data.sampler = parseId( xml.getAttribute( 'source' ) );
  32188. return data;
  32189. }
  32190. function buildAnimation( data ) {
  32191. var tracks = [];
  32192. var channels = data.channels;
  32193. var samplers = data.samplers;
  32194. var sources = data.sources;
  32195. for ( var target in channels ) {
  32196. if ( channels.hasOwnProperty( target ) ) {
  32197. var channel = channels[ target ];
  32198. var sampler = samplers[ channel.sampler ];
  32199. var inputId = sampler.inputs.INPUT;
  32200. var outputId = sampler.inputs.OUTPUT;
  32201. var inputSource = sources[ inputId ];
  32202. var outputSource = sources[ outputId ];
  32203. var animation = buildAnimationChannel( channel, inputSource, outputSource );
  32204. createKeyframeTracks( animation, tracks );
  32205. }
  32206. }
  32207. return tracks;
  32208. }
  32209. function getAnimation( id ) {
  32210. return getBuild( library.animations[ id ], buildAnimation );
  32211. }
  32212. function buildAnimationChannel( channel, inputSource, outputSource ) {
  32213. var node = library.nodes[ channel.id ];
  32214. var object3D = getNode( node.id );
  32215. var transform = node.transforms[ channel.sid ];
  32216. var defaultMatrix = node.matrix.clone().transpose();
  32217. var time, stride;
  32218. var i, il, j, jl;
  32219. var data = {};
  32220. // the collada spec allows the animation of data in various ways.
  32221. // depending on the transform type (matrix, translate, rotate, scale), we execute different logic
  32222. switch ( transform ) {
  32223. case 'matrix':
  32224. for ( i = 0, il = inputSource.array.length; i < il; i ++ ) {
  32225. time = inputSource.array[ i ];
  32226. stride = i * outputSource.stride;
  32227. if ( data[ time ] === undefined ) data[ time ] = {};
  32228. if ( channel.arraySyntax === true ) {
  32229. var value = outputSource.array[ stride ];
  32230. var index = channel.indices[ 0 ] + 4 * channel.indices[ 1 ];
  32231. data[ time ][ index ] = value;
  32232. } else {
  32233. for ( j = 0, jl = outputSource.stride; j < jl; j ++ ) {
  32234. data[ time ][ j ] = outputSource.array[ stride + j ];
  32235. }
  32236. }
  32237. }
  32238. break;
  32239. case 'translate':
  32240. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32241. break;
  32242. case 'rotate':
  32243. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32244. break;
  32245. case 'scale':
  32246. console.warn( 'THREE.ColladaLoader: Animation transform type "%s" not yet implemented.', transform );
  32247. break;
  32248. }
  32249. var keyframes = prepareAnimationData( data, defaultMatrix );
  32250. var animation = {
  32251. name: object3D.uuid,
  32252. keyframes: keyframes
  32253. };
  32254. return animation;
  32255. }
  32256. function prepareAnimationData( data, defaultMatrix ) {
  32257. var keyframes = [];
  32258. // transfer data into a sortable array
  32259. for ( var time in data ) {
  32260. keyframes.push( { time: parseFloat( time ), value: data[ time ] } );
  32261. }
  32262. // ensure keyframes are sorted by time
  32263. keyframes.sort( ascending );
  32264. // now we clean up all animation data, so we can use them for keyframe tracks
  32265. for ( var i = 0; i < 16; i ++ ) {
  32266. transformAnimationData( keyframes, i, defaultMatrix.elements[ i ] );
  32267. }
  32268. return keyframes;
  32269. // array sort function
  32270. function ascending( a, b ) {
  32271. return a.time - b.time;
  32272. }
  32273. }
  32274. var position = new THREE.Vector3();
  32275. var scale = new THREE.Vector3();
  32276. var quaternion = new THREE.Quaternion();
  32277. function createKeyframeTracks( animation, tracks ) {
  32278. var keyframes = animation.keyframes;
  32279. var name = animation.name;
  32280. var times = [];
  32281. var positionData = [];
  32282. var quaternionData = [];
  32283. var scaleData = [];
  32284. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32285. var keyframe = keyframes[ i ];
  32286. var time = keyframe.time;
  32287. var value = keyframe.value;
  32288. matrix.fromArray( value ).transpose();
  32289. matrix.decompose( position, quaternion, scale );
  32290. times.push( time );
  32291. positionData.push( position.x, position.y, position.z );
  32292. quaternionData.push( quaternion.x, quaternion.y, quaternion.z, quaternion.w );
  32293. scaleData.push( scale.x, scale.y, scale.z );
  32294. }
  32295. if ( positionData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.position', times, positionData ) );
  32296. if ( quaternionData.length > 0 ) tracks.push( new THREE.QuaternionKeyframeTrack( name + '.quaternion', times, quaternionData ) );
  32297. if ( scaleData.length > 0 ) tracks.push( new THREE.VectorKeyframeTrack( name + '.scale', times, scaleData ) );
  32298. return tracks;
  32299. }
  32300. function transformAnimationData( keyframes, property, defaultValue ) {
  32301. var keyframe;
  32302. var empty = true;
  32303. var i, l;
  32304. // check, if values of a property are missing in our keyframes
  32305. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32306. keyframe = keyframes[ i ];
  32307. if ( keyframe.value[ property ] === undefined ) {
  32308. keyframe.value[ property ] = null; // mark as missing
  32309. } else {
  32310. empty = false;
  32311. }
  32312. }
  32313. if ( empty === true ) {
  32314. // no values at all, so we set a default value
  32315. for ( i = 0, l = keyframes.length; i < l; i ++ ) {
  32316. keyframe = keyframes[ i ];
  32317. keyframe.value[ property ] = defaultValue;
  32318. }
  32319. } else {
  32320. // filling gaps
  32321. createMissingKeyframes( keyframes, property );
  32322. }
  32323. }
  32324. function createMissingKeyframes( keyframes, property ) {
  32325. var prev, next;
  32326. for ( var i = 0, l = keyframes.length; i < l; i ++ ) {
  32327. var keyframe = keyframes[ i ];
  32328. if ( keyframe.value[ property ] === null ) {
  32329. prev = getPrev( keyframes, i, property );
  32330. next = getNext( keyframes, i, property );
  32331. if ( prev === null ) {
  32332. keyframe.value[ property ] = next.value[ property ];
  32333. continue;
  32334. }
  32335. if ( next === null ) {
  32336. keyframe.value[ property ] = prev.value[ property ];
  32337. continue;
  32338. }
  32339. interpolate( keyframe, prev, next, property );
  32340. }
  32341. }
  32342. }
  32343. function getPrev( keyframes, i, property ) {
  32344. while ( i >= 0 ) {
  32345. var keyframe = keyframes[ i ];
  32346. if ( keyframe.value[ property ] !== null ) return keyframe;
  32347. i --;
  32348. }
  32349. return null;
  32350. }
  32351. function getNext( keyframes, i, property ) {
  32352. while ( i < keyframes.length ) {
  32353. var keyframe = keyframes[ i ];
  32354. if ( keyframe.value[ property ] !== null ) return keyframe;
  32355. i ++;
  32356. }
  32357. return null;
  32358. }
  32359. function interpolate( key, prev, next, property ) {
  32360. if ( ( next.time - prev.time ) === 0 ) {
  32361. key.value[ property ] = prev.value[ property ];
  32362. return;
  32363. }
  32364. key.value[ property ] = ( ( key.time - prev.time ) * ( next.value[ property ] - prev.value[ property ] ) / ( next.time - prev.time ) ) + prev.value[ property ];
  32365. }
  32366. // animation clips
  32367. function parseAnimationClip( xml ) {
  32368. var data = {
  32369. name: xml.getAttribute( 'id' ) || 'default',
  32370. start: parseFloat( xml.getAttribute( 'start' ) || 0 ),
  32371. end: parseFloat( xml.getAttribute( 'end' ) || 0 ),
  32372. animations: []
  32373. };
  32374. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32375. var child = xml.childNodes[ i ];
  32376. if ( child.nodeType !== 1 ) continue;
  32377. switch ( child.nodeName ) {
  32378. case 'instance_animation':
  32379. data.animations.push( parseId( child.getAttribute( 'url' ) ) );
  32380. break;
  32381. }
  32382. }
  32383. library.clips[ xml.getAttribute( 'id' ) ] = data;
  32384. }
  32385. function buildAnimationClip( data ) {
  32386. var tracks = [];
  32387. var name = data.name;
  32388. var duration = ( data.end - data.start ) || - 1;
  32389. var animations = data.animations;
  32390. for ( var i = 0, il = animations.length; i < il; i ++ ) {
  32391. var animationTracks = getAnimation( animations[ i ] );
  32392. for ( var j = 0, jl = animationTracks.length; j < jl; j ++ ) {
  32393. tracks.push( animationTracks[ j ] );
  32394. }
  32395. }
  32396. return new THREE.AnimationClip( name, duration, tracks );
  32397. }
  32398. function getAnimationClip( id ) {
  32399. return getBuild( library.clips[ id ], buildAnimationClip );
  32400. }
  32401. // controller
  32402. function parseController( xml ) {
  32403. var data = {};
  32404. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32405. var child = xml.childNodes[ i ];
  32406. if ( child.nodeType !== 1 ) continue;
  32407. switch ( child.nodeName ) {
  32408. case 'skin':
  32409. // there is exactly one skin per controller
  32410. data.id = parseId( child.getAttribute( 'source' ) );
  32411. data.skin = parseSkin( child );
  32412. break;
  32413. case 'morph':
  32414. data.id = parseId( child.getAttribute( 'source' ) );
  32415. console.warn( 'THREE.ColladaLoader: Morph target animation not supported yet.' );
  32416. break;
  32417. }
  32418. }
  32419. library.controllers[ xml.getAttribute( 'id' ) ] = data;
  32420. }
  32421. function parseSkin( xml ) {
  32422. var data = {
  32423. sources: {}
  32424. };
  32425. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32426. var child = xml.childNodes[ i ];
  32427. if ( child.nodeType !== 1 ) continue;
  32428. switch ( child.nodeName ) {
  32429. case 'bind_shape_matrix':
  32430. data.bindShapeMatrix = parseFloats( child.textContent );
  32431. break;
  32432. case 'source':
  32433. var id = child.getAttribute( 'id' );
  32434. data.sources[ id ] = parseSource( child );
  32435. break;
  32436. case 'joints':
  32437. data.joints = parseJoints( child );
  32438. break;
  32439. case 'vertex_weights':
  32440. data.vertexWeights = parseVertexWeights( child );
  32441. break;
  32442. }
  32443. }
  32444. return data;
  32445. }
  32446. function parseJoints( xml ) {
  32447. var data = {
  32448. inputs: {}
  32449. };
  32450. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32451. var child = xml.childNodes[ i ];
  32452. if ( child.nodeType !== 1 ) continue;
  32453. switch ( child.nodeName ) {
  32454. case 'input':
  32455. var semantic = child.getAttribute( 'semantic' );
  32456. var id = parseId( child.getAttribute( 'source' ) );
  32457. data.inputs[ semantic ] = id;
  32458. break;
  32459. }
  32460. }
  32461. return data;
  32462. }
  32463. function parseVertexWeights( xml ) {
  32464. var data = {
  32465. inputs: {}
  32466. };
  32467. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32468. var child = xml.childNodes[ i ];
  32469. if ( child.nodeType !== 1 ) continue;
  32470. switch ( child.nodeName ) {
  32471. case 'input':
  32472. var semantic = child.getAttribute( 'semantic' );
  32473. var id = parseId( child.getAttribute( 'source' ) );
  32474. var offset = parseInt( child.getAttribute( 'offset' ) );
  32475. data.inputs[ semantic ] = { id: id, offset: offset };
  32476. break;
  32477. case 'vcount':
  32478. data.vcount = parseInts( child.textContent );
  32479. break;
  32480. case 'v':
  32481. data.v = parseInts( child.textContent );
  32482. break;
  32483. }
  32484. }
  32485. return data;
  32486. }
  32487. function buildController( data ) {
  32488. var build = {
  32489. id: data.id
  32490. };
  32491. var geometry = library.geometries[ build.id ];
  32492. if ( data.skin !== undefined ) {
  32493. build.skin = buildSkin( data.skin );
  32494. // we enhance the 'sources' property of the corresponding geometry with our skin data
  32495. geometry.sources.skinIndices = build.skin.indices;
  32496. geometry.sources.skinWeights = build.skin.weights;
  32497. }
  32498. return build;
  32499. }
  32500. function buildSkin( data ) {
  32501. var BONE_LIMIT = 4;
  32502. var build = {
  32503. joints: [], // this must be an array to preserve the joint order
  32504. indices: {
  32505. array: [],
  32506. stride: BONE_LIMIT
  32507. },
  32508. weights: {
  32509. array: [],
  32510. stride: BONE_LIMIT
  32511. }
  32512. };
  32513. var sources = data.sources;
  32514. var vertexWeights = data.vertexWeights;
  32515. var vcount = vertexWeights.vcount;
  32516. var v = vertexWeights.v;
  32517. var jointOffset = vertexWeights.inputs.JOINT.offset;
  32518. var weightOffset = vertexWeights.inputs.WEIGHT.offset;
  32519. var jointSource = data.sources[ data.joints.inputs.JOINT ];
  32520. var inverseSource = data.sources[ data.joints.inputs.INV_BIND_MATRIX ];
  32521. var weights = sources[ vertexWeights.inputs.WEIGHT.id ].array;
  32522. var stride = 0;
  32523. var i, j, l;
  32524. // procces skin data for each vertex
  32525. for ( i = 0, l = vcount.length; i < l; i ++ ) {
  32526. var jointCount = vcount[ i ]; // this is the amount of joints that affect a single vertex
  32527. var vertexSkinData = [];
  32528. for ( j = 0; j < jointCount; j ++ ) {
  32529. var skinIndex = v[ stride + jointOffset ];
  32530. var weightId = v[ stride + weightOffset ];
  32531. var skinWeight = weights[ weightId ];
  32532. vertexSkinData.push( { index: skinIndex, weight: skinWeight } );
  32533. stride += 2;
  32534. }
  32535. // we sort the joints in descending order based on the weights.
  32536. // this ensures, we only procced the most important joints of the vertex
  32537. vertexSkinData.sort( descending );
  32538. // now we provide for each vertex a set of four index and weight values.
  32539. // the order of the skin data matches the order of vertices
  32540. for ( j = 0; j < BONE_LIMIT; j ++ ) {
  32541. var d = vertexSkinData[ j ];
  32542. if ( d !== undefined ) {
  32543. build.indices.array.push( d.index );
  32544. build.weights.array.push( d.weight );
  32545. } else {
  32546. build.indices.array.push( 0 );
  32547. build.weights.array.push( 0 );
  32548. }
  32549. }
  32550. }
  32551. // setup bind matrix
  32552. build.bindMatrix = new THREE.Matrix4().fromArray( data.bindShapeMatrix ).transpose();
  32553. // process bones and inverse bind matrix data
  32554. for ( i = 0, l = jointSource.array.length; i < l; i ++ ) {
  32555. var name = jointSource.array[ i ];
  32556. var boneInverse = new THREE.Matrix4().fromArray( inverseSource.array, i * inverseSource.stride ).transpose();
  32557. build.joints.push( { name: name, boneInverse: boneInverse } );
  32558. }
  32559. return build;
  32560. // array sort function
  32561. function descending( a, b ) {
  32562. return b.weight - a.weight;
  32563. }
  32564. }
  32565. function getController( id ) {
  32566. return getBuild( library.controllers[ id ], buildController );
  32567. }
  32568. // image
  32569. function parseImage( xml ) {
  32570. var data = {
  32571. init_from: getElementsByTagName( xml, 'init_from' )[ 0 ].textContent
  32572. };
  32573. library.images[ xml.getAttribute( 'id' ) ] = data;
  32574. }
  32575. function buildImage( data ) {
  32576. if ( data.build !== undefined ) return data.build;
  32577. return data.init_from;
  32578. }
  32579. function getImage( id ) {
  32580. return getBuild( library.images[ id ], buildImage );
  32581. }
  32582. // effect
  32583. function parseEffect( xml ) {
  32584. var data = {};
  32585. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32586. var child = xml.childNodes[ i ];
  32587. if ( child.nodeType !== 1 ) continue;
  32588. switch ( child.nodeName ) {
  32589. case 'profile_COMMON':
  32590. data.profile = parseEffectProfileCOMMON( child );
  32591. break;
  32592. }
  32593. }
  32594. library.effects[ xml.getAttribute( 'id' ) ] = data;
  32595. }
  32596. function parseEffectProfileCOMMON( xml ) {
  32597. var data = {
  32598. surfaces: {},
  32599. samplers: {}
  32600. };
  32601. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32602. var child = xml.childNodes[ i ];
  32603. if ( child.nodeType !== 1 ) continue;
  32604. switch ( child.nodeName ) {
  32605. case 'newparam':
  32606. parseEffectNewparam( child, data );
  32607. break;
  32608. case 'technique':
  32609. data.technique = parseEffectTechnique( child );
  32610. break;
  32611. }
  32612. }
  32613. return data;
  32614. }
  32615. function parseEffectNewparam( xml, data ) {
  32616. var sid = xml.getAttribute( 'sid' );
  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 'surface':
  32622. data.surfaces[ sid ] = parseEffectSurface( child );
  32623. break;
  32624. case 'sampler2D':
  32625. data.samplers[ sid ] = parseEffectSampler( child );
  32626. break;
  32627. }
  32628. }
  32629. }
  32630. function parseEffectSurface( xml ) {
  32631. var data = {};
  32632. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32633. var child = xml.childNodes[ i ];
  32634. if ( child.nodeType !== 1 ) continue;
  32635. switch ( child.nodeName ) {
  32636. case 'init_from':
  32637. data.init_from = child.textContent;
  32638. break;
  32639. }
  32640. }
  32641. return data;
  32642. }
  32643. function parseEffectSampler( xml ) {
  32644. var data = {};
  32645. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32646. var child = xml.childNodes[ i ];
  32647. if ( child.nodeType !== 1 ) continue;
  32648. switch ( child.nodeName ) {
  32649. case 'source':
  32650. data.source = child.textContent;
  32651. break;
  32652. }
  32653. }
  32654. return data;
  32655. }
  32656. function parseEffectTechnique( xml ) {
  32657. var data = {};
  32658. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32659. var child = xml.childNodes[ i ];
  32660. if ( child.nodeType !== 1 ) continue;
  32661. switch ( child.nodeName ) {
  32662. case 'constant':
  32663. case 'lambert':
  32664. case 'blinn':
  32665. case 'phong':
  32666. data.type = child.nodeName;
  32667. data.parameters = parseEffectParameters( child );
  32668. break;
  32669. }
  32670. }
  32671. return data;
  32672. }
  32673. function parseEffectParameters( xml ) {
  32674. var data = {};
  32675. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32676. var child = xml.childNodes[ i ];
  32677. if ( child.nodeType !== 1 ) continue;
  32678. switch ( child.nodeName ) {
  32679. case 'emission':
  32680. case 'diffuse':
  32681. case 'specular':
  32682. case 'shininess':
  32683. case 'transparent':
  32684. case 'transparency':
  32685. data[ child.nodeName ] = parseEffectParameter( child );
  32686. break;
  32687. }
  32688. }
  32689. return data;
  32690. }
  32691. function parseEffectParameter( xml ) {
  32692. var data = {};
  32693. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32694. var child = xml.childNodes[ i ];
  32695. if ( child.nodeType !== 1 ) continue;
  32696. switch ( child.nodeName ) {
  32697. case 'color':
  32698. data[ child.nodeName ] = parseFloats( child.textContent );
  32699. break;
  32700. case 'float':
  32701. data[ child.nodeName ] = parseFloat( child.textContent );
  32702. break;
  32703. case 'texture':
  32704. data[ child.nodeName ] = { id: child.getAttribute( 'texture' ), extra: parseEffectParameterTexture( child ) };
  32705. break;
  32706. }
  32707. }
  32708. return data;
  32709. }
  32710. function parseEffectParameterTexture( xml ) {
  32711. var data = {
  32712. technique: {}
  32713. };
  32714. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32715. var child = xml.childNodes[ i ];
  32716. if ( child.nodeType !== 1 ) continue;
  32717. switch ( child.nodeName ) {
  32718. case 'extra':
  32719. parseEffectParameterTextureExtra( child, data );
  32720. break;
  32721. }
  32722. }
  32723. return data;
  32724. }
  32725. function parseEffectParameterTextureExtra( xml, data ) {
  32726. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32727. var child = xml.childNodes[ i ];
  32728. if ( child.nodeType !== 1 ) continue;
  32729. switch ( child.nodeName ) {
  32730. case 'technique':
  32731. parseEffectParameterTextureExtraTechnique( child, data );
  32732. break;
  32733. }
  32734. }
  32735. }
  32736. function parseEffectParameterTextureExtraTechnique( xml, data ) {
  32737. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32738. var child = xml.childNodes[ i ];
  32739. if ( child.nodeType !== 1 ) continue;
  32740. switch ( child.nodeName ) {
  32741. case 'repeatU':
  32742. case 'repeatV':
  32743. case 'offsetU':
  32744. case 'offsetV':
  32745. data.technique[ child.nodeName ] = parseFloat( child.textContent );
  32746. break;
  32747. case 'wrapU':
  32748. case 'wrapV':
  32749. // some files have values for wrapU/wrapV which become NaN via parseInt
  32750. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  32751. data.technique[ child.nodeName ] = 1;
  32752. } else if ( child.textContent.toUpperCase() === 'FALSE' ) {
  32753. data.technique[ child.nodeName ] = 0;
  32754. } else {
  32755. data.technique[ child.nodeName ] = parseInt( child.textContent );
  32756. }
  32757. break;
  32758. }
  32759. }
  32760. }
  32761. function buildEffect( data ) {
  32762. return data;
  32763. }
  32764. function getEffect( id ) {
  32765. return getBuild( library.effects[ id ], buildEffect );
  32766. }
  32767. // material
  32768. function parseMaterial( xml ) {
  32769. var data = {
  32770. name: xml.getAttribute( 'name' )
  32771. };
  32772. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32773. var child = xml.childNodes[ i ];
  32774. if ( child.nodeType !== 1 ) continue;
  32775. switch ( child.nodeName ) {
  32776. case 'instance_effect':
  32777. data.url = parseId( child.getAttribute( 'url' ) );
  32778. break;
  32779. }
  32780. }
  32781. library.materials[ xml.getAttribute( 'id' ) ] = data;
  32782. }
  32783. function buildMaterial( data ) {
  32784. var effect = getEffect( data.url );
  32785. var technique = effect.profile.technique;
  32786. var material;
  32787. switch ( technique.type ) {
  32788. case 'phong':
  32789. case 'blinn':
  32790. material = new THREE.MeshPhongMaterial();
  32791. break;
  32792. case 'lambert':
  32793. material = new THREE.MeshLambertMaterial();
  32794. break;
  32795. default:
  32796. material = new THREE.MeshBasicMaterial();
  32797. break;
  32798. }
  32799. material.name = data.name;
  32800. function getTexture( textureObject ) {
  32801. var sampler = effect.profile.samplers[ textureObject.id ];
  32802. if ( sampler !== undefined ) {
  32803. var surface = effect.profile.surfaces[ sampler.source ];
  32804. var texture = textureLoader.load( getImage( surface.init_from ) );
  32805. var extra = textureObject.extra;
  32806. if ( extra !== undefined && extra.technique !== undefined && isEmpty( extra.technique ) === false ) {
  32807. var technique = extra.technique;
  32808. texture.wrapS = technique.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  32809. texture.wrapT = technique.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  32810. texture.offset.set( technique.offsetU || 0, technique.offsetV || 0 );
  32811. texture.repeat.set( technique.repeatU || 1, technique.repeatV || 1 );
  32812. } else {
  32813. texture.wrapS = THREE.RepeatWrapping;
  32814. texture.wrapT = THREE.RepeatWrapping;
  32815. }
  32816. return texture;
  32817. }
  32818. console.error( 'THREE.ColladaLoader: Undefined sampler', textureObject.id );
  32819. return null;
  32820. }
  32821. var parameters = technique.parameters;
  32822. for ( var key in parameters ) {
  32823. var parameter = parameters[ key ];
  32824. switch ( key ) {
  32825. case 'diffuse':
  32826. if ( parameter.color ) material.color.fromArray( parameter.color );
  32827. if ( parameter.texture ) material.map = getTexture( parameter.texture );
  32828. break;
  32829. case 'specular':
  32830. if ( parameter.color && material.specular ) material.specular.fromArray( parameter.color );
  32831. if ( parameter.texture ) material.specularMap = getTexture( parameter.texture );
  32832. break;
  32833. case 'shininess':
  32834. if ( parameter.float && material.shininess )
  32835. material.shininess = parameter.float;
  32836. break;
  32837. case 'emission':
  32838. if ( parameter.color && material.emissive )
  32839. material.emissive.fromArray( parameter.color );
  32840. break;
  32841. case 'transparent':
  32842. // if ( parameter.texture ) material.alphaMap = getTexture( parameter.texture );
  32843. material.transparent = true;
  32844. break;
  32845. case 'transparency':
  32846. if ( parameter.float !== undefined ) material.opacity = parameter.float;
  32847. material.transparent = true;
  32848. break;
  32849. }
  32850. }
  32851. return material;
  32852. }
  32853. function getMaterial( id ) {
  32854. return getBuild( library.materials[ id ], buildMaterial );
  32855. }
  32856. // camera
  32857. function parseCamera( xml ) {
  32858. var data = {
  32859. name: xml.getAttribute( 'name' )
  32860. };
  32861. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32862. var child = xml.childNodes[ i ];
  32863. if ( child.nodeType !== 1 ) continue;
  32864. switch ( child.nodeName ) {
  32865. case 'optics':
  32866. data.optics = parseCameraOptics( child );
  32867. break;
  32868. }
  32869. }
  32870. library.cameras[ xml.getAttribute( 'id' ) ] = data;
  32871. }
  32872. function parseCameraOptics( xml ) {
  32873. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  32874. var child = xml.childNodes[ i ];
  32875. switch ( child.nodeName ) {
  32876. case 'technique_common':
  32877. return parseCameraTechnique( child );
  32878. }
  32879. }
  32880. return {};
  32881. }
  32882. function parseCameraTechnique( xml ) {
  32883. var data = {};
  32884. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  32885. var child = xml.childNodes[ i ];
  32886. switch ( child.nodeName ) {
  32887. case 'perspective':
  32888. case 'orthographic':
  32889. data.technique = child.nodeName;
  32890. data.parameters = parseCameraParameters( child );
  32891. break;
  32892. }
  32893. }
  32894. return data;
  32895. }
  32896. function parseCameraParameters( xml ) {
  32897. var data = {};
  32898. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  32899. var child = xml.childNodes[ i ];
  32900. switch ( child.nodeName ) {
  32901. case 'xfov':
  32902. case 'yfov':
  32903. case 'xmag':
  32904. case 'ymag':
  32905. case 'znear':
  32906. case 'zfar':
  32907. case 'aspect_ratio':
  32908. data[ child.nodeName ] = parseFloat( child.textContent );
  32909. break;
  32910. }
  32911. }
  32912. return data;
  32913. }
  32914. function buildCamera( data ) {
  32915. var camera;
  32916. switch ( data.optics.technique ) {
  32917. case 'perspective':
  32918. camera = new THREE.PerspectiveCamera(
  32919. data.optics.parameters.yfov,
  32920. data.optics.parameters.aspect_ratio,
  32921. data.optics.parameters.znear,
  32922. data.optics.parameters.zfar
  32923. );
  32924. break;
  32925. case 'orthographic':
  32926. var ymag = data.optics.parameters.ymag;
  32927. var xmag = data.optics.parameters.xmag;
  32928. var aspectRatio = data.optics.parameters.aspect_ratio;
  32929. xmag = ( xmag === undefined ) ? ( ymag * aspectRatio ) : xmag;
  32930. ymag = ( ymag === undefined ) ? ( xmag / aspectRatio ) : ymag;
  32931. xmag *= 0.5;
  32932. ymag *= 0.5;
  32933. camera = new THREE.OrthographicCamera(
  32934. - xmag, xmag, ymag, - ymag, // left, right, top, bottom
  32935. data.optics.parameters.znear,
  32936. data.optics.parameters.zfar
  32937. );
  32938. break;
  32939. default:
  32940. camera = new THREE.PerspectiveCamera();
  32941. break;
  32942. }
  32943. camera.name = data.name;
  32944. return camera;
  32945. }
  32946. function getCamera( id ) {
  32947. var data = library.cameras[ id ];
  32948. if ( data !== undefined ) {
  32949. return getBuild( data, buildCamera );
  32950. }
  32951. console.warn( 'THREE.ColladaLoader: Couldn\'t find camera with ID:', id );
  32952. return null;
  32953. }
  32954. // light
  32955. function parseLight( xml ) {
  32956. var data = {};
  32957. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32958. var child = xml.childNodes[ i ];
  32959. if ( child.nodeType !== 1 ) continue;
  32960. switch ( child.nodeName ) {
  32961. case 'technique_common':
  32962. data = parseLightTechnique( child );
  32963. break;
  32964. }
  32965. }
  32966. library.lights[ xml.getAttribute( 'id' ) ] = data;
  32967. }
  32968. function parseLightTechnique( xml ) {
  32969. var data = {};
  32970. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32971. var child = xml.childNodes[ i ];
  32972. if ( child.nodeType !== 1 ) continue;
  32973. switch ( child.nodeName ) {
  32974. case 'directional':
  32975. case 'point':
  32976. case 'spot':
  32977. case 'ambient':
  32978. data.technique = child.nodeName;
  32979. data.parameters = parseLightParameters( child );
  32980. }
  32981. }
  32982. return data;
  32983. }
  32984. function parseLightParameters( xml ) {
  32985. var data = {};
  32986. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  32987. var child = xml.childNodes[ i ];
  32988. if ( child.nodeType !== 1 ) continue;
  32989. switch ( child.nodeName ) {
  32990. case 'color':
  32991. var array = parseFloats( child.textContent );
  32992. data.color = new THREE.Color().fromArray( array );
  32993. break;
  32994. case 'falloff_angle':
  32995. data.falloffAngle = parseFloat( child.textContent );
  32996. break;
  32997. case 'quadratic_attenuation':
  32998. var f = parseFloat( child.textContent );
  32999. data.distance = f ? Math.sqrt( 1 / f ) : 0;
  33000. break;
  33001. }
  33002. }
  33003. return data;
  33004. }
  33005. function buildLight( data ) {
  33006. var light;
  33007. switch ( data.technique ) {
  33008. case 'directional':
  33009. light = new THREE.DirectionalLight();
  33010. break;
  33011. case 'point':
  33012. light = new THREE.PointLight();
  33013. break;
  33014. case 'spot':
  33015. light = new THREE.SpotLight();
  33016. break;
  33017. case 'ambient':
  33018. light = new THREE.AmbientLight();
  33019. break;
  33020. }
  33021. if ( data.parameters.color ) light.color.copy( data.parameters.color );
  33022. if ( data.parameters.distance ) light.distance = data.parameters.distance;
  33023. return light;
  33024. }
  33025. function getLight( id ) {
  33026. var data = library.lights[ id ];
  33027. if ( data !== undefined ) {
  33028. return getBuild( data, buildLight );
  33029. }
  33030. console.warn( 'THREE.ColladaLoader: Couldn\'t find light with ID:', id );
  33031. return null;
  33032. }
  33033. // geometry
  33034. function parseGeometry( xml ) {
  33035. var data = {
  33036. name: xml.getAttribute( 'name' ),
  33037. sources: {},
  33038. vertices: {},
  33039. primitives: []
  33040. };
  33041. var mesh = getElementsByTagName( xml, 'mesh' )[ 0 ];
  33042. // the following tags inside geometry are not supported yet (see https://github.com/mrdoob/three.js/pull/12606): convex_mesh, spline, brep
  33043. if ( mesh === undefined ) return;
  33044. for ( var i = 0; i < mesh.childNodes.length; i ++ ) {
  33045. var child = mesh.childNodes[ i ];
  33046. if ( child.nodeType !== 1 ) continue;
  33047. var id = child.getAttribute( 'id' );
  33048. switch ( child.nodeName ) {
  33049. case 'source':
  33050. data.sources[ id ] = parseSource( child );
  33051. break;
  33052. case 'vertices':
  33053. // data.sources[ id ] = data.sources[ parseId( getElementsByTagName( child, 'input' )[ 0 ].getAttribute( 'source' ) ) ];
  33054. data.vertices = parseGeometryVertices( child );
  33055. break;
  33056. case 'polygons':
  33057. console.warn( 'THREE.ColladaLoader: Unsupported primitive type: ', child.nodeName );
  33058. break;
  33059. case 'lines':
  33060. case 'linestrips':
  33061. case 'polylist':
  33062. case 'triangles':
  33063. data.primitives.push( parseGeometryPrimitive( child ) );
  33064. break;
  33065. default:
  33066. console.log( child );
  33067. }
  33068. }
  33069. library.geometries[ xml.getAttribute( 'id' ) ] = data;
  33070. }
  33071. function parseSource( xml ) {
  33072. var data = {
  33073. array: [],
  33074. stride: 3
  33075. };
  33076. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33077. var child = xml.childNodes[ i ];
  33078. if ( child.nodeType !== 1 ) continue;
  33079. switch ( child.nodeName ) {
  33080. case 'float_array':
  33081. data.array = parseFloats( child.textContent );
  33082. break;
  33083. case 'Name_array':
  33084. data.array = parseStrings( child.textContent );
  33085. break;
  33086. case 'technique_common':
  33087. var accessor = getElementsByTagName( child, 'accessor' )[ 0 ];
  33088. if ( accessor !== undefined ) {
  33089. data.stride = parseInt( accessor.getAttribute( 'stride' ) );
  33090. }
  33091. break;
  33092. }
  33093. }
  33094. return data;
  33095. }
  33096. function parseGeometryVertices( xml ) {
  33097. var data = {};
  33098. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33099. var child = xml.childNodes[ i ];
  33100. if ( child.nodeType !== 1 ) continue;
  33101. data[ child.getAttribute( 'semantic' ) ] = parseId( child.getAttribute( 'source' ) );
  33102. }
  33103. return data;
  33104. }
  33105. function parseGeometryPrimitive( xml ) {
  33106. var primitive = {
  33107. type: xml.nodeName,
  33108. material: xml.getAttribute( 'material' ),
  33109. count: parseInt( xml.getAttribute( 'count' ) ),
  33110. inputs: {},
  33111. stride: 0
  33112. };
  33113. for ( var i = 0, l = xml.childNodes.length; i < l; i ++ ) {
  33114. var child = xml.childNodes[ i ];
  33115. if ( child.nodeType !== 1 ) continue;
  33116. switch ( child.nodeName ) {
  33117. case 'input':
  33118. var id = parseId( child.getAttribute( 'source' ) );
  33119. var semantic = child.getAttribute( 'semantic' );
  33120. var offset = parseInt( child.getAttribute( 'offset' ) );
  33121. primitive.inputs[ semantic ] = { id: id, offset: offset };
  33122. primitive.stride = Math.max( primitive.stride, offset + 1 );
  33123. break;
  33124. case 'vcount':
  33125. primitive.vcount = parseInts( child.textContent );
  33126. break;
  33127. case 'p':
  33128. primitive.p = parseInts( child.textContent );
  33129. break;
  33130. }
  33131. }
  33132. return primitive;
  33133. }
  33134. function groupPrimitives( primitives ) {
  33135. var build = {};
  33136. for ( var i = 0; i < primitives.length; i ++ ) {
  33137. var primitive = primitives[ i ];
  33138. if ( build[ primitive.type ] === undefined ) build[ primitive.type ] = [];
  33139. build[ primitive.type ].push( primitive );
  33140. }
  33141. return build;
  33142. }
  33143. function buildGeometry( data ) {
  33144. var build = {};
  33145. var sources = data.sources;
  33146. var vertices = data.vertices;
  33147. var primitives = data.primitives;
  33148. if ( primitives.length === 0 ) return {};
  33149. // our goal is to create one buffer geoemtry for a single type of primitives
  33150. // first, we group all primitives by their type
  33151. var groupedPrimitives = groupPrimitives( primitives );
  33152. for ( var type in groupedPrimitives ) {
  33153. // second, we create for each type of primitives (polylist,triangles or lines) a buffer geometry
  33154. build[ type ] = buildGeometryType( groupedPrimitives[ type ], sources, vertices );
  33155. }
  33156. return build;
  33157. }
  33158. function buildGeometryType( primitives, sources, vertices ) {
  33159. var build = {};
  33160. var position = { array: [], stride: 0 };
  33161. var normal = { array: [], stride: 0 };
  33162. var uv = { array: [], stride: 0 };
  33163. var color = { array: [], stride: 0 };
  33164. var skinIndex = { array: [], stride: 4 };
  33165. var skinWeight = { array: [], stride: 4 };
  33166. var geometry = new THREE.BufferGeometry();
  33167. var materialKeys = [];
  33168. var start = 0, count = 0;
  33169. for ( var p = 0; p < primitives.length; p ++ ) {
  33170. var primitive = primitives[ p ];
  33171. var inputs = primitive.inputs;
  33172. var triangleCount = 1;
  33173. if ( primitive.vcount && primitive.vcount[ 0 ] === 4 ) {
  33174. triangleCount = 2; // one quad -> two triangles
  33175. }
  33176. // groups
  33177. if ( primitive.type === 'lines' || primitive.type === 'linestrips' ) {
  33178. count = primitive.count * 2;
  33179. } else {
  33180. count = primitive.count * 3 * triangleCount;
  33181. }
  33182. geometry.addGroup( start, count, p );
  33183. start += count;
  33184. // material
  33185. if ( primitive.material ) {
  33186. materialKeys.push( primitive.material );
  33187. }
  33188. // geometry data
  33189. for ( var name in inputs ) {
  33190. var input = inputs[ name ];
  33191. switch ( name ) {
  33192. case 'VERTEX':
  33193. for ( var key in vertices ) {
  33194. var id = vertices[ key ];
  33195. switch ( key ) {
  33196. case 'POSITION':
  33197. buildGeometryData( primitive, sources[ id ], input.offset, position.array );
  33198. position.stride = sources[ id ].stride;
  33199. if ( sources.skinWeights && sources.skinIndices ) {
  33200. buildGeometryData( primitive, sources.skinIndices, input.offset, skinIndex.array );
  33201. buildGeometryData( primitive, sources.skinWeights, input.offset, skinWeight.array );
  33202. }
  33203. break;
  33204. case 'NORMAL':
  33205. buildGeometryData( primitive, sources[ id ], input.offset, normal.array );
  33206. normal.stride = sources[ id ].stride;
  33207. break;
  33208. case 'COLOR':
  33209. buildGeometryData( primitive, sources[ id ], input.offset, color.array );
  33210. color.stride = sources[ id ].stride;
  33211. break;
  33212. case 'TEXCOORD':
  33213. buildGeometryData( primitive, sources[ id ], input.offset, uv.array );
  33214. uv.stride = sources[ id ].stride;
  33215. break;
  33216. default:
  33217. console.warn( 'THREE.ColladaLoader: Semantic "%s" not handled in geometry build process.', key );
  33218. }
  33219. }
  33220. break;
  33221. case 'NORMAL':
  33222. buildGeometryData( primitive, sources[ input.id ], input.offset, normal.array );
  33223. normal.stride = sources[ input.id ].stride;
  33224. break;
  33225. case 'COLOR':
  33226. buildGeometryData( primitive, sources[ input.id ], input.offset, color.array );
  33227. color.stride = sources[ input.id ].stride;
  33228. break;
  33229. case 'TEXCOORD':
  33230. buildGeometryData( primitive, sources[ input.id ], input.offset, uv.array );
  33231. uv.stride = sources[ input.id ].stride;
  33232. break;
  33233. }
  33234. }
  33235. }
  33236. // build geometry
  33237. if ( position.array.length > 0 ) geometry.addAttribute( 'position', new THREE.Float32BufferAttribute( position.array, position.stride ) );
  33238. if ( normal.array.length > 0 ) geometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( normal.array, normal.stride ) );
  33239. if ( color.array.length > 0 ) geometry.addAttribute( 'color', new THREE.Float32BufferAttribute( color.array, color.stride ) );
  33240. if ( uv.array.length > 0 ) geometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( uv.array, uv.stride ) );
  33241. if ( skinIndex.array.length > 0 ) geometry.addAttribute( 'skinIndex', new THREE.Float32BufferAttribute( skinIndex.array, skinIndex.stride ) );
  33242. if ( skinWeight.array.length > 0 ) geometry.addAttribute( 'skinWeight', new THREE.Float32BufferAttribute( skinWeight.array, skinWeight.stride ) );
  33243. build.data = geometry;
  33244. build.type = primitives[ 0 ].type;
  33245. build.materialKeys = materialKeys;
  33246. return build;
  33247. }
  33248. function buildGeometryData( primitive, source, offset, array ) {
  33249. var indices = primitive.p;
  33250. var stride = primitive.stride;
  33251. var vcount = primitive.vcount;
  33252. function pushVector( i ) {
  33253. var index = indices[ i + offset ] * sourceStride;
  33254. var length = index + sourceStride;
  33255. for ( ; index < length; index ++ ) {
  33256. array.push( sourceArray[ index ] );
  33257. }
  33258. }
  33259. var maxcount = 0;
  33260. var sourceArray = source.array;
  33261. var sourceStride = source.stride;
  33262. if ( primitive.vcount !== undefined ) {
  33263. var index = 0;
  33264. for ( var i = 0, l = vcount.length; i < l; i ++ ) {
  33265. var count = vcount[ i ];
  33266. if ( count === 4 ) {
  33267. var a = index + stride * 0;
  33268. var b = index + stride * 1;
  33269. var c = index + stride * 2;
  33270. var d = index + stride * 3;
  33271. pushVector( a ); pushVector( b ); pushVector( d );
  33272. pushVector( b ); pushVector( c ); pushVector( d );
  33273. } else if ( count === 3 ) {
  33274. var a = index + stride * 0;
  33275. var b = index + stride * 1;
  33276. var c = index + stride * 2;
  33277. pushVector( a ); pushVector( b ); pushVector( c );
  33278. } else {
  33279. maxcount = Math.max( maxcount, count );
  33280. }
  33281. index += stride * count;
  33282. }
  33283. if ( maxcount > 0 ) {
  33284. console.log( 'THREE.ColladaLoader: Geometry has faces with more than 4 vertices.' );
  33285. }
  33286. } else {
  33287. for ( var i = 0, l = indices.length; i < l; i += stride ) {
  33288. pushVector( i );
  33289. }
  33290. }
  33291. }
  33292. function getGeometry( id ) {
  33293. return getBuild( library.geometries[ id ], buildGeometry );
  33294. }
  33295. // kinematics
  33296. function parseKinematicsModel( xml ) {
  33297. var data = {
  33298. name: xml.getAttribute( 'name' ) || '',
  33299. joints: {},
  33300. links: []
  33301. };
  33302. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33303. var child = xml.childNodes[ i ];
  33304. if ( child.nodeType !== 1 ) continue;
  33305. switch ( child.nodeName ) {
  33306. case 'technique_common':
  33307. parseKinematicsTechniqueCommon( child, data );
  33308. break;
  33309. }
  33310. }
  33311. library.kinematicsModels[ xml.getAttribute( 'id' ) ] = data;
  33312. }
  33313. function buildKinematicsModel( data ) {
  33314. if ( data.build !== undefined ) return data.build;
  33315. return data;
  33316. }
  33317. function getKinematicsModel( id ) {
  33318. return getBuild( library.kinematicsModels[ id ], buildKinematicsModel );
  33319. }
  33320. function parseKinematicsTechniqueCommon( xml, data ) {
  33321. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33322. var child = xml.childNodes[ i ];
  33323. if ( child.nodeType !== 1 ) continue;
  33324. switch ( child.nodeName ) {
  33325. case 'joint':
  33326. data.joints[ child.getAttribute( 'sid' ) ] = parseKinematicsJoint( child );
  33327. break;
  33328. case 'link':
  33329. data.links.push( parseKinematicsLink( child ) );
  33330. break;
  33331. }
  33332. }
  33333. }
  33334. function parseKinematicsJoint( xml ) {
  33335. var data;
  33336. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33337. var child = xml.childNodes[ i ];
  33338. if ( child.nodeType !== 1 ) continue;
  33339. switch ( child.nodeName ) {
  33340. case 'prismatic':
  33341. case 'revolute':
  33342. data = parseKinematicsJointParameter( child );
  33343. break;
  33344. }
  33345. }
  33346. return data;
  33347. }
  33348. function parseKinematicsJointParameter( xml, data ) {
  33349. var data = {
  33350. sid: xml.getAttribute( 'sid' ),
  33351. name: xml.getAttribute( 'name' ) || '',
  33352. axis: new THREE.Vector3(),
  33353. limits: {
  33354. min: 0,
  33355. max: 0
  33356. },
  33357. type: xml.nodeName,
  33358. static: false,
  33359. zeroPosition: 0,
  33360. middlePosition: 0
  33361. };
  33362. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33363. var child = xml.childNodes[ i ];
  33364. if ( child.nodeType !== 1 ) continue;
  33365. switch ( child.nodeName ) {
  33366. case 'axis':
  33367. var array = parseFloats( child.textContent );
  33368. data.axis.fromArray( array );
  33369. break;
  33370. case 'limits':
  33371. var max = child.getElementsByTagName( 'max' )[ 0 ];
  33372. var min = child.getElementsByTagName( 'min' )[ 0 ];
  33373. data.limits.max = parseFloat( max.textContent );
  33374. data.limits.min = parseFloat( min.textContent );
  33375. break;
  33376. }
  33377. }
  33378. // if min is equal to or greater than max, consider the joint static
  33379. if ( data.limits.min >= data.limits.max ) {
  33380. data.static = true;
  33381. }
  33382. // calculate middle position
  33383. data.middlePosition = ( data.limits.min + data.limits.max ) / 2.0;
  33384. return data;
  33385. }
  33386. function parseKinematicsLink( xml ) {
  33387. var data = {
  33388. sid: xml.getAttribute( 'sid' ),
  33389. name: xml.getAttribute( 'name' ) || '',
  33390. attachments: [],
  33391. transforms: []
  33392. };
  33393. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33394. var child = xml.childNodes[ i ];
  33395. if ( child.nodeType !== 1 ) continue;
  33396. switch ( child.nodeName ) {
  33397. case 'attachment_full':
  33398. data.attachments.push( parseKinematicsAttachment( child ) );
  33399. break;
  33400. case 'matrix':
  33401. case 'translate':
  33402. case 'rotate':
  33403. data.transforms.push( parseKinematicsTransform( child ) );
  33404. break;
  33405. }
  33406. }
  33407. return data;
  33408. }
  33409. function parseKinematicsAttachment( xml ) {
  33410. var data = {
  33411. joint: xml.getAttribute( 'joint' ).split( '/' ).pop(),
  33412. transforms: [],
  33413. links: []
  33414. };
  33415. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33416. var child = xml.childNodes[ i ];
  33417. if ( child.nodeType !== 1 ) continue;
  33418. switch ( child.nodeName ) {
  33419. case 'link':
  33420. data.links.push( parseKinematicsLink( child ) );
  33421. break;
  33422. case 'matrix':
  33423. case 'translate':
  33424. case 'rotate':
  33425. data.transforms.push( parseKinematicsTransform( child ) );
  33426. break;
  33427. }
  33428. }
  33429. return data;
  33430. }
  33431. function parseKinematicsTransform( xml ) {
  33432. var data = {
  33433. type: xml.nodeName
  33434. };
  33435. var array = parseFloats( xml.textContent );
  33436. switch ( data.type ) {
  33437. case 'matrix':
  33438. data.obj = new THREE.Matrix4();
  33439. data.obj.fromArray( array ).transpose();
  33440. break;
  33441. case 'translate':
  33442. data.obj = new THREE.Vector3();
  33443. data.obj.fromArray( array );
  33444. break;
  33445. case 'rotate':
  33446. data.obj = new THREE.Vector3();
  33447. data.obj.fromArray( array );
  33448. data.angle = THREE.Math.degToRad( array[ 3 ] );
  33449. break;
  33450. }
  33451. return data;
  33452. }
  33453. function parseKinematicsScene( xml ) {
  33454. var data = {
  33455. bindJointAxis: []
  33456. };
  33457. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33458. var child = xml.childNodes[ i ];
  33459. if ( child.nodeType !== 1 ) continue;
  33460. switch ( child.nodeName ) {
  33461. case 'bind_joint_axis':
  33462. data.bindJointAxis.push( parseKinematicsBindJointAxis( child ) );
  33463. break;
  33464. }
  33465. }
  33466. library.kinematicsScenes[ parseId( xml.getAttribute( 'url' ) ) ] = data;
  33467. }
  33468. function parseKinematicsBindJointAxis( xml ) {
  33469. var data = {
  33470. target: xml.getAttribute( 'target' ).split( '/' ).pop()
  33471. };
  33472. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33473. var child = xml.childNodes[ i ];
  33474. if ( child.nodeType !== 1 ) continue;
  33475. switch ( child.nodeName ) {
  33476. case 'axis':
  33477. var param = child.getElementsByTagName( 'param' )[ 0 ];
  33478. data.axis = param.textContent;
  33479. var tmpJointIndex = data.axis.split( 'inst_' ).pop().split( 'axis' )[ 0 ];
  33480. data.jointIndex = tmpJointIndex.substr( 0, tmpJointIndex.length - 1 );
  33481. break;
  33482. }
  33483. }
  33484. return data;
  33485. }
  33486. function buildKinematicsScene( data ) {
  33487. if ( data.build !== undefined ) return data.build;
  33488. return data;
  33489. }
  33490. function getKinematicsScene( id ) {
  33491. return getBuild( library.kinematicsScenes[ id ], buildKinematicsScene );
  33492. }
  33493. function setupKinematics() {
  33494. var kinematicsModelId = Object.keys( library.kinematicsModels )[ 0 ];
  33495. var kinematicsSceneId = Object.keys( library.kinematicsScenes )[ 0 ];
  33496. var visualSceneId = Object.keys( library.visualScenes )[ 0 ];
  33497. if ( kinematicsModelId === undefined || kinematicsSceneId === undefined ) return;
  33498. var kinematicsModel = getKinematicsModel( kinematicsModelId );
  33499. var kinematicsScene = getKinematicsScene( kinematicsSceneId );
  33500. var visualScene = getVisualScene( visualSceneId );
  33501. var bindJointAxis = kinematicsScene.bindJointAxis;
  33502. var jointMap = {};
  33503. for ( var i = 0, l = bindJointAxis.length; i < l; i ++ ) {
  33504. var axis = bindJointAxis[ i ];
  33505. // the result of the following query is an element of type 'translate', 'rotate','scale' or 'matrix'
  33506. var targetElement = collada.querySelector( '[sid="' + axis.target + '"]' );
  33507. if ( targetElement ) {
  33508. // get the parent of the transfrom element
  33509. var parentVisualElement = targetElement.parentElement;
  33510. // connect the joint of the kinematics model with the element in the visual scene
  33511. connect( axis.jointIndex, parentVisualElement );
  33512. }
  33513. }
  33514. function connect( jointIndex, visualElement ) {
  33515. var visualElementName = visualElement.getAttribute( 'name' );
  33516. var joint = kinematicsModel.joints[ jointIndex ];
  33517. visualScene.traverse( function ( object ) {
  33518. if ( object.name === visualElementName ) {
  33519. jointMap[ jointIndex ] = {
  33520. object: object,
  33521. transforms: buildTransformList( visualElement ),
  33522. joint: joint,
  33523. position: joint.zeroPosition
  33524. };
  33525. }
  33526. } );
  33527. }
  33528. var m0 = new THREE.Matrix4();
  33529. kinematics = {
  33530. joints: kinematicsModel && kinematicsModel.joints,
  33531. getJointValue: function ( jointIndex ) {
  33532. var jointData = jointMap[ jointIndex ];
  33533. if ( jointData ) {
  33534. return jointData.position;
  33535. } else {
  33536. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' doesn\'t exist.' );
  33537. }
  33538. },
  33539. setJointValue: function ( jointIndex, value ) {
  33540. var jointData = jointMap[ jointIndex ];
  33541. if ( jointData ) {
  33542. var joint = jointData.joint;
  33543. if ( value > joint.limits.max || value < joint.limits.min ) {
  33544. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ').' );
  33545. } else if ( joint.static ) {
  33546. console.warn( 'THREE.ColladaLoader: Joint ' + jointIndex + ' is static.' );
  33547. } else {
  33548. var object = jointData.object;
  33549. var axis = joint.axis;
  33550. var transforms = jointData.transforms;
  33551. matrix.identity();
  33552. // each update, we have to apply all transforms in the correct order
  33553. for ( var i = 0; i < transforms.length; i ++ ) {
  33554. var transform = transforms[ i ];
  33555. // if there is a connection of the transform node with a joint, apply the joint value
  33556. if ( transform.sid && transform.sid.indexOf( jointIndex ) !== - 1 ) {
  33557. switch ( joint.type ) {
  33558. case 'revolute':
  33559. matrix.multiply( m0.makeRotationAxis( axis, THREE.Math.degToRad( value ) ) );
  33560. break;
  33561. case 'prismatic':
  33562. matrix.multiply( m0.makeTranslation( axis.x * value, axis.y * value, axis.z * value ) );
  33563. break;
  33564. default:
  33565. console.warn( 'THREE.ColladaLoader: Unknown joint type: ' + joint.type );
  33566. break;
  33567. }
  33568. } else {
  33569. switch ( transform.type ) {
  33570. case 'matrix':
  33571. matrix.multiply( transform.obj );
  33572. break;
  33573. case 'translate':
  33574. matrix.multiply( m0.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  33575. break;
  33576. case 'scale':
  33577. matrix.scale( transform.obj );
  33578. break;
  33579. case 'rotate':
  33580. matrix.multiply( m0.makeRotationAxis( transform.obj, transform.angle ) );
  33581. break;
  33582. }
  33583. }
  33584. }
  33585. object.matrix.copy( matrix );
  33586. object.matrix.decompose( object.position, object.quaternion, object.scale );
  33587. jointMap[ jointIndex ].position = value;
  33588. }
  33589. } else {
  33590. console.log( 'THREE.ColladaLoader: ' + jointIndex + ' does not exist.' );
  33591. }
  33592. }
  33593. };
  33594. }
  33595. function buildTransformList( node ) {
  33596. var transforms = [];
  33597. var xml = collada.querySelector( '[id="' + node.id + '"]' );
  33598. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33599. var child = xml.childNodes[ i ];
  33600. if ( child.nodeType !== 1 ) continue;
  33601. switch ( child.nodeName ) {
  33602. case 'matrix':
  33603. var array = parseFloats( child.textContent );
  33604. var matrix = new THREE.Matrix4().fromArray( array ).transpose();
  33605. transforms.push( {
  33606. sid: child.getAttribute( 'sid' ),
  33607. type: child.nodeName,
  33608. obj: matrix
  33609. } );
  33610. break;
  33611. case 'translate':
  33612. case 'scale':
  33613. var array = parseFloats( child.textContent );
  33614. var vector = new THREE.Vector3().fromArray( array );
  33615. transforms.push( {
  33616. sid: child.getAttribute( 'sid' ),
  33617. type: child.nodeName,
  33618. obj: vector
  33619. } );
  33620. break;
  33621. case 'rotate':
  33622. var array = parseFloats( child.textContent );
  33623. var vector = new THREE.Vector3().fromArray( array );
  33624. var angle = THREE.Math.degToRad( array[ 3 ] );
  33625. transforms.push( {
  33626. sid: child.getAttribute( 'sid' ),
  33627. type: child.nodeName,
  33628. obj: vector,
  33629. angle: angle
  33630. } );
  33631. break;
  33632. }
  33633. }
  33634. return transforms;
  33635. }
  33636. // nodes
  33637. function prepareNodes( xml ) {
  33638. var elements = xml.getElementsByTagName( 'node' );
  33639. // ensure all node elements have id attributes
  33640. for ( var i = 0; i < elements.length; i ++ ) {
  33641. var element = elements[ i ];
  33642. if ( element.hasAttribute( 'id' ) === false ) {
  33643. element.setAttribute( 'id', generateId() );
  33644. }
  33645. }
  33646. }
  33647. var matrix = new THREE.Matrix4();
  33648. var vector = new THREE.Vector3();
  33649. function parseNode( xml ) {
  33650. var data = {
  33651. name: xml.getAttribute( 'name' ) || '',
  33652. type: xml.getAttribute( 'type' ),
  33653. id: xml.getAttribute( 'id' ),
  33654. sid: xml.getAttribute( 'sid' ),
  33655. matrix: new THREE.Matrix4(),
  33656. nodes: [],
  33657. instanceCameras: [],
  33658. instanceControllers: [],
  33659. instanceLights: [],
  33660. instanceGeometries: [],
  33661. instanceNodes: [],
  33662. transforms: {}
  33663. };
  33664. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33665. var child = xml.childNodes[ i ];
  33666. if ( child.nodeType !== 1 ) continue;
  33667. switch ( child.nodeName ) {
  33668. case 'node':
  33669. data.nodes.push( child.getAttribute( 'id' ) );
  33670. parseNode( child );
  33671. break;
  33672. case 'instance_camera':
  33673. data.instanceCameras.push( parseId( child.getAttribute( 'url' ) ) );
  33674. break;
  33675. case 'instance_controller':
  33676. data.instanceControllers.push( parseNodeInstance( child ) );
  33677. break;
  33678. case 'instance_light':
  33679. data.instanceLights.push( parseId( child.getAttribute( 'url' ) ) );
  33680. break;
  33681. case 'instance_geometry':
  33682. data.instanceGeometries.push( parseNodeInstance( child ) );
  33683. break;
  33684. case 'instance_node':
  33685. data.instanceNodes.push( parseId( child.getAttribute( 'url' ) ) );
  33686. break;
  33687. case 'matrix':
  33688. var array = parseFloats( child.textContent );
  33689. data.matrix.multiply( matrix.fromArray( array ).transpose() );
  33690. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  33691. break;
  33692. case 'translate':
  33693. var array = parseFloats( child.textContent );
  33694. vector.fromArray( array );
  33695. data.matrix.multiply( matrix.makeTranslation( vector.x, vector.y, vector.z ) );
  33696. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  33697. break;
  33698. case 'rotate':
  33699. var array = parseFloats( child.textContent );
  33700. var angle = THREE.Math.degToRad( array[ 3 ] );
  33701. data.matrix.multiply( matrix.makeRotationAxis( vector.fromArray( array ), angle ) );
  33702. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  33703. break;
  33704. case 'scale':
  33705. var array = parseFloats( child.textContent );
  33706. data.matrix.scale( vector.fromArray( array ) );
  33707. data.transforms[ child.getAttribute( 'sid' ) ] = child.nodeName;
  33708. break;
  33709. case 'extra':
  33710. break;
  33711. default:
  33712. console.log( child );
  33713. }
  33714. }
  33715. library.nodes[ data.id ] = data;
  33716. return data;
  33717. }
  33718. function parseNodeInstance( xml ) {
  33719. var data = {
  33720. id: parseId( xml.getAttribute( 'url' ) ),
  33721. materials: {},
  33722. skeletons: []
  33723. };
  33724. for ( var i = 0; i < xml.childNodes.length; i ++ ) {
  33725. var child = xml.childNodes[ i ];
  33726. switch ( child.nodeName ) {
  33727. case 'bind_material':
  33728. var instances = child.getElementsByTagName( 'instance_material' );
  33729. for ( var j = 0; j < instances.length; j ++ ) {
  33730. var instance = instances[ j ];
  33731. var symbol = instance.getAttribute( 'symbol' );
  33732. var target = instance.getAttribute( 'target' );
  33733. data.materials[ symbol ] = parseId( target );
  33734. }
  33735. break;
  33736. case 'skeleton':
  33737. data.skeletons.push( parseId( child.textContent ) );
  33738. break;
  33739. default:
  33740. break;
  33741. }
  33742. }
  33743. return data;
  33744. }
  33745. function buildSkeleton( skeletons, joints ) {
  33746. var boneData = [];
  33747. var sortedBoneData = [];
  33748. var i, j, data;
  33749. // a skeleton can have multiple root bones. collada expresses this
  33750. // situtation with multiple "skeleton" tags per controller instance
  33751. for ( i = 0; i < skeletons.length; i ++ ) {
  33752. var skeleton = skeletons[ i ];
  33753. var root = getNode( skeleton );
  33754. // setup bone data for a single bone hierarchy
  33755. buildBoneHierarchy( root, joints, boneData );
  33756. }
  33757. // sort bone data (the order is defined in the corresponding controller)
  33758. for ( i = 0; i < joints.length; i ++ ) {
  33759. for ( j = 0; j < boneData.length; j ++ ) {
  33760. data = boneData[ j ];
  33761. if ( data.bone.name === joints[ i ].name ) {
  33762. sortedBoneData[ i ] = data;
  33763. data.processed = true;
  33764. break;
  33765. }
  33766. }
  33767. }
  33768. // add unprocessed bone data at the end of the list
  33769. for ( i = 0; i < boneData.length; i ++ ) {
  33770. data = boneData[ i ];
  33771. if ( data.processed === false ) {
  33772. sortedBoneData.push( data );
  33773. data.processed = true;
  33774. }
  33775. }
  33776. // setup arrays for skeleton creation
  33777. var bones = [];
  33778. var boneInverses = [];
  33779. for ( i = 0; i < sortedBoneData.length; i ++ ) {
  33780. data = sortedBoneData[ i ];
  33781. bones.push( data.bone );
  33782. boneInverses.push( data.boneInverse );
  33783. }
  33784. return new THREE.Skeleton( bones, boneInverses );
  33785. }
  33786. function buildBoneHierarchy( root, joints, boneData ) {
  33787. // setup bone data from visual scene
  33788. root.traverse( function ( object ) {
  33789. if ( object.isBone === true ) {
  33790. var boneInverse;
  33791. // retrieve the boneInverse from the controller data
  33792. for ( var i = 0; i < joints.length; i ++ ) {
  33793. var joint = joints[ i ];
  33794. if ( joint.name === object.name ) {
  33795. boneInverse = joint.boneInverse;
  33796. break;
  33797. }
  33798. }
  33799. if ( boneInverse === undefined ) {
  33800. // Unfortunately, there can be joints in the visual scene that are not part of the
  33801. // corresponding controller. In this case, we have to create a dummy boneInverse matrix
  33802. // for the respective bone. This bone won't affect any vertices, because there are no skin indices
  33803. // and weights defined for it. But we still have to add the bone to the sorted bone list in order to
  33804. // ensure a correct animation of the model.
  33805. boneInverse = new THREE.Matrix4();
  33806. }
  33807. boneData.push( { bone: object, boneInverse: boneInverse, processed: false } );
  33808. }
  33809. } );
  33810. }
  33811. function buildNode( data ) {
  33812. var objects = [];
  33813. var matrix = data.matrix;
  33814. var nodes = data.nodes;
  33815. var type = data.type;
  33816. var instanceCameras = data.instanceCameras;
  33817. var instanceControllers = data.instanceControllers;
  33818. var instanceLights = data.instanceLights;
  33819. var instanceGeometries = data.instanceGeometries;
  33820. var instanceNodes = data.instanceNodes;
  33821. // nodes
  33822. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  33823. objects.push( getNode( nodes[ i ] ) );
  33824. }
  33825. // instance cameras
  33826. for ( var i = 0, l = instanceCameras.length; i < l; i ++ ) {
  33827. var instanceCamera = getCamera( instanceCameras[ i ] );
  33828. if ( instanceCamera !== null ) {
  33829. objects.push( instanceCamera.clone() );
  33830. }
  33831. }
  33832. // instance controllers
  33833. for ( var i = 0, l = instanceControllers.length; i < l; i ++ ) {
  33834. var instance = instanceControllers[ i ];
  33835. var controller = getController( instance.id );
  33836. var geometries = getGeometry( controller.id );
  33837. var newObjects = buildObjects( geometries, instance.materials );
  33838. var skeletons = instance.skeletons;
  33839. var joints = controller.skin.joints;
  33840. var skeleton = buildSkeleton( skeletons, joints );
  33841. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  33842. var object = newObjects[ j ];
  33843. if ( object.isSkinnedMesh ) {
  33844. object.bind( skeleton, controller.skin.bindMatrix );
  33845. object.normalizeSkinWeights();
  33846. }
  33847. objects.push( object );
  33848. }
  33849. }
  33850. // instance lights
  33851. for ( var i = 0, l = instanceLights.length; i < l; i ++ ) {
  33852. var instanceLight = getLight( instanceLights[ i ] );
  33853. if ( instanceLight !== null ) {
  33854. objects.push( instanceLight.clone() );
  33855. }
  33856. }
  33857. // instance geometries
  33858. for ( var i = 0, l = instanceGeometries.length; i < l; i ++ ) {
  33859. var instance = instanceGeometries[ i ];
  33860. // a single geometry instance in collada can lead to multiple object3Ds.
  33861. // this is the case when primitives are combined like triangles and lines
  33862. var geometries = getGeometry( instance.id );
  33863. var newObjects = buildObjects( geometries, instance.materials );
  33864. for ( var j = 0, jl = newObjects.length; j < jl; j ++ ) {
  33865. objects.push( newObjects[ j ] );
  33866. }
  33867. }
  33868. // instance nodes
  33869. for ( var i = 0, l = instanceNodes.length; i < l; i ++ ) {
  33870. objects.push( getNode( instanceNodes[ i ] ).clone() );
  33871. }
  33872. var object;
  33873. if ( nodes.length === 0 && objects.length === 1 ) {
  33874. object = objects[ 0 ];
  33875. } else {
  33876. object = ( type === 'JOINT' ) ? new THREE.Bone() : new THREE.Group();
  33877. for ( var i = 0; i < objects.length; i ++ ) {
  33878. object.add( objects[ i ] );
  33879. }
  33880. }
  33881. object.name = ( type === 'JOINT' ) ? data.sid : data.name;
  33882. object.matrix.copy( matrix );
  33883. object.matrix.decompose( object.position, object.quaternion, object.scale );
  33884. return object;
  33885. }
  33886. function resolveMaterialBinding( keys, instanceMaterials ) {
  33887. var materials = [];
  33888. for ( var i = 0, l = keys.length; i < l; i ++ ) {
  33889. var id = instanceMaterials[ keys[ i ] ];
  33890. materials.push( getMaterial( id ) );
  33891. }
  33892. return materials;
  33893. }
  33894. function buildObjects( geometries, instanceMaterials ) {
  33895. var objects = [];
  33896. for ( var type in geometries ) {
  33897. var geometry = geometries[ type ];
  33898. var materials = resolveMaterialBinding( geometry.materialKeys, instanceMaterials );
  33899. // handle case if no materials are defined
  33900. if ( materials.length === 0 ) {
  33901. if ( type === 'lines' || type === 'linestrips' ) {
  33902. materials.push( new THREE.LineBasicMaterial() );
  33903. } else {
  33904. materials.push( new THREE.MeshPhongMaterial() );
  33905. }
  33906. }
  33907. // regard skinning
  33908. var skinning = ( geometry.data.attributes.skinIndex !== undefined );
  33909. if ( skinning ) {
  33910. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  33911. materials[ i ].skinning = true;
  33912. }
  33913. }
  33914. // choose between a single or multi materials (material array)
  33915. var material = ( materials.length === 1 ) ? materials[ 0 ] : materials;
  33916. // now create a specific 3D object
  33917. var object;
  33918. switch ( type ) {
  33919. case 'lines':
  33920. object = new THREE.LineSegments( geometry.data, material );
  33921. break;
  33922. case 'linestrips':
  33923. object = new THREE.Line( geometry.data, material );
  33924. break;
  33925. case 'triangles':
  33926. case 'polylist':
  33927. if ( skinning ) {
  33928. object = new THREE.SkinnedMesh( geometry.data, material );
  33929. } else {
  33930. object = new THREE.Mesh( geometry.data, material );
  33931. }
  33932. break;
  33933. }
  33934. objects.push( object );
  33935. }
  33936. return objects;
  33937. }
  33938. function getNode( id ) {
  33939. return getBuild( library.nodes[ id ], buildNode );
  33940. }
  33941. // visual scenes
  33942. function parseVisualScene( xml ) {
  33943. var data = {
  33944. name: xml.getAttribute( 'name' ),
  33945. children: []
  33946. };
  33947. prepareNodes( xml );
  33948. var elements = getElementsByTagName( xml, 'node' );
  33949. for ( var i = 0; i < elements.length; i ++ ) {
  33950. data.children.push( parseNode( elements[ i ] ) );
  33951. }
  33952. library.visualScenes[ xml.getAttribute( 'id' ) ] = data;
  33953. }
  33954. function buildVisualScene( data ) {
  33955. var group = new THREE.Group();
  33956. group.name = data.name;
  33957. var children = data.children;
  33958. for ( var i = 0; i < children.length; i ++ ) {
  33959. var child = children[ i ];
  33960. if ( child.id === null ) {
  33961. group.add( buildNode( child ) );
  33962. } else {
  33963. // if there is an ID, let's try to get the finished build (e.g. joints are already build)
  33964. group.add( getNode( child.id ) );
  33965. }
  33966. }
  33967. return group;
  33968. }
  33969. function getVisualScene( id ) {
  33970. return getBuild( library.visualScenes[ id ], buildVisualScene );
  33971. }
  33972. // scenes
  33973. function parseScene( xml ) {
  33974. var instance = getElementsByTagName( xml, 'instance_visual_scene' )[ 0 ];
  33975. return getVisualScene( parseId( instance.getAttribute( 'url' ) ) );
  33976. }
  33977. function setupAnimations() {
  33978. var clips = library.clips;
  33979. if ( isEmpty( clips ) === true ) {
  33980. if ( isEmpty( library.animations ) === false ) {
  33981. // if there are animations but no clips, we create a default clip for playback
  33982. var tracks = [];
  33983. for ( var id in library.animations ) {
  33984. var animationTracks = getAnimation( id );
  33985. for ( var i = 0, l = animationTracks.length; i < l; i ++ ) {
  33986. tracks.push( animationTracks[ i ] );
  33987. }
  33988. }
  33989. animations.push( new THREE.AnimationClip( 'default', - 1, tracks ) );
  33990. }
  33991. } else {
  33992. for ( var id in clips ) {
  33993. animations.push( getAnimationClip( id ) );
  33994. }
  33995. }
  33996. }
  33997. console.time( 'THREE.ColladaLoader' );
  33998. if ( text.length === 0 ) {
  33999. return { scene: new THREE.Scene() };
  34000. }
  34001. console.time( 'THREE.ColladaLoader: DOMParser' );
  34002. var xml = new DOMParser().parseFromString( text, 'application/xml' );
  34003. console.timeEnd( 'THREE.ColladaLoader: DOMParser' );
  34004. var collada = getElementsByTagName( xml, 'COLLADA' )[ 0 ];
  34005. // metadata
  34006. var version = collada.getAttribute( 'version' );
  34007. console.log( 'THREE.ColladaLoader: File version', version );
  34008. var asset = parseAsset( getElementsByTagName( collada, 'asset' )[ 0 ] );
  34009. var textureLoader = new THREE.TextureLoader( this.manager );
  34010. textureLoader.setPath( path ).setCrossOrigin( this.crossOrigin );
  34011. //
  34012. var animations = [];
  34013. var kinematics = {};
  34014. var count = 0;
  34015. //
  34016. var library = {
  34017. animations: {},
  34018. clips: {},
  34019. controllers: {},
  34020. images: {},
  34021. effects: {},
  34022. materials: {},
  34023. cameras: {},
  34024. lights: {},
  34025. geometries: {},
  34026. nodes: {},
  34027. visualScenes: {},
  34028. kinematicsModels: {},
  34029. kinematicsScenes: {}
  34030. };
  34031. console.time( 'THREE.ColladaLoader: Parse' );
  34032. parseLibrary( collada, 'library_animations', 'animation', parseAnimation );
  34033. parseLibrary( collada, 'library_animation_clips', 'animation_clip', parseAnimationClip );
  34034. parseLibrary( collada, 'library_controllers', 'controller', parseController );
  34035. parseLibrary( collada, 'library_images', 'image', parseImage );
  34036. parseLibrary( collada, 'library_effects', 'effect', parseEffect );
  34037. parseLibrary( collada, 'library_materials', 'material', parseMaterial );
  34038. parseLibrary( collada, 'library_cameras', 'camera', parseCamera );
  34039. parseLibrary( collada, 'library_lights', 'light', parseLight );
  34040. parseLibrary( collada, 'library_geometries', 'geometry', parseGeometry );
  34041. parseLibrary( collada, 'library_nodes', 'node', parseNode );
  34042. parseLibrary( collada, 'library_visual_scenes', 'visual_scene', parseVisualScene );
  34043. parseLibrary( collada, 'library_kinematics_models', 'kinematics_model', parseKinematicsModel );
  34044. parseLibrary( collada, 'scene', 'instance_kinematics_scene', parseKinematicsScene );
  34045. console.timeEnd( 'THREE.ColladaLoader: Parse' );
  34046. console.time( 'THREE.ColladaLoader: Build' );
  34047. buildLibrary( library.animations, buildAnimation );
  34048. buildLibrary( library.clips, buildAnimationClip );
  34049. buildLibrary( library.controllers, buildController );
  34050. buildLibrary( library.images, buildImage );
  34051. buildLibrary( library.effects, buildEffect );
  34052. buildLibrary( library.materials, buildMaterial );
  34053. buildLibrary( library.cameras, buildCamera );
  34054. buildLibrary( library.lights, buildLight );
  34055. buildLibrary( library.geometries, buildGeometry );
  34056. buildLibrary( library.visualScenes, buildVisualScene );
  34057. console.timeEnd( 'THREE.ColladaLoader: Build' );
  34058. setupAnimations();
  34059. setupKinematics();
  34060. var scene = parseScene( getElementsByTagName( collada, 'scene' )[ 0 ] );
  34061. if ( asset.upAxis === 'Z_UP' ) {
  34062. scene.rotation.x = - Math.PI / 2;
  34063. }
  34064. scene.scale.multiplyScalar( asset.unit );
  34065. console.timeEnd( 'THREE.ColladaLoader' );
  34066. return {
  34067. animations: animations,
  34068. kinematics: kinematics,
  34069. library: library,
  34070. scene: scene
  34071. };
  34072. }
  34073. };
  34074. },{}],43:[function(_dereq_,module,exports){
  34075. /**
  34076. * @author Rich Tibbett / https://github.com/richtr
  34077. * @author mrdoob / http://mrdoob.com/
  34078. * @author Tony Parisi / http://www.tonyparisi.com/
  34079. * @author Takahiro / https://github.com/takahirox
  34080. * @author Don McCurdy / https://www.donmccurdy.com
  34081. */
  34082. THREE.GLTFLoader = ( function () {
  34083. function GLTFLoader( manager ) {
  34084. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34085. }
  34086. GLTFLoader.prototype = {
  34087. constructor: GLTFLoader,
  34088. crossOrigin: 'Anonymous',
  34089. load: function ( url, onLoad, onProgress, onError ) {
  34090. var scope = this;
  34091. var path = this.path !== undefined ? this.path : THREE.LoaderUtils.extractUrlBase( url );
  34092. var loader = new THREE.FileLoader( scope.manager );
  34093. loader.setResponseType( 'arraybuffer' );
  34094. loader.load( url, function ( data ) {
  34095. try {
  34096. scope.parse( data, path, onLoad, onError );
  34097. } catch ( e ) {
  34098. if ( onError !== undefined ) {
  34099. onError( e );
  34100. } else {
  34101. throw e;
  34102. }
  34103. }
  34104. }, onProgress, onError );
  34105. },
  34106. setCrossOrigin: function ( value ) {
  34107. this.crossOrigin = value;
  34108. return this;
  34109. },
  34110. setPath: function ( value ) {
  34111. this.path = value;
  34112. return this;
  34113. },
  34114. parse: function ( data, path, onLoad, onError ) {
  34115. var content;
  34116. var extensions = {};
  34117. if ( typeof data === 'string' ) {
  34118. content = data;
  34119. } else {
  34120. var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) );
  34121. if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) {
  34122. try {
  34123. extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data );
  34124. } catch ( error ) {
  34125. if ( onError ) onError( error );
  34126. return;
  34127. }
  34128. content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content;
  34129. } else {
  34130. content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) );
  34131. }
  34132. }
  34133. var json = JSON.parse( content );
  34134. if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) {
  34135. if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) );
  34136. return;
  34137. }
  34138. if ( json.extensionsUsed ) {
  34139. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_LIGHTS ) >= 0 ) {
  34140. extensions[ EXTENSIONS.KHR_LIGHTS ] = new GLTFLightsExtension( json );
  34141. }
  34142. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_COMMON ) >= 0 ) {
  34143. extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] = new GLTFMaterialsCommonExtension( json );
  34144. }
  34145. if ( json.extensionsUsed.indexOf( EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ) >= 0 ) {
  34146. extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] = new GLTFMaterialsPbrSpecularGlossinessExtension();
  34147. }
  34148. }
  34149. console.time( 'GLTFLoader' );
  34150. var parser = new GLTFParser( json, extensions, {
  34151. path: path || this.path || '',
  34152. crossOrigin: this.crossOrigin,
  34153. manager: this.manager
  34154. } );
  34155. parser.parse( function ( scene, scenes, cameras, animations, asset ) {
  34156. console.timeEnd( 'GLTFLoader' );
  34157. var glTF = {
  34158. scene: scene,
  34159. scenes: scenes,
  34160. cameras: cameras,
  34161. animations: animations,
  34162. asset: asset
  34163. };
  34164. onLoad( glTF );
  34165. }, onError );
  34166. }
  34167. };
  34168. /* GLTFREGISTRY */
  34169. function GLTFRegistry() {
  34170. var objects = {};
  34171. return {
  34172. get: function ( key ) {
  34173. return objects[ key ];
  34174. },
  34175. add: function ( key, object ) {
  34176. objects[ key ] = object;
  34177. },
  34178. remove: function ( key ) {
  34179. delete objects[ key ];
  34180. },
  34181. removeAll: function () {
  34182. objects = {};
  34183. }
  34184. };
  34185. }
  34186. /*********************************/
  34187. /********** EXTENSIONS ***********/
  34188. /*********************************/
  34189. var EXTENSIONS = {
  34190. KHR_BINARY_GLTF: 'KHR_binary_glTF',
  34191. KHR_LIGHTS: 'KHR_lights',
  34192. KHR_MATERIALS_COMMON: 'KHR_materials_common',
  34193. KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness'
  34194. };
  34195. /**
  34196. * Lights Extension
  34197. *
  34198. * Specification: PENDING
  34199. */
  34200. function GLTFLightsExtension( json ) {
  34201. this.name = EXTENSIONS.KHR_LIGHTS;
  34202. this.lights = {};
  34203. var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS ] ) || {};
  34204. var lights = extension.lights || {};
  34205. for ( var lightId in lights ) {
  34206. var light = lights[ lightId ];
  34207. var lightNode;
  34208. var color = new THREE.Color().fromArray( light.color );
  34209. switch ( light.type ) {
  34210. case 'directional':
  34211. lightNode = new THREE.DirectionalLight( color );
  34212. lightNode.position.set( 0, 0, 1 );
  34213. break;
  34214. case 'point':
  34215. lightNode = new THREE.PointLight( color );
  34216. break;
  34217. case 'spot':
  34218. lightNode = new THREE.SpotLight( color );
  34219. lightNode.position.set( 0, 0, 1 );
  34220. break;
  34221. case 'ambient':
  34222. lightNode = new THREE.AmbientLight( color );
  34223. break;
  34224. }
  34225. if ( lightNode ) {
  34226. if ( light.constantAttenuation !== undefined ) {
  34227. lightNode.intensity = light.constantAttenuation;
  34228. }
  34229. if ( light.linearAttenuation !== undefined ) {
  34230. lightNode.distance = 1 / light.linearAttenuation;
  34231. }
  34232. if ( light.quadraticAttenuation !== undefined ) {
  34233. lightNode.decay = light.quadraticAttenuation;
  34234. }
  34235. if ( light.fallOffAngle !== undefined ) {
  34236. lightNode.angle = light.fallOffAngle;
  34237. }
  34238. if ( light.fallOffExponent !== undefined ) {
  34239. console.warn( 'THREE.GLTFLoader:: light.fallOffExponent not currently supported.' );
  34240. }
  34241. lightNode.name = light.name || ( 'light_' + lightId );
  34242. this.lights[ lightId ] = lightNode;
  34243. }
  34244. }
  34245. }
  34246. /**
  34247. * Common Materials Extension
  34248. *
  34249. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_common
  34250. */
  34251. function GLTFMaterialsCommonExtension( json ) {
  34252. this.name = EXTENSIONS.KHR_MATERIALS_COMMON;
  34253. }
  34254. GLTFMaterialsCommonExtension.prototype.getMaterialType = function ( material ) {
  34255. var khrMaterial = material.extensions[ this.name ];
  34256. switch ( khrMaterial.type ) {
  34257. case 'commonBlinn' :
  34258. case 'commonPhong' :
  34259. return THREE.MeshPhongMaterial;
  34260. case 'commonLambert' :
  34261. return THREE.MeshLambertMaterial;
  34262. case 'commonConstant' :
  34263. default :
  34264. return THREE.MeshBasicMaterial;
  34265. }
  34266. };
  34267. GLTFMaterialsCommonExtension.prototype.extendParams = function ( materialParams, material, parser ) {
  34268. var khrMaterial = material.extensions[ this.name ];
  34269. var pending = [];
  34270. var keys = [];
  34271. // TODO: Currently ignored: 'ambientFactor', 'ambientTexture'
  34272. switch ( khrMaterial.type ) {
  34273. case 'commonBlinn' :
  34274. case 'commonPhong' :
  34275. keys.push( 'diffuseFactor', 'diffuseTexture', 'specularFactor', 'specularTexture', 'shininessFactor' );
  34276. break;
  34277. case 'commonLambert' :
  34278. keys.push( 'diffuseFactor', 'diffuseTexture' );
  34279. break;
  34280. case 'commonConstant' :
  34281. default :
  34282. break;
  34283. }
  34284. var materialValues = {};
  34285. keys.forEach( function ( v ) {
  34286. if ( khrMaterial[ v ] !== undefined ) materialValues[ v ] = khrMaterial[ v ];
  34287. } );
  34288. if ( materialValues.diffuseFactor !== undefined ) {
  34289. materialParams.color = new THREE.Color().fromArray( materialValues.diffuseFactor );
  34290. materialParams.opacity = materialValues.diffuseFactor[ 3 ];
  34291. }
  34292. if ( materialValues.diffuseTexture !== undefined ) {
  34293. pending.push( parser.assignTexture( materialParams, 'map', materialValues.diffuseTexture.index ) );
  34294. }
  34295. if ( materialValues.specularFactor !== undefined ) {
  34296. materialParams.specular = new THREE.Color().fromArray( materialValues.specularFactor );
  34297. }
  34298. if ( materialValues.specularTexture !== undefined ) {
  34299. pending.push( parser.assignTexture( materialParams, 'specularMap', materialValues.specularTexture.index ) );
  34300. }
  34301. if ( materialValues.shininessFactor !== undefined ) {
  34302. materialParams.shininess = materialValues.shininessFactor;
  34303. }
  34304. return Promise.all( pending );
  34305. };
  34306. /* BINARY EXTENSION */
  34307. var BINARY_EXTENSION_BUFFER_NAME = 'binary_glTF';
  34308. var BINARY_EXTENSION_HEADER_MAGIC = 'glTF';
  34309. var BINARY_EXTENSION_HEADER_LENGTH = 12;
  34310. var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 };
  34311. function GLTFBinaryExtension( data ) {
  34312. this.name = EXTENSIONS.KHR_BINARY_GLTF;
  34313. this.content = null;
  34314. this.body = null;
  34315. var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH );
  34316. this.header = {
  34317. magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ),
  34318. version: headerView.getUint32( 4, true ),
  34319. length: headerView.getUint32( 8, true )
  34320. };
  34321. if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) {
  34322. throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' );
  34323. } else if ( this.header.version < 2.0 ) {
  34324. throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' );
  34325. }
  34326. var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH );
  34327. var chunkIndex = 0;
  34328. while ( chunkIndex < chunkView.byteLength ) {
  34329. var chunkLength = chunkView.getUint32( chunkIndex, true );
  34330. chunkIndex += 4;
  34331. var chunkType = chunkView.getUint32( chunkIndex, true );
  34332. chunkIndex += 4;
  34333. if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) {
  34334. var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength );
  34335. this.content = THREE.LoaderUtils.decodeText( contentArray );
  34336. } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) {
  34337. var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex;
  34338. this.body = data.slice( byteOffset, byteOffset + chunkLength );
  34339. }
  34340. // Clients must ignore chunks with unknown types.
  34341. chunkIndex += chunkLength;
  34342. }
  34343. if ( this.content === null ) {
  34344. throw new Error( 'THREE.GLTFLoader: JSON content not found.' );
  34345. }
  34346. }
  34347. /**
  34348. * Specular-Glossiness Extension
  34349. *
  34350. * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  34351. */
  34352. function GLTFMaterialsPbrSpecularGlossinessExtension() {
  34353. return {
  34354. name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS,
  34355. specularGlossinessParams: [
  34356. 'color',
  34357. 'map',
  34358. 'lightMap',
  34359. 'lightMapIntensity',
  34360. 'aoMap',
  34361. 'aoMapIntensity',
  34362. 'emissive',
  34363. 'emissiveIntensity',
  34364. 'emissiveMap',
  34365. 'bumpMap',
  34366. 'bumpScale',
  34367. 'normalMap',
  34368. 'displacementMap',
  34369. 'displacementScale',
  34370. 'displacementBias',
  34371. 'specularMap',
  34372. 'specular',
  34373. 'glossinessMap',
  34374. 'glossiness',
  34375. 'alphaMap',
  34376. 'envMap',
  34377. 'envMapIntensity',
  34378. 'refractionRatio',
  34379. ],
  34380. getMaterialType: function () {
  34381. return THREE.ShaderMaterial;
  34382. },
  34383. extendParams: function ( params, material, parser ) {
  34384. var pbrSpecularGlossiness = material.extensions[ this.name ];
  34385. var shader = THREE.ShaderLib[ 'standard' ];
  34386. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  34387. var specularMapParsFragmentChunk = [
  34388. '#ifdef USE_SPECULARMAP',
  34389. ' uniform sampler2D specularMap;',
  34390. '#endif'
  34391. ].join( '\n' );
  34392. var glossinessMapParsFragmentChunk = [
  34393. '#ifdef USE_GLOSSINESSMAP',
  34394. ' uniform sampler2D glossinessMap;',
  34395. '#endif'
  34396. ].join( '\n' );
  34397. var specularMapFragmentChunk = [
  34398. 'vec3 specularFactor = specular;',
  34399. '#ifdef USE_SPECULARMAP',
  34400. ' vec4 texelSpecular = texture2D( specularMap, vUv );',
  34401. ' texelSpecular = sRGBToLinear( texelSpecular );',
  34402. ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34403. ' specularFactor *= texelSpecular.rgb;',
  34404. '#endif'
  34405. ].join( '\n' );
  34406. var glossinessMapFragmentChunk = [
  34407. 'float glossinessFactor = glossiness;',
  34408. '#ifdef USE_GLOSSINESSMAP',
  34409. ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );',
  34410. ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture',
  34411. ' glossinessFactor *= texelGlossiness.a;',
  34412. '#endif'
  34413. ].join( '\n' );
  34414. var lightPhysicalFragmentChunk = [
  34415. 'PhysicalMaterial material;',
  34416. 'material.diffuseColor = diffuseColor.rgb;',
  34417. 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );',
  34418. 'material.specularColor = specularFactor.rgb;',
  34419. ].join( '\n' );
  34420. var fragmentShader = shader.fragmentShader
  34421. .replace( '#include <specularmap_fragment>', '' )
  34422. .replace( 'uniform float roughness;', 'uniform vec3 specular;' )
  34423. .replace( 'uniform float metalness;', 'uniform float glossiness;' )
  34424. .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk )
  34425. .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk )
  34426. .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk )
  34427. .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk )
  34428. .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk );
  34429. delete uniforms.roughness;
  34430. delete uniforms.metalness;
  34431. delete uniforms.roughnessMap;
  34432. delete uniforms.metalnessMap;
  34433. uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) };
  34434. uniforms.glossiness = { value: 0.5 };
  34435. uniforms.specularMap = { value: null };
  34436. uniforms.glossinessMap = { value: null };
  34437. params.vertexShader = shader.vertexShader;
  34438. params.fragmentShader = fragmentShader;
  34439. params.uniforms = uniforms;
  34440. params.defines = { 'STANDARD': '' };
  34441. params.color = new THREE.Color( 1.0, 1.0, 1.0 );
  34442. params.opacity = 1.0;
  34443. var pending = [];
  34444. if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) {
  34445. var array = pbrSpecularGlossiness.diffuseFactor;
  34446. params.color.fromArray( array );
  34447. params.opacity = array[ 3 ];
  34448. }
  34449. if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) {
  34450. pending.push( parser.assignTexture( params, 'map', pbrSpecularGlossiness.diffuseTexture.index ) );
  34451. }
  34452. params.emissive = new THREE.Color( 0.0, 0.0, 0.0 );
  34453. params.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0;
  34454. params.specular = new THREE.Color( 1.0, 1.0, 1.0 );
  34455. if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) {
  34456. params.specular.fromArray( pbrSpecularGlossiness.specularFactor );
  34457. }
  34458. if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) {
  34459. var specGlossIndex = pbrSpecularGlossiness.specularGlossinessTexture.index;
  34460. pending.push( parser.assignTexture( params, 'glossinessMap', specGlossIndex ) );
  34461. pending.push( parser.assignTexture( params, 'specularMap', specGlossIndex ) );
  34462. }
  34463. return Promise.all( pending );
  34464. },
  34465. createMaterial: function ( params ) {
  34466. // setup material properties based on MeshStandardMaterial for Specular-Glossiness
  34467. var material = new THREE.ShaderMaterial( {
  34468. defines: params.defines,
  34469. vertexShader: params.vertexShader,
  34470. fragmentShader: params.fragmentShader,
  34471. uniforms: params.uniforms,
  34472. fog: true,
  34473. lights: true,
  34474. opacity: params.opacity,
  34475. transparent: params.transparent
  34476. } );
  34477. material.isGLTFSpecularGlossinessMaterial = true;
  34478. material.color = params.color;
  34479. material.map = params.map === undefined ? null : params.map;
  34480. material.lightMap = null;
  34481. material.lightMapIntensity = 1.0;
  34482. material.aoMap = params.aoMap === undefined ? null : params.aoMap;
  34483. material.aoMapIntensity = 1.0;
  34484. material.emissive = params.emissive;
  34485. material.emissiveIntensity = 1.0;
  34486. material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap;
  34487. material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap;
  34488. material.bumpScale = 1;
  34489. material.normalMap = params.normalMap === undefined ? null : params.normalMap;
  34490. if ( params.normalScale ) material.normalScale = params.normalScale;
  34491. material.displacementMap = null;
  34492. material.displacementScale = 1;
  34493. material.displacementBias = 0;
  34494. material.specularMap = params.specularMap === undefined ? null : params.specularMap;
  34495. material.specular = params.specular;
  34496. material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap;
  34497. material.glossiness = params.glossiness;
  34498. material.alphaMap = null;
  34499. material.envMap = params.envMap === undefined ? null : params.envMap;
  34500. material.envMapIntensity = 1.0;
  34501. material.refractionRatio = 0.98;
  34502. material.extensions.derivatives = true;
  34503. return material;
  34504. },
  34505. /**
  34506. * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can
  34507. * copy only properties it knows about or inherits, and misses many properties that would
  34508. * normally be defined by MeshStandardMaterial.
  34509. *
  34510. * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of
  34511. * loading a glTF model, but cloning later (e.g. by the user) would require these changes
  34512. * AND also updating `.onBeforeRender` on the parent mesh.
  34513. *
  34514. * @param {THREE.ShaderMaterial} source
  34515. * @return {THREE.ShaderMaterial}
  34516. */
  34517. cloneMaterial: function ( source ) {
  34518. var target = source.clone();
  34519. target.isGLTFSpecularGlossinessMaterial = true;
  34520. var params = this.specularGlossinessParams;
  34521. for ( var i = 0, il = params.length; i < il; i ++ ) {
  34522. target[ params[ i ] ] = source[ params[ i ] ];
  34523. }
  34524. return target;
  34525. },
  34526. // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer.
  34527. refreshUniforms: function ( renderer, scene, camera, geometry, material, group ) {
  34528. var uniforms = material.uniforms;
  34529. var defines = material.defines;
  34530. uniforms.opacity.value = material.opacity;
  34531. uniforms.diffuse.value.copy( material.color );
  34532. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  34533. uniforms.map.value = material.map;
  34534. uniforms.specularMap.value = material.specularMap;
  34535. uniforms.alphaMap.value = material.alphaMap;
  34536. uniforms.lightMap.value = material.lightMap;
  34537. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  34538. uniforms.aoMap.value = material.aoMap;
  34539. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  34540. // uv repeat and offset setting priorities
  34541. // 1. color map
  34542. // 2. specular map
  34543. // 3. normal map
  34544. // 4. bump map
  34545. // 5. alpha map
  34546. // 6. emissive map
  34547. var uvScaleMap;
  34548. if ( material.map ) {
  34549. uvScaleMap = material.map;
  34550. } else if ( material.specularMap ) {
  34551. uvScaleMap = material.specularMap;
  34552. } else if ( material.displacementMap ) {
  34553. uvScaleMap = material.displacementMap;
  34554. } else if ( material.normalMap ) {
  34555. uvScaleMap = material.normalMap;
  34556. } else if ( material.bumpMap ) {
  34557. uvScaleMap = material.bumpMap;
  34558. } else if ( material.glossinessMap ) {
  34559. uvScaleMap = material.glossinessMap;
  34560. } else if ( material.alphaMap ) {
  34561. uvScaleMap = material.alphaMap;
  34562. } else if ( material.emissiveMap ) {
  34563. uvScaleMap = material.emissiveMap;
  34564. }
  34565. if ( uvScaleMap !== undefined ) {
  34566. // backwards compatibility
  34567. if ( uvScaleMap.isWebGLRenderTarget ) {
  34568. uvScaleMap = uvScaleMap.texture;
  34569. }
  34570. var offset;
  34571. var repeat;
  34572. if ( uvScaleMap.matrix !== undefined ) {
  34573. // > r88.
  34574. if ( uvScaleMap.matrixAutoUpdate === true ) {
  34575. offset = uvScaleMap.offset;
  34576. repeat = uvScaleMap.repeat;
  34577. var rotation = uvScaleMap.rotation;
  34578. var center = uvScaleMap.center;
  34579. uvScaleMap.matrix.setUvTransform( offset.x, offset.y, repeat.x, repeat.y, rotation, center.x, center.y );
  34580. }
  34581. uniforms.uvTransform.value.copy( uvScaleMap.matrix );
  34582. } else {
  34583. // <= r87. Remove when reasonable.
  34584. offset = uvScaleMap.offset;
  34585. repeat = uvScaleMap.repeat;
  34586. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  34587. }
  34588. }
  34589. uniforms.envMap.value = material.envMap;
  34590. uniforms.envMapIntensity.value = material.envMapIntensity;
  34591. uniforms.flipEnvMap.value = ( material.envMap && material.envMap.isCubeTexture ) ? - 1 : 1;
  34592. uniforms.refractionRatio.value = material.refractionRatio;
  34593. uniforms.specular.value.copy( material.specular );
  34594. uniforms.glossiness.value = material.glossiness;
  34595. uniforms.glossinessMap.value = material.glossinessMap;
  34596. uniforms.emissiveMap.value = material.emissiveMap;
  34597. uniforms.bumpMap.value = material.bumpMap;
  34598. uniforms.normalMap.value = material.normalMap;
  34599. uniforms.displacementMap.value = material.displacementMap;
  34600. uniforms.displacementScale.value = material.displacementScale;
  34601. uniforms.displacementBias.value = material.displacementBias;
  34602. if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) {
  34603. defines.USE_GLOSSINESSMAP = '';
  34604. // set USE_ROUGHNESSMAP to enable vUv
  34605. defines.USE_ROUGHNESSMAP = '';
  34606. }
  34607. if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) {
  34608. delete defines.USE_GLOSSINESSMAP;
  34609. delete defines.USE_ROUGHNESSMAP;
  34610. }
  34611. }
  34612. };
  34613. }
  34614. /*********************************/
  34615. /********** INTERNALS ************/
  34616. /*********************************/
  34617. /* CONSTANTS */
  34618. var WEBGL_CONSTANTS = {
  34619. FLOAT: 5126,
  34620. //FLOAT_MAT2: 35674,
  34621. FLOAT_MAT3: 35675,
  34622. FLOAT_MAT4: 35676,
  34623. FLOAT_VEC2: 35664,
  34624. FLOAT_VEC3: 35665,
  34625. FLOAT_VEC4: 35666,
  34626. LINEAR: 9729,
  34627. REPEAT: 10497,
  34628. SAMPLER_2D: 35678,
  34629. POINTS: 0,
  34630. LINES: 1,
  34631. LINE_LOOP: 2,
  34632. LINE_STRIP: 3,
  34633. TRIANGLES: 4,
  34634. TRIANGLE_STRIP: 5,
  34635. TRIANGLE_FAN: 6,
  34636. UNSIGNED_BYTE: 5121,
  34637. UNSIGNED_SHORT: 5123
  34638. };
  34639. var WEBGL_TYPE = {
  34640. 5126: Number,
  34641. //35674: THREE.Matrix2,
  34642. 35675: THREE.Matrix3,
  34643. 35676: THREE.Matrix4,
  34644. 35664: THREE.Vector2,
  34645. 35665: THREE.Vector3,
  34646. 35666: THREE.Vector4,
  34647. 35678: THREE.Texture
  34648. };
  34649. var WEBGL_COMPONENT_TYPES = {
  34650. 5120: Int8Array,
  34651. 5121: Uint8Array,
  34652. 5122: Int16Array,
  34653. 5123: Uint16Array,
  34654. 5125: Uint32Array,
  34655. 5126: Float32Array
  34656. };
  34657. var WEBGL_FILTERS = {
  34658. 9728: THREE.NearestFilter,
  34659. 9729: THREE.LinearFilter,
  34660. 9984: THREE.NearestMipMapNearestFilter,
  34661. 9985: THREE.LinearMipMapNearestFilter,
  34662. 9986: THREE.NearestMipMapLinearFilter,
  34663. 9987: THREE.LinearMipMapLinearFilter
  34664. };
  34665. var WEBGL_WRAPPINGS = {
  34666. 33071: THREE.ClampToEdgeWrapping,
  34667. 33648: THREE.MirroredRepeatWrapping,
  34668. 10497: THREE.RepeatWrapping
  34669. };
  34670. var WEBGL_TEXTURE_FORMATS = {
  34671. 6406: THREE.AlphaFormat,
  34672. 6407: THREE.RGBFormat,
  34673. 6408: THREE.RGBAFormat,
  34674. 6409: THREE.LuminanceFormat,
  34675. 6410: THREE.LuminanceAlphaFormat
  34676. };
  34677. var WEBGL_TEXTURE_DATATYPES = {
  34678. 5121: THREE.UnsignedByteType,
  34679. 32819: THREE.UnsignedShort4444Type,
  34680. 32820: THREE.UnsignedShort5551Type,
  34681. 33635: THREE.UnsignedShort565Type
  34682. };
  34683. var WEBGL_SIDES = {
  34684. 1028: THREE.BackSide, // Culling front
  34685. 1029: THREE.FrontSide // Culling back
  34686. //1032: THREE.NoSide // Culling front and back, what to do?
  34687. };
  34688. var WEBGL_DEPTH_FUNCS = {
  34689. 512: THREE.NeverDepth,
  34690. 513: THREE.LessDepth,
  34691. 514: THREE.EqualDepth,
  34692. 515: THREE.LessEqualDepth,
  34693. 516: THREE.GreaterEqualDepth,
  34694. 517: THREE.NotEqualDepth,
  34695. 518: THREE.GreaterEqualDepth,
  34696. 519: THREE.AlwaysDepth
  34697. };
  34698. var WEBGL_BLEND_EQUATIONS = {
  34699. 32774: THREE.AddEquation,
  34700. 32778: THREE.SubtractEquation,
  34701. 32779: THREE.ReverseSubtractEquation
  34702. };
  34703. var WEBGL_BLEND_FUNCS = {
  34704. 0: THREE.ZeroFactor,
  34705. 1: THREE.OneFactor,
  34706. 768: THREE.SrcColorFactor,
  34707. 769: THREE.OneMinusSrcColorFactor,
  34708. 770: THREE.SrcAlphaFactor,
  34709. 771: THREE.OneMinusSrcAlphaFactor,
  34710. 772: THREE.DstAlphaFactor,
  34711. 773: THREE.OneMinusDstAlphaFactor,
  34712. 774: THREE.DstColorFactor,
  34713. 775: THREE.OneMinusDstColorFactor,
  34714. 776: THREE.SrcAlphaSaturateFactor
  34715. // The followings are not supported by Three.js yet
  34716. //32769: CONSTANT_COLOR,
  34717. //32770: ONE_MINUS_CONSTANT_COLOR,
  34718. //32771: CONSTANT_ALPHA,
  34719. //32772: ONE_MINUS_CONSTANT_COLOR
  34720. };
  34721. var WEBGL_TYPE_SIZES = {
  34722. 'SCALAR': 1,
  34723. 'VEC2': 2,
  34724. 'VEC3': 3,
  34725. 'VEC4': 4,
  34726. 'MAT2': 4,
  34727. 'MAT3': 9,
  34728. 'MAT4': 16
  34729. };
  34730. var PATH_PROPERTIES = {
  34731. scale: 'scale',
  34732. translation: 'position',
  34733. rotation: 'quaternion',
  34734. weights: 'morphTargetInfluences'
  34735. };
  34736. var INTERPOLATION = {
  34737. CUBICSPLINE: THREE.InterpolateSmooth,
  34738. LINEAR: THREE.InterpolateLinear,
  34739. STEP: THREE.InterpolateDiscrete
  34740. };
  34741. var STATES_ENABLES = {
  34742. 2884: 'CULL_FACE',
  34743. 2929: 'DEPTH_TEST',
  34744. 3042: 'BLEND',
  34745. 3089: 'SCISSOR_TEST',
  34746. 32823: 'POLYGON_OFFSET_FILL',
  34747. 32926: 'SAMPLE_ALPHA_TO_COVERAGE'
  34748. };
  34749. var ALPHA_MODES = {
  34750. OPAQUE: 'OPAQUE',
  34751. MASK: 'MASK',
  34752. BLEND: 'BLEND'
  34753. };
  34754. /* UTILITY FUNCTIONS */
  34755. function resolveURL( url, path ) {
  34756. // Invalid URL
  34757. if ( typeof url !== 'string' || url === '' ) return '';
  34758. // Absolute URL http://,https://,//
  34759. if ( /^(https?:)?\/\//i.test( url ) ) return url;
  34760. // Data URI
  34761. if ( /^data:.*,.*$/i.test( url ) ) return url;
  34762. // Blob URL
  34763. if ( /^blob:.*$/i.test( url ) ) return url;
  34764. // Relative URL
  34765. return path + url;
  34766. }
  34767. /**
  34768. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material
  34769. */
  34770. function createDefaultMaterial() {
  34771. return new THREE.MeshStandardMaterial( {
  34772. color: 0xFFFFFF,
  34773. emissive: 0x000000,
  34774. metalness: 1,
  34775. roughness: 1,
  34776. transparent: false,
  34777. depthTest: true,
  34778. side: THREE.FrontSide
  34779. } );
  34780. }
  34781. /**
  34782. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets
  34783. *
  34784. * TODO: Implement support for morph targets on TANGENT attribute.
  34785. *
  34786. * @param {THREE.Mesh} mesh
  34787. * @param {GLTF.Mesh} meshDef
  34788. * @param {GLTF.Primitive} primitiveDef
  34789. * @param {Array<THREE.BufferAttribute>} accessors
  34790. */
  34791. function addMorphTargets( mesh, meshDef, primitiveDef, accessors ) {
  34792. var geometry = mesh.geometry;
  34793. var material = mesh.material;
  34794. var targets = primitiveDef.targets;
  34795. var morphAttributes = geometry.morphAttributes;
  34796. morphAttributes.position = [];
  34797. morphAttributes.normal = [];
  34798. material.morphTargets = true;
  34799. for ( var i = 0, il = targets.length; i < il; i ++ ) {
  34800. var target = targets[ i ];
  34801. var attributeName = 'morphTarget' + i;
  34802. var positionAttribute, normalAttribute;
  34803. if ( target.POSITION !== undefined ) {
  34804. // Three.js morph formula is
  34805. // position
  34806. // + weight0 * ( morphTarget0 - position )
  34807. // + weight1 * ( morphTarget1 - position )
  34808. // ...
  34809. // while the glTF one is
  34810. // position
  34811. // + weight0 * morphTarget0
  34812. // + weight1 * morphTarget1
  34813. // ...
  34814. // then adding position to morphTarget.
  34815. // So morphTarget value will depend on mesh's position, then cloning attribute
  34816. // for the case if attribute is shared among two or more meshes.
  34817. positionAttribute = accessors[ target.POSITION ].clone();
  34818. var position = geometry.attributes.position;
  34819. for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) {
  34820. positionAttribute.setXYZ(
  34821. j,
  34822. positionAttribute.getX( j ) + position.getX( j ),
  34823. positionAttribute.getY( j ) + position.getY( j ),
  34824. positionAttribute.getZ( j ) + position.getZ( j )
  34825. );
  34826. }
  34827. } else if ( geometry.attributes.position ) {
  34828. // Copying the original position not to affect the final position.
  34829. // See the formula above.
  34830. positionAttribute = geometry.attributes.position.clone();
  34831. }
  34832. if ( positionAttribute !== undefined ) {
  34833. positionAttribute.name = attributeName;
  34834. morphAttributes.position.push( positionAttribute );
  34835. }
  34836. if ( target.NORMAL !== undefined ) {
  34837. material.morphNormals = true;
  34838. // see target.POSITION's comment
  34839. normalAttribute = accessors[ target.NORMAL ].clone();
  34840. var normal = geometry.attributes.normal;
  34841. for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) {
  34842. normalAttribute.setXYZ(
  34843. j,
  34844. normalAttribute.getX( j ) + normal.getX( j ),
  34845. normalAttribute.getY( j ) + normal.getY( j ),
  34846. normalAttribute.getZ( j ) + normal.getZ( j )
  34847. );
  34848. }
  34849. } else if ( geometry.attributes.normal !== undefined ) {
  34850. normalAttribute = geometry.attributes.normal.clone();
  34851. }
  34852. if ( normalAttribute !== undefined ) {
  34853. normalAttribute.name = attributeName;
  34854. morphAttributes.normal.push( normalAttribute );
  34855. }
  34856. }
  34857. mesh.updateMorphTargets();
  34858. if ( meshDef.weights !== undefined ) {
  34859. for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) {
  34860. mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ];
  34861. }
  34862. }
  34863. }
  34864. function isPrimitiveEqual( a, b ) {
  34865. if ( a.indices !== b.indices ) {
  34866. return false;
  34867. }
  34868. var attribA = a.attributes || {};
  34869. var attribB = b.attributes || {};
  34870. var keysA = Object.keys( attribA );
  34871. var keysB = Object.keys( attribB );
  34872. if ( keysA.length !== keysB.length ) {
  34873. return false;
  34874. }
  34875. for ( var i = 0, il = keysA.length; i < il; i ++ ) {
  34876. var key = keysA[ i ];
  34877. if ( attribA[ key ] !== attribB[ key ] ) {
  34878. return false;
  34879. }
  34880. }
  34881. return true;
  34882. }
  34883. function getCachedGeometry( cache, newPrimitive ) {
  34884. for ( var i = 0, il = cache.length; i < il; i ++ ) {
  34885. var cached = cache[ i ];
  34886. if ( isPrimitiveEqual( cached.primitive, newPrimitive ) ) {
  34887. return cached.geometry;
  34888. }
  34889. }
  34890. return null;
  34891. }
  34892. /* GLTF PARSER */
  34893. function GLTFParser( json, extensions, options ) {
  34894. this.json = json || {};
  34895. this.extensions = extensions || {};
  34896. this.options = options || {};
  34897. // loader object cache
  34898. this.cache = new GLTFRegistry();
  34899. // BufferGeometry caching
  34900. this.primitiveCache = [];
  34901. this.textureLoader = new THREE.TextureLoader( this.options.manager );
  34902. this.textureLoader.setCrossOrigin( this.options.crossOrigin );
  34903. this.fileLoader = new THREE.FileLoader( this.options.manager );
  34904. this.fileLoader.setResponseType( 'arraybuffer' );
  34905. }
  34906. GLTFParser.prototype.parse = function ( onLoad, onError ) {
  34907. var json = this.json;
  34908. var parser = this;
  34909. // Clear the loader cache
  34910. this.cache.removeAll();
  34911. // Mark the special nodes/meshes in json for efficient parse
  34912. this.markDefs();
  34913. // Fire the callback on complete
  34914. this.getMultiDependencies( [
  34915. 'scene',
  34916. 'animation',
  34917. 'camera'
  34918. ] ).then( function ( dependencies ) {
  34919. var scenes = dependencies.scenes || [];
  34920. var scene = scenes[ json.scene || 0 ];
  34921. var animations = dependencies.animations || [];
  34922. var asset = json.asset;
  34923. var cameras = dependencies.cameras || [];
  34924. onLoad( scene, scenes, cameras, animations, asset );
  34925. } ).catch( onError );
  34926. };
  34927. /**
  34928. * Marks the special nodes/meshes in json for efficient parse.
  34929. */
  34930. GLTFParser.prototype.markDefs = function () {
  34931. var nodeDefs = this.json.nodes || [];
  34932. var skinDefs = this.json.skins || [];
  34933. var meshDefs = this.json.meshes || [];
  34934. var meshReferences = {};
  34935. var meshUses = {};
  34936. // Nothing in the node definition indicates whether it is a Bone or an
  34937. // Object3D. Use the skins' joint references to mark bones.
  34938. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) {
  34939. var joints = skinDefs[ skinIndex ].joints;
  34940. for ( var i = 0, il = joints.length; i < il; i ++ ) {
  34941. nodeDefs[ joints[ i ] ].isBone = true;
  34942. }
  34943. }
  34944. // Meshes can (and should) be reused by multiple nodes in a glTF asset. To
  34945. // avoid having more than one THREE.Mesh with the same name, count
  34946. // references and rename instances below.
  34947. //
  34948. // Example: CesiumMilkTruck sample model reuses "Wheel" meshes.
  34949. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) {
  34950. var nodeDef = nodeDefs[ nodeIndex ];
  34951. if ( nodeDef.mesh !== undefined ) {
  34952. if ( meshReferences[ nodeDef.mesh ] === undefined ) {
  34953. meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0;
  34954. }
  34955. meshReferences[ nodeDef.mesh ] ++;
  34956. // Nothing in the mesh definition indicates whether it is
  34957. // a SkinnedMesh or Mesh. Use the node's mesh reference
  34958. // to mark SkinnedMesh if node has skin.
  34959. if ( nodeDef.skin !== undefined ) {
  34960. meshDefs[ nodeDef.mesh ].isSkinnedMesh = true;
  34961. }
  34962. }
  34963. }
  34964. this.json.meshReferences = meshReferences;
  34965. this.json.meshUses = meshUses;
  34966. };
  34967. /**
  34968. * Requests the specified dependency asynchronously, with caching.
  34969. * @param {string} type
  34970. * @param {number} index
  34971. * @return {Promise<Object>}
  34972. */
  34973. GLTFParser.prototype.getDependency = function ( type, index ) {
  34974. var cacheKey = type + ':' + index;
  34975. var dependency = this.cache.get( cacheKey );
  34976. if ( ! dependency ) {
  34977. var fnName = 'load' + type.charAt( 0 ).toUpperCase() + type.slice( 1 );
  34978. dependency = this[ fnName ]( index );
  34979. this.cache.add( cacheKey, dependency );
  34980. }
  34981. return dependency;
  34982. };
  34983. /**
  34984. * Requests all dependencies of the specified type asynchronously, with caching.
  34985. * @param {string} type
  34986. * @return {Promise<Array<Object>>}
  34987. */
  34988. GLTFParser.prototype.getDependencies = function ( type ) {
  34989. var dependencies = this.cache.get( type );
  34990. if ( ! dependencies ) {
  34991. var parser = this;
  34992. var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || [];
  34993. dependencies = Promise.all( defs.map( function ( def, index ) {
  34994. return parser.getDependency( type, index );
  34995. } ) );
  34996. this.cache.add( type, dependencies );
  34997. }
  34998. return dependencies;
  34999. };
  35000. /**
  35001. * Requests all multiple dependencies of the specified types asynchronously, with caching.
  35002. * @param {Array<string>} types
  35003. * @return {Promise<Object<Array<Object>>>}
  35004. */
  35005. GLTFParser.prototype.getMultiDependencies = function ( types ) {
  35006. var results = {};
  35007. var pendings = [];
  35008. for ( var i = 0, il = types.length; i < il; i ++ ) {
  35009. var type = types[ i ];
  35010. var value = this.getDependencies( type );
  35011. value = value.then( function ( key, value ) {
  35012. results[ key ] = value;
  35013. }.bind( this, type + ( type === 'mesh' ? 'es' : 's' ) ) );
  35014. pendings.push( value );
  35015. }
  35016. return Promise.all( pendings ).then( function () {
  35017. return results;
  35018. } );
  35019. };
  35020. /**
  35021. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35022. * @param {number} bufferIndex
  35023. * @return {Promise<ArrayBuffer>}
  35024. */
  35025. GLTFParser.prototype.loadBuffer = function ( bufferIndex ) {
  35026. var bufferDef = this.json.buffers[ bufferIndex ];
  35027. var loader = this.fileLoader;
  35028. if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) {
  35029. throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' );
  35030. }
  35031. // If present, GLB container is required to be the first buffer.
  35032. if ( bufferDef.uri === undefined && bufferIndex === 0 ) {
  35033. return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body );
  35034. }
  35035. var options = this.options;
  35036. return new Promise( function ( resolve, reject ) {
  35037. loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () {
  35038. reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) );
  35039. } );
  35040. } );
  35041. };
  35042. /**
  35043. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views
  35044. * @param {number} bufferViewIndex
  35045. * @return {Promise<ArrayBuffer>}
  35046. */
  35047. GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) {
  35048. var bufferViewDef = this.json.bufferViews[ bufferViewIndex ];
  35049. return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) {
  35050. var byteLength = bufferViewDef.byteLength || 0;
  35051. var byteOffset = bufferViewDef.byteOffset || 0;
  35052. return buffer.slice( byteOffset, byteOffset + byteLength );
  35053. } );
  35054. };
  35055. /**
  35056. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors
  35057. * @param {number} accessorIndex
  35058. * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>}
  35059. */
  35060. GLTFParser.prototype.loadAccessor = function ( accessorIndex ) {
  35061. var json = this.json;
  35062. var accessorDef = this.json.accessors[ accessorIndex ];
  35063. var pendingBufferViews = [];
  35064. if ( accessorDef.bufferView !== undefined ) {
  35065. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) );
  35066. } else {
  35067. pendingBufferViews.push( null );
  35068. }
  35069. if ( accessorDef.sparse !== undefined ) {
  35070. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) );
  35071. pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) );
  35072. }
  35073. return Promise.all( pendingBufferViews ).then( function ( bufferViews ) {
  35074. var bufferView = bufferViews[ 0 ];
  35075. var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ];
  35076. var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ];
  35077. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  35078. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  35079. var itemBytes = elementBytes * itemSize;
  35080. var byteStride = json.bufferViews[ accessorDef.bufferView ].byteStride;
  35081. var normalized = accessorDef.normalized === true;
  35082. var array, bufferAttribute;
  35083. // The buffer is not interleaved if the stride is the item size in bytes.
  35084. if ( byteStride && byteStride !== itemBytes ) {
  35085. // Use the full buffer if it's interleaved.
  35086. array = new TypedArray( bufferView );
  35087. // Integer parameters to IB/IBA are in array elements, not bytes.
  35088. var ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes );
  35089. bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, accessorDef.byteOffset / elementBytes, normalized );
  35090. } else {
  35091. if ( bufferView === null ) {
  35092. array = new TypedArray( accessorDef.count * itemSize );
  35093. } else {
  35094. array = new TypedArray( bufferView, accessorDef.byteOffset, accessorDef.count * itemSize );
  35095. }
  35096. bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized );
  35097. }
  35098. // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors
  35099. if ( accessorDef.sparse !== undefined ) {
  35100. var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR;
  35101. var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ];
  35102. var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0;
  35103. var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0;
  35104. var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices );
  35105. var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize );
  35106. if ( bufferView !== null ) {
  35107. // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes.
  35108. bufferAttribute.setArray( bufferAttribute.array.slice() );
  35109. }
  35110. for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) {
  35111. var index = sparseIndices[ i ];
  35112. bufferAttribute.setX( index, sparseValues[ i * itemSize ] );
  35113. if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] );
  35114. if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] );
  35115. if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] );
  35116. if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' );
  35117. }
  35118. }
  35119. return bufferAttribute;
  35120. } );
  35121. };
  35122. /**
  35123. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures
  35124. * @param {number} textureIndex
  35125. * @return {Promise<THREE.Texture>}
  35126. */
  35127. GLTFParser.prototype.loadTexture = function ( textureIndex ) {
  35128. var parser = this;
  35129. var json = this.json;
  35130. var options = this.options;
  35131. var textureLoader = this.textureLoader;
  35132. var URL = window.URL || window.webkitURL;
  35133. var textureDef = json.textures[ textureIndex ];
  35134. var source = json.images[ textureDef.source ];
  35135. var sourceURI = source.uri;
  35136. var isObjectURL = false;
  35137. if ( source.bufferView !== undefined ) {
  35138. // Load binary image data from bufferView, if provided.
  35139. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) {
  35140. isObjectURL = true;
  35141. var blob = new Blob( [ bufferView ], { type: source.mimeType } );
  35142. sourceURI = URL.createObjectURL( blob );
  35143. return sourceURI;
  35144. } );
  35145. }
  35146. return Promise.resolve( sourceURI ).then( function ( sourceURI ) {
  35147. // Load Texture resource.
  35148. var loader = THREE.Loader.Handlers.get( sourceURI ) || textureLoader;
  35149. return new Promise( function ( resolve, reject ) {
  35150. loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject );
  35151. } );
  35152. } ).then( function ( texture ) {
  35153. // Clean up resources and configure Texture.
  35154. if ( isObjectURL === true ) {
  35155. URL.revokeObjectURL( sourceURI );
  35156. }
  35157. texture.flipY = false;
  35158. if ( textureDef.name !== undefined ) texture.name = textureDef.name;
  35159. texture.format = textureDef.format !== undefined ? WEBGL_TEXTURE_FORMATS[ textureDef.format ] : THREE.RGBAFormat;
  35160. if ( textureDef.internalFormat !== undefined && texture.format !== WEBGL_TEXTURE_FORMATS[ textureDef.internalFormat ] ) {
  35161. console.warn( 'THREE.GLTFLoader: Three.js does not support texture internalFormat which is different from texture format. ' +
  35162. 'internalFormat will be forced to be the same value as format.' );
  35163. }
  35164. texture.type = textureDef.type !== undefined ? WEBGL_TEXTURE_DATATYPES[ textureDef.type ] : THREE.UnsignedByteType;
  35165. var samplers = json.samplers || {};
  35166. var sampler = samplers[ textureDef.sampler ] || {};
  35167. texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter;
  35168. texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipMapLinearFilter;
  35169. texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping;
  35170. texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping;
  35171. return texture;
  35172. } );
  35173. };
  35174. /**
  35175. * Asynchronously assigns a texture to the given material parameters.
  35176. * @param {Object} materialParams
  35177. * @param {string} textureName
  35178. * @param {number} textureIndex
  35179. * @return {Promise}
  35180. */
  35181. GLTFParser.prototype.assignTexture = function ( materialParams, textureName, textureIndex ) {
  35182. return this.getDependency( 'texture', textureIndex ).then( function ( texture ) {
  35183. materialParams[ textureName ] = texture;
  35184. } );
  35185. };
  35186. /**
  35187. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials
  35188. * @param {number} materialIndex
  35189. * @return {Promise<THREE.Material>}
  35190. */
  35191. GLTFParser.prototype.loadMaterial = function ( materialIndex ) {
  35192. var parser = this;
  35193. var json = this.json;
  35194. var extensions = this.extensions;
  35195. var materialDef = this.json.materials[ materialIndex ];
  35196. var materialType;
  35197. var materialParams = {};
  35198. var materialExtensions = materialDef.extensions || {};
  35199. var pending = [];
  35200. if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_COMMON ] ) {
  35201. var khcExtension = extensions[ EXTENSIONS.KHR_MATERIALS_COMMON ];
  35202. materialType = khcExtension.getMaterialType( materialDef );
  35203. pending.push( khcExtension.extendParams( materialParams, materialDef, parser ) );
  35204. } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) {
  35205. var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35206. materialType = sgExtension.getMaterialType( materialDef );
  35207. pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) );
  35208. } else if ( materialDef.pbrMetallicRoughness !== undefined ) {
  35209. // Specification:
  35210. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material
  35211. materialType = THREE.MeshStandardMaterial;
  35212. var metallicRoughness = materialDef.pbrMetallicRoughness;
  35213. materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 );
  35214. materialParams.opacity = 1.0;
  35215. if ( Array.isArray( metallicRoughness.baseColorFactor ) ) {
  35216. var array = metallicRoughness.baseColorFactor;
  35217. materialParams.color.fromArray( array );
  35218. materialParams.opacity = array[ 3 ];
  35219. }
  35220. if ( metallicRoughness.baseColorTexture !== undefined ) {
  35221. pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture.index ) );
  35222. }
  35223. materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0;
  35224. materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0;
  35225. if ( metallicRoughness.metallicRoughnessTexture !== undefined ) {
  35226. var textureIndex = metallicRoughness.metallicRoughnessTexture.index;
  35227. pending.push( parser.assignTexture( materialParams, 'metalnessMap', textureIndex ) );
  35228. pending.push( parser.assignTexture( materialParams, 'roughnessMap', textureIndex ) );
  35229. }
  35230. } else {
  35231. materialType = THREE.MeshPhongMaterial;
  35232. }
  35233. if ( materialDef.doubleSided === true ) {
  35234. materialParams.side = THREE.DoubleSide;
  35235. }
  35236. var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE;
  35237. if ( alphaMode === ALPHA_MODES.BLEND ) {
  35238. materialParams.transparent = true;
  35239. } else {
  35240. materialParams.transparent = false;
  35241. if ( alphaMode === ALPHA_MODES.MASK ) {
  35242. materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5;
  35243. }
  35244. }
  35245. if ( materialDef.normalTexture !== undefined ) {
  35246. pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture.index ) );
  35247. materialParams.normalScale = new THREE.Vector2( 1, 1 );
  35248. if ( materialDef.normalTexture.scale !== undefined ) {
  35249. materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale );
  35250. }
  35251. }
  35252. if ( materialDef.occlusionTexture !== undefined ) {
  35253. pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture.index ) );
  35254. if ( materialDef.occlusionTexture.strength !== undefined ) {
  35255. materialParams.aoMapIntensity = materialDef.occlusionTexture.strength;
  35256. }
  35257. }
  35258. if ( materialDef.emissiveFactor !== undefined ) {
  35259. if ( materialType === THREE.MeshBasicMaterial ) {
  35260. materialParams.color = new THREE.Color().fromArray( materialDef.emissiveFactor );
  35261. } else {
  35262. materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor );
  35263. }
  35264. }
  35265. if ( materialDef.emissiveTexture !== undefined ) {
  35266. if ( materialType === THREE.MeshBasicMaterial ) {
  35267. pending.push( parser.assignTexture( materialParams, 'map', materialDef.emissiveTexture.index ) );
  35268. } else {
  35269. pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture.index ) );
  35270. }
  35271. }
  35272. return Promise.all( pending ).then( function () {
  35273. var material;
  35274. if ( materialType === THREE.ShaderMaterial ) {
  35275. material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams );
  35276. } else {
  35277. material = new materialType( materialParams );
  35278. }
  35279. if ( materialDef.name !== undefined ) material.name = materialDef.name;
  35280. // Normal map textures use OpenGL conventions:
  35281. // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#materialnormaltexture
  35282. if ( material.normalScale ) {
  35283. material.normalScale.x = - material.normalScale.x;
  35284. }
  35285. // emissiveTexture and baseColorTexture use sRGB encoding.
  35286. if ( material.map ) material.map.encoding = THREE.sRGBEncoding;
  35287. if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding;
  35288. if ( materialDef.extras ) material.userData = materialDef.extras;
  35289. return material;
  35290. } );
  35291. };
  35292. /**
  35293. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry
  35294. * @param {Array<Object>} primitives
  35295. * @return {Promise<Array<THREE.BufferGeometry>>}
  35296. */
  35297. GLTFParser.prototype.loadGeometries = function ( primitives ) {
  35298. var cache = this.primitiveCache;
  35299. return this.getDependencies( 'accessor' ).then( function ( accessors ) {
  35300. var geometries = [];
  35301. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35302. var primitive = primitives[ i ];
  35303. // See if we've already created this geometry
  35304. var cached = getCachedGeometry( cache, primitive );
  35305. if ( cached ) {
  35306. // Use the cached geometry if it exists
  35307. geometries.push( cached );
  35308. } else {
  35309. // Otherwise create a new geometry
  35310. var geometry = new THREE.BufferGeometry();
  35311. var attributes = primitive.attributes;
  35312. for ( var attributeId in attributes ) {
  35313. var attributeEntry = attributes[ attributeId ];
  35314. var bufferAttribute = accessors[ attributeEntry ];
  35315. switch ( attributeId ) {
  35316. case 'POSITION':
  35317. geometry.addAttribute( 'position', bufferAttribute );
  35318. break;
  35319. case 'NORMAL':
  35320. geometry.addAttribute( 'normal', bufferAttribute );
  35321. break;
  35322. case 'TEXCOORD_0':
  35323. case 'TEXCOORD0':
  35324. case 'TEXCOORD':
  35325. geometry.addAttribute( 'uv', bufferAttribute );
  35326. break;
  35327. case 'TEXCOORD_1':
  35328. geometry.addAttribute( 'uv2', bufferAttribute );
  35329. break;
  35330. case 'COLOR_0':
  35331. case 'COLOR0':
  35332. case 'COLOR':
  35333. geometry.addAttribute( 'color', bufferAttribute );
  35334. break;
  35335. case 'WEIGHTS_0':
  35336. case 'WEIGHT': // WEIGHT semantic deprecated.
  35337. geometry.addAttribute( 'skinWeight', bufferAttribute );
  35338. break;
  35339. case 'JOINTS_0':
  35340. case 'JOINT': // JOINT semantic deprecated.
  35341. geometry.addAttribute( 'skinIndex', bufferAttribute );
  35342. break;
  35343. }
  35344. }
  35345. if ( primitive.indices !== undefined ) {
  35346. geometry.setIndex( accessors[ primitive.indices ] );
  35347. }
  35348. // Cache this geometry
  35349. cache.push( {
  35350. primitive: primitive,
  35351. geometry: geometry
  35352. } );
  35353. geometries.push( geometry );
  35354. }
  35355. }
  35356. return geometries;
  35357. } );
  35358. };
  35359. /**
  35360. * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes
  35361. * @param {number} meshIndex
  35362. * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>}
  35363. */
  35364. GLTFParser.prototype.loadMesh = function ( meshIndex ) {
  35365. var scope = this;
  35366. var json = this.json;
  35367. var extensions = this.extensions;
  35368. var meshDef = this.json.meshes[ meshIndex ];
  35369. return this.getMultiDependencies( [
  35370. 'accessor',
  35371. 'material'
  35372. ] ).then( function ( dependencies ) {
  35373. var group = new THREE.Group();
  35374. var primitives = meshDef.primitives;
  35375. return scope.loadGeometries( primitives ).then( function ( geometries ) {
  35376. for ( var i = 0, il = primitives.length; i < il; i ++ ) {
  35377. var primitive = primitives[ i ];
  35378. var geometry = geometries[ i ];
  35379. var material = primitive.material === undefined
  35380. ? createDefaultMaterial()
  35381. : dependencies.materials[ primitive.material ];
  35382. if ( material.aoMap
  35383. && geometry.attributes.uv2 === undefined
  35384. && geometry.attributes.uv !== undefined ) {
  35385. console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' );
  35386. geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) );
  35387. }
  35388. // If the material will be modified later on, clone it now.
  35389. var useVertexColors = geometry.attributes.color !== undefined;
  35390. var useFlatShading = geometry.attributes.normal === undefined;
  35391. var useSkinning = meshDef.isSkinnedMesh === true;
  35392. var useMorphTargets = primitive.targets !== undefined;
  35393. if ( useVertexColors || useFlatShading || useSkinning || useMorphTargets ) {
  35394. if ( material.isGLTFSpecularGlossinessMaterial ) {
  35395. var specGlossExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ];
  35396. material = specGlossExtension.cloneMaterial( material );
  35397. } else {
  35398. material = material.clone();
  35399. }
  35400. }
  35401. if ( useVertexColors ) {
  35402. material.vertexColors = THREE.VertexColors;
  35403. material.needsUpdate = true;
  35404. }
  35405. if ( useFlatShading ) {
  35406. material.flatShading = true;
  35407. }
  35408. var mesh;
  35409. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES ||
  35410. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ||
  35411. primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ||
  35412. primitive.mode === undefined ) {
  35413. if ( useSkinning ) {
  35414. mesh = new THREE.SkinnedMesh( geometry, material );
  35415. material.skinning = true;
  35416. } else {
  35417. mesh = new THREE.Mesh( geometry, material );
  35418. }
  35419. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) {
  35420. mesh.drawMode = THREE.TriangleStripDrawMode;
  35421. } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) {
  35422. mesh.drawMode = THREE.TriangleFanDrawMode;
  35423. }
  35424. } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) {
  35425. mesh = new THREE.LineSegments( geometry, material );
  35426. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) {
  35427. mesh = new THREE.Line( geometry, material );
  35428. } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) {
  35429. mesh = new THREE.LineLoop( geometry, material );
  35430. } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) {
  35431. mesh = new THREE.Points( geometry, material );
  35432. } else {
  35433. throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode );
  35434. }
  35435. mesh.name = meshDef.name || ( 'mesh_' + meshIndex );
  35436. if ( useMorphTargets ) {
  35437. addMorphTargets( mesh, meshDef, primitive, dependencies.accessors );
  35438. }
  35439. if ( meshDef.extras !== undefined ) mesh.userData = meshDef.extras;
  35440. if ( primitive.extras !== undefined ) mesh.geometry.userData = primitive.extras;
  35441. // for Specular-Glossiness.
  35442. if ( material.isGLTFSpecularGlossinessMaterial === true ) {
  35443. mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms;
  35444. }
  35445. if ( primitives.length > 1 ) {
  35446. mesh.name += '_' + i;
  35447. group.add( mesh );
  35448. } else {
  35449. return mesh;
  35450. }
  35451. }
  35452. return group;
  35453. } );
  35454. } );
  35455. };
  35456. /**
  35457. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras
  35458. * @param {number} cameraIndex
  35459. * @return {Promise<THREE.Camera>}
  35460. */
  35461. GLTFParser.prototype.loadCamera = function ( cameraIndex ) {
  35462. var camera;
  35463. var cameraDef = this.json.cameras[ cameraIndex ];
  35464. var params = cameraDef[ cameraDef.type ];
  35465. if ( ! params ) {
  35466. console.warn( 'THREE.GLTFLoader: Missing camera parameters.' );
  35467. return;
  35468. }
  35469. if ( cameraDef.type === 'perspective' ) {
  35470. var aspectRatio = params.aspectRatio || 1;
  35471. var xfov = params.yfov * aspectRatio;
  35472. camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspectRatio, params.znear || 1, params.zfar || 2e6 );
  35473. } else if ( cameraDef.type === 'orthographic' ) {
  35474. camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar );
  35475. }
  35476. if ( cameraDef.name !== undefined ) camera.name = cameraDef.name;
  35477. if ( cameraDef.extras ) camera.userData = cameraDef.extras;
  35478. return Promise.resolve( camera );
  35479. };
  35480. /**
  35481. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins
  35482. * @param {number} skinIndex
  35483. * @return {Promise<Object>}
  35484. */
  35485. GLTFParser.prototype.loadSkin = function ( skinIndex ) {
  35486. var skinDef = this.json.skins[ skinIndex ];
  35487. var skinEntry = { joints: skinDef.joints };
  35488. if ( skinDef.inverseBindMatrices === undefined ) {
  35489. return Promise.resolve( skinEntry );
  35490. }
  35491. return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) {
  35492. skinEntry.inverseBindMatrices = accessor;
  35493. return skinEntry;
  35494. } );
  35495. };
  35496. /**
  35497. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations
  35498. * @param {number} animationIndex
  35499. * @return {Promise<THREE.AnimationClip>}
  35500. */
  35501. GLTFParser.prototype.loadAnimation = function ( animationIndex ) {
  35502. var json = this.json;
  35503. var animationDef = this.json.animations[ animationIndex ];
  35504. return this.getMultiDependencies( [
  35505. 'accessor',
  35506. 'node'
  35507. ] ).then( function ( dependencies ) {
  35508. var tracks = [];
  35509. for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) {
  35510. var channel = animationDef.channels[ i ];
  35511. var sampler = animationDef.samplers[ channel.sampler ];
  35512. if ( sampler ) {
  35513. var target = channel.target;
  35514. var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated.
  35515. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input;
  35516. var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output;
  35517. var inputAccessor = dependencies.accessors[ input ];
  35518. var outputAccessor = dependencies.accessors[ output ];
  35519. var node = dependencies.nodes[ name ];
  35520. if ( node ) {
  35521. node.updateMatrix();
  35522. node.matrixAutoUpdate = true;
  35523. var TypedKeyframeTrack;
  35524. switch ( PATH_PROPERTIES[ target.path ] ) {
  35525. case PATH_PROPERTIES.weights:
  35526. TypedKeyframeTrack = THREE.NumberKeyframeTrack;
  35527. break;
  35528. case PATH_PROPERTIES.rotation:
  35529. TypedKeyframeTrack = THREE.QuaternionKeyframeTrack;
  35530. break;
  35531. case PATH_PROPERTIES.position:
  35532. case PATH_PROPERTIES.scale:
  35533. default:
  35534. TypedKeyframeTrack = THREE.VectorKeyframeTrack;
  35535. break;
  35536. }
  35537. var targetName = node.name ? node.name : node.uuid;
  35538. if ( sampler.interpolation === 'CUBICSPLINE' ) {
  35539. var itemSize = outputAccessor.itemSize;
  35540. var TypedArray = outputAccessor.array.constructor;
  35541. var outputAccessorValues = new TypedArray( outputAccessor.count * itemSize / 3 );
  35542. // Layout of keyframe output values for CUBICSPLINE animations:
  35543. //
  35544. // [ inTangent1, splineVertex1, outTangent1, inTangent2, splineVertex2, ... ]
  35545. //
  35546. // THREE.KeyframeTrack infers tangents from the spline vertices when interpolating:
  35547. // those values are extracted below. This still guarantees smooth curves, but does
  35548. // throw away more precise information in the tangents. In the future, consider
  35549. // re-sampling at a higher framerate using the tangents provided.
  35550. //
  35551. // See: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation
  35552. for ( var j = 0, jl = outputAccessor.count; j < jl; j += 3 ) {
  35553. outputAccessorValues[ j * itemSize / 3 ] = outputAccessor.getX( j + 1 );
  35554. if ( itemSize > 1 ) outputAccessorValues[ j * itemSize / 3 + 1 ] = outputAccessor.getY( j + 1 );
  35555. if ( itemSize > 2 ) outputAccessorValues[ j * itemSize / 3 + 2 ] = outputAccessor.getZ( j + 1 );
  35556. if ( itemSize > 3 ) outputAccessorValues[ j * itemSize / 3 + 3 ] = outputAccessor.getW( j + 1 );
  35557. }
  35558. outputAccessor = new THREE.BufferAttribute( outputAccessorValues, itemSize / 3, outputAccessor.normalized );
  35559. }
  35560. var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear;
  35561. var targetNames = [];
  35562. if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) {
  35563. // node should be THREE.Group here but
  35564. // PATH_PROPERTIES.weights(morphTargetInfluences) should be
  35565. // the property of a mesh object under node.
  35566. // So finding targets here.
  35567. node.traverse( function ( object ) {
  35568. if ( object.isMesh === true && object.material.morphTargets === true ) {
  35569. targetNames.push( object.name ? object.name : object.uuid );
  35570. }
  35571. } );
  35572. } else {
  35573. targetNames.push( targetName );
  35574. }
  35575. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  35576. // buffers before creating a truncated copy to keep. Because buffers may
  35577. // be reused by other tracks, make copies here.
  35578. for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) {
  35579. tracks.push( new TypedKeyframeTrack(
  35580. targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ],
  35581. THREE.AnimationUtils.arraySlice( inputAccessor.array, 0 ),
  35582. THREE.AnimationUtils.arraySlice( outputAccessor.array, 0 ),
  35583. interpolation
  35584. ) );
  35585. }
  35586. }
  35587. }
  35588. }
  35589. var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex;
  35590. return new THREE.AnimationClip( name, undefined, tracks );
  35591. } );
  35592. };
  35593. /**
  35594. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy
  35595. * @param {number} nodeIndex
  35596. * @return {Promise<THREE.Object3D>}
  35597. */
  35598. GLTFParser.prototype.loadNode = function ( nodeIndex ) {
  35599. var json = this.json;
  35600. var extensions = this.extensions;
  35601. var meshReferences = this.json.meshReferences;
  35602. var meshUses = this.json.meshUses;
  35603. var nodeDef = this.json.nodes[ nodeIndex ];
  35604. return this.getMultiDependencies( [
  35605. 'mesh',
  35606. 'skin',
  35607. 'camera'
  35608. ] ).then( function ( dependencies ) {
  35609. var node;
  35610. if ( nodeDef.isBone === true ) {
  35611. node = new THREE.Bone();
  35612. } else if ( nodeDef.mesh !== undefined ) {
  35613. var mesh = dependencies.meshes[ nodeDef.mesh ];
  35614. node = mesh.clone();
  35615. // for Specular-Glossiness
  35616. if ( mesh.isGroup === true ) {
  35617. for ( var i = 0, il = mesh.children.length; i < il; i ++ ) {
  35618. var child = mesh.children[ i ];
  35619. if ( child.material && child.material.isGLTFSpecularGlossinessMaterial === true ) {
  35620. node.children[ i ].onBeforeRender = child.onBeforeRender;
  35621. }
  35622. }
  35623. } else {
  35624. if ( mesh.material && mesh.material.isGLTFSpecularGlossinessMaterial === true ) {
  35625. node.onBeforeRender = mesh.onBeforeRender;
  35626. }
  35627. }
  35628. if ( meshReferences[ nodeDef.mesh ] > 1 ) {
  35629. node.name += '_instance_' + meshUses[ nodeDef.mesh ] ++;
  35630. }
  35631. } else if ( nodeDef.camera !== undefined ) {
  35632. node = dependencies.cameras[ nodeDef.camera ];
  35633. } else if ( nodeDef.extensions
  35634. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  35635. && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  35636. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  35637. node = lights[ nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ];
  35638. } else {
  35639. node = new THREE.Object3D();
  35640. }
  35641. if ( nodeDef.name !== undefined ) {
  35642. node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name );
  35643. }
  35644. if ( nodeDef.extras ) node.userData = nodeDef.extras;
  35645. if ( nodeDef.matrix !== undefined ) {
  35646. var matrix = new THREE.Matrix4();
  35647. matrix.fromArray( nodeDef.matrix );
  35648. node.applyMatrix( matrix );
  35649. } else {
  35650. if ( nodeDef.translation !== undefined ) {
  35651. node.position.fromArray( nodeDef.translation );
  35652. }
  35653. if ( nodeDef.rotation !== undefined ) {
  35654. node.quaternion.fromArray( nodeDef.rotation );
  35655. }
  35656. if ( nodeDef.scale !== undefined ) {
  35657. node.scale.fromArray( nodeDef.scale );
  35658. }
  35659. }
  35660. return node;
  35661. } );
  35662. };
  35663. /**
  35664. * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes
  35665. * @param {number} sceneIndex
  35666. * @return {Promise<THREE.Scene>}
  35667. */
  35668. GLTFParser.prototype.loadScene = function () {
  35669. // scene node hierachy builder
  35670. function buildNodeHierachy( nodeId, parentObject, json, allNodes, skins ) {
  35671. var node = allNodes[ nodeId ];
  35672. var nodeDef = json.nodes[ nodeId ];
  35673. // build skeleton here as well
  35674. if ( nodeDef.skin !== undefined ) {
  35675. var meshes = node.isGroup === true ? node.children : [ node ];
  35676. for ( var i = 0, il = meshes.length; i < il; i ++ ) {
  35677. var mesh = meshes[ i ];
  35678. var skinEntry = skins[ nodeDef.skin ];
  35679. var bones = [];
  35680. var boneInverses = [];
  35681. for ( var j = 0, jl = skinEntry.joints.length; j < jl; j ++ ) {
  35682. var jointId = skinEntry.joints[ j ];
  35683. var jointNode = allNodes[ jointId ];
  35684. if ( jointNode ) {
  35685. bones.push( jointNode );
  35686. var mat = new THREE.Matrix4();
  35687. if ( skinEntry.inverseBindMatrices !== undefined ) {
  35688. mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 );
  35689. }
  35690. boneInverses.push( mat );
  35691. } else {
  35692. console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', jointId );
  35693. }
  35694. }
  35695. mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld );
  35696. }
  35697. }
  35698. // build node hierachy
  35699. parentObject.add( node );
  35700. if ( nodeDef.children ) {
  35701. var children = nodeDef.children;
  35702. for ( var i = 0, il = children.length; i < il; i ++ ) {
  35703. var child = children[ i ];
  35704. buildNodeHierachy( child, node, json, allNodes, skins );
  35705. }
  35706. }
  35707. }
  35708. return function loadScene( sceneIndex ) {
  35709. var json = this.json;
  35710. var extensions = this.extensions;
  35711. var sceneDef = this.json.scenes[ sceneIndex ];
  35712. return this.getMultiDependencies( [
  35713. 'node',
  35714. 'skin'
  35715. ] ).then( function ( dependencies ) {
  35716. var scene = new THREE.Scene();
  35717. if ( sceneDef.name !== undefined ) scene.name = sceneDef.name;
  35718. if ( sceneDef.extras ) scene.userData = sceneDef.extras;
  35719. var nodeIds = sceneDef.nodes || [];
  35720. for ( var i = 0, il = nodeIds.length; i < il; i ++ ) {
  35721. buildNodeHierachy( nodeIds[ i ], scene, json, dependencies.nodes, dependencies.skins );
  35722. }
  35723. // Ambient lighting, if present, is always attached to the scene root.
  35724. if ( sceneDef.extensions
  35725. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ]
  35726. && sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light !== undefined ) {
  35727. var lights = extensions[ EXTENSIONS.KHR_LIGHTS ].lights;
  35728. scene.add( lights[ sceneDef.extensions[ EXTENSIONS.KHR_LIGHTS ].light ] );
  35729. }
  35730. return scene;
  35731. } );
  35732. };
  35733. }();
  35734. return GLTFLoader;
  35735. } )();
  35736. },{}],44:[function(_dereq_,module,exports){
  35737. /**
  35738. * Loads a Wavefront .mtl file specifying materials
  35739. *
  35740. * @author angelxuanchang
  35741. */
  35742. THREE.MTLLoader = function ( manager ) {
  35743. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35744. };
  35745. THREE.MTLLoader.prototype = {
  35746. constructor: THREE.MTLLoader,
  35747. /**
  35748. * Loads and parses a MTL asset from a URL.
  35749. *
  35750. * @param {String} url - URL to the MTL file.
  35751. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  35752. * @param {Function} [onProgress] - Callback for download progress.
  35753. * @param {Function} [onError] - Callback for download errors.
  35754. *
  35755. * @see setPath setTexturePath
  35756. *
  35757. * @note In order for relative texture references to resolve correctly
  35758. * you must call setPath and/or setTexturePath explicitly prior to load.
  35759. */
  35760. load: function ( url, onLoad, onProgress, onError ) {
  35761. var scope = this;
  35762. var loader = new THREE.FileLoader( this.manager );
  35763. loader.setPath( this.path );
  35764. loader.load( url, function ( text ) {
  35765. onLoad( scope.parse( text ) );
  35766. }, onProgress, onError );
  35767. },
  35768. /**
  35769. * Set base path for resolving references.
  35770. * If set this path will be prepended to each loaded and found reference.
  35771. *
  35772. * @see setTexturePath
  35773. * @param {String} path
  35774. *
  35775. * @example
  35776. * mtlLoader.setPath( 'assets/obj/' );
  35777. * mtlLoader.load( 'my.mtl', ... );
  35778. */
  35779. setPath: function ( path ) {
  35780. this.path = path;
  35781. },
  35782. /**
  35783. * Set base path for resolving texture references.
  35784. * If set this path will be prepended found texture reference.
  35785. * If not set and setPath is, it will be used as texture base path.
  35786. *
  35787. * @see setPath
  35788. * @param {String} path
  35789. *
  35790. * @example
  35791. * mtlLoader.setPath( 'assets/obj/' );
  35792. * mtlLoader.setTexturePath( 'assets/textures/' );
  35793. * mtlLoader.load( 'my.mtl', ... );
  35794. */
  35795. setTexturePath: function ( path ) {
  35796. this.texturePath = path;
  35797. },
  35798. setBaseUrl: function ( path ) {
  35799. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  35800. this.setTexturePath( path );
  35801. },
  35802. setCrossOrigin: function ( value ) {
  35803. this.crossOrigin = value;
  35804. },
  35805. setMaterialOptions: function ( value ) {
  35806. this.materialOptions = value;
  35807. },
  35808. /**
  35809. * Parses a MTL file.
  35810. *
  35811. * @param {String} text - Content of MTL file
  35812. * @return {THREE.MTLLoader.MaterialCreator}
  35813. *
  35814. * @see setPath setTexturePath
  35815. *
  35816. * @note In order for relative texture references to resolve correctly
  35817. * you must call setPath and/or setTexturePath explicitly prior to parse.
  35818. */
  35819. parse: function ( text ) {
  35820. var lines = text.split( '\n' );
  35821. var info = {};
  35822. var delimiter_pattern = /\s+/;
  35823. var materialsInfo = {};
  35824. for ( var i = 0; i < lines.length; i ++ ) {
  35825. var line = lines[ i ];
  35826. line = line.trim();
  35827. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  35828. // Blank line or comment ignore
  35829. continue;
  35830. }
  35831. var pos = line.indexOf( ' ' );
  35832. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  35833. key = key.toLowerCase();
  35834. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  35835. value = value.trim();
  35836. if ( key === 'newmtl' ) {
  35837. // New material
  35838. info = { name: value };
  35839. materialsInfo[ value ] = info;
  35840. } else if ( info ) {
  35841. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  35842. var ss = value.split( delimiter_pattern, 3 );
  35843. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  35844. } else {
  35845. info[ key ] = value;
  35846. }
  35847. }
  35848. }
  35849. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  35850. materialCreator.setCrossOrigin( this.crossOrigin );
  35851. materialCreator.setManager( this.manager );
  35852. materialCreator.setMaterials( materialsInfo );
  35853. return materialCreator;
  35854. }
  35855. };
  35856. /**
  35857. * Create a new THREE-MTLLoader.MaterialCreator
  35858. * @param baseUrl - Url relative to which textures are loaded
  35859. * @param options - Set of options on how to construct the materials
  35860. * side: Which side to apply the material
  35861. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  35862. * wrap: What type of wrapping to apply for textures
  35863. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  35864. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  35865. * Default: false, assumed to be already normalized
  35866. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  35867. * Default: false
  35868. * @constructor
  35869. */
  35870. THREE.MTLLoader.MaterialCreator = function ( baseUrl, options ) {
  35871. this.baseUrl = baseUrl || '';
  35872. this.options = options;
  35873. this.materialsInfo = {};
  35874. this.materials = {};
  35875. this.materialsArray = [];
  35876. this.nameLookup = {};
  35877. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  35878. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  35879. };
  35880. THREE.MTLLoader.MaterialCreator.prototype = {
  35881. constructor: THREE.MTLLoader.MaterialCreator,
  35882. crossOrigin: 'Anonymous',
  35883. setCrossOrigin: function ( value ) {
  35884. this.crossOrigin = value;
  35885. },
  35886. setManager: function ( value ) {
  35887. this.manager = value;
  35888. },
  35889. setMaterials: function ( materialsInfo ) {
  35890. this.materialsInfo = this.convert( materialsInfo );
  35891. this.materials = {};
  35892. this.materialsArray = [];
  35893. this.nameLookup = {};
  35894. },
  35895. convert: function ( materialsInfo ) {
  35896. if ( ! this.options ) return materialsInfo;
  35897. var converted = {};
  35898. for ( var mn in materialsInfo ) {
  35899. // Convert materials info into normalized form based on options
  35900. var mat = materialsInfo[ mn ];
  35901. var covmat = {};
  35902. converted[ mn ] = covmat;
  35903. for ( var prop in mat ) {
  35904. var save = true;
  35905. var value = mat[ prop ];
  35906. var lprop = prop.toLowerCase();
  35907. switch ( lprop ) {
  35908. case 'kd':
  35909. case 'ka':
  35910. case 'ks':
  35911. // Diffuse color (color under white light) using RGB values
  35912. if ( this.options && this.options.normalizeRGB ) {
  35913. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  35914. }
  35915. if ( this.options && this.options.ignoreZeroRGBs ) {
  35916. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  35917. // ignore
  35918. save = false;
  35919. }
  35920. }
  35921. break;
  35922. default:
  35923. break;
  35924. }
  35925. if ( save ) {
  35926. covmat[ lprop ] = value;
  35927. }
  35928. }
  35929. }
  35930. return converted;
  35931. },
  35932. preload: function () {
  35933. for ( var mn in this.materialsInfo ) {
  35934. this.create( mn );
  35935. }
  35936. },
  35937. getIndex: function ( materialName ) {
  35938. return this.nameLookup[ materialName ];
  35939. },
  35940. getAsArray: function () {
  35941. var index = 0;
  35942. for ( var mn in this.materialsInfo ) {
  35943. this.materialsArray[ index ] = this.create( mn );
  35944. this.nameLookup[ mn ] = index;
  35945. index ++;
  35946. }
  35947. return this.materialsArray;
  35948. },
  35949. create: function ( materialName ) {
  35950. if ( this.materials[ materialName ] === undefined ) {
  35951. this.createMaterial_( materialName );
  35952. }
  35953. return this.materials[ materialName ];
  35954. },
  35955. createMaterial_: function ( materialName ) {
  35956. // Create material
  35957. var scope = this;
  35958. var mat = this.materialsInfo[ materialName ];
  35959. var params = {
  35960. name: materialName,
  35961. side: this.side
  35962. };
  35963. function resolveURL( baseUrl, url ) {
  35964. if ( typeof url !== 'string' || url === '' )
  35965. return '';
  35966. // Absolute URL
  35967. if ( /^https?:\/\//i.test( url ) ) return url;
  35968. return baseUrl + url;
  35969. }
  35970. function setMapForType( mapType, value ) {
  35971. if ( params[ mapType ] ) return; // Keep the first encountered texture
  35972. var texParams = scope.getTextureParams( value, params );
  35973. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  35974. map.repeat.copy( texParams.scale );
  35975. map.offset.copy( texParams.offset );
  35976. map.wrapS = scope.wrap;
  35977. map.wrapT = scope.wrap;
  35978. params[ mapType ] = map;
  35979. }
  35980. for ( var prop in mat ) {
  35981. var value = mat[ prop ];
  35982. var n;
  35983. if ( value === '' ) continue;
  35984. switch ( prop.toLowerCase() ) {
  35985. // Ns is material specular exponent
  35986. case 'kd':
  35987. // Diffuse color (color under white light) using RGB values
  35988. params.color = new THREE.Color().fromArray( value );
  35989. break;
  35990. case 'ks':
  35991. // Specular color (color when light is reflected from shiny surface) using RGB values
  35992. params.specular = new THREE.Color().fromArray( value );
  35993. break;
  35994. case 'map_kd':
  35995. // Diffuse texture map
  35996. setMapForType( "map", value );
  35997. break;
  35998. case 'map_ks':
  35999. // Specular map
  36000. setMapForType( "specularMap", value );
  36001. break;
  36002. case 'norm':
  36003. setMapForType( "normalMap", value );
  36004. break;
  36005. case 'map_bump':
  36006. case 'bump':
  36007. // Bump texture map
  36008. setMapForType( "bumpMap", value );
  36009. break;
  36010. case 'ns':
  36011. // The specular exponent (defines the focus of the specular highlight)
  36012. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  36013. params.shininess = parseFloat( value );
  36014. break;
  36015. case 'd':
  36016. n = parseFloat( value );
  36017. if ( n < 1 ) {
  36018. params.opacity = n;
  36019. params.transparent = true;
  36020. }
  36021. break;
  36022. case 'tr':
  36023. n = parseFloat( value );
  36024. if ( n > 0 ) {
  36025. params.opacity = 1 - n;
  36026. params.transparent = true;
  36027. }
  36028. break;
  36029. default:
  36030. break;
  36031. }
  36032. }
  36033. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  36034. return this.materials[ materialName ];
  36035. },
  36036. getTextureParams: function ( value, matParams ) {
  36037. var texParams = {
  36038. scale: new THREE.Vector2( 1, 1 ),
  36039. offset: new THREE.Vector2( 0, 0 )
  36040. };
  36041. var items = value.split( /\s+/ );
  36042. var pos;
  36043. pos = items.indexOf( '-bm' );
  36044. if ( pos >= 0 ) {
  36045. matParams.bumpScale = parseFloat( items[ pos + 1 ] );
  36046. items.splice( pos, 2 );
  36047. }
  36048. pos = items.indexOf( '-s' );
  36049. if ( pos >= 0 ) {
  36050. texParams.scale.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36051. items.splice( pos, 4 ); // we expect 3 parameters here!
  36052. }
  36053. pos = items.indexOf( '-o' );
  36054. if ( pos >= 0 ) {
  36055. texParams.offset.set( parseFloat( items[ pos + 1 ] ), parseFloat( items[ pos + 2 ] ) );
  36056. items.splice( pos, 4 ); // we expect 3 parameters here!
  36057. }
  36058. texParams.url = items.join( ' ' ).trim();
  36059. return texParams;
  36060. },
  36061. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  36062. var texture;
  36063. var loader = THREE.Loader.Handlers.get( url );
  36064. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  36065. if ( loader === null ) {
  36066. loader = new THREE.TextureLoader( manager );
  36067. }
  36068. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  36069. texture = loader.load( url, onLoad, onProgress, onError );
  36070. if ( mapping !== undefined ) texture.mapping = mapping;
  36071. return texture;
  36072. }
  36073. };
  36074. },{}],45:[function(_dereq_,module,exports){
  36075. /**
  36076. * @author mrdoob / http://mrdoob.com/
  36077. */
  36078. THREE.OBJLoader = ( function () {
  36079. // o object_name | g group_name
  36080. var object_pattern = /^[og]\s*(.+)?/;
  36081. // mtllib file_reference
  36082. var material_library_pattern = /^mtllib /;
  36083. // usemtl material_name
  36084. var material_use_pattern = /^usemtl /;
  36085. function ParserState() {
  36086. var state = {
  36087. objects: [],
  36088. object: {},
  36089. vertices: [],
  36090. normals: [],
  36091. colors: [],
  36092. uvs: [],
  36093. materialLibraries: [],
  36094. startObject: function ( name, fromDeclaration ) {
  36095. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  36096. // file. We need to use it for the first parsed g/o to keep things in sync.
  36097. if ( this.object && this.object.fromDeclaration === false ) {
  36098. this.object.name = name;
  36099. this.object.fromDeclaration = ( fromDeclaration !== false );
  36100. return;
  36101. }
  36102. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  36103. if ( this.object && typeof this.object._finalize === 'function' ) {
  36104. this.object._finalize( true );
  36105. }
  36106. this.object = {
  36107. name: name || '',
  36108. fromDeclaration: ( fromDeclaration !== false ),
  36109. geometry: {
  36110. vertices: [],
  36111. normals: [],
  36112. colors: [],
  36113. uvs: []
  36114. },
  36115. materials: [],
  36116. smooth: true,
  36117. startMaterial: function ( name, libraries ) {
  36118. var previous = this._finalize( false );
  36119. // New usemtl declaration overwrites an inherited material, except if faces were declared
  36120. // after the material, then it must be preserved for proper MultiMaterial continuation.
  36121. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  36122. this.materials.splice( previous.index, 1 );
  36123. }
  36124. var material = {
  36125. index: this.materials.length,
  36126. name: name || '',
  36127. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  36128. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  36129. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  36130. groupEnd: - 1,
  36131. groupCount: - 1,
  36132. inherited: false,
  36133. clone: function ( index ) {
  36134. var cloned = {
  36135. index: ( typeof index === 'number' ? index : this.index ),
  36136. name: this.name,
  36137. mtllib: this.mtllib,
  36138. smooth: this.smooth,
  36139. groupStart: 0,
  36140. groupEnd: - 1,
  36141. groupCount: - 1,
  36142. inherited: false
  36143. };
  36144. cloned.clone = this.clone.bind( cloned );
  36145. return cloned;
  36146. }
  36147. };
  36148. this.materials.push( material );
  36149. return material;
  36150. },
  36151. currentMaterial: function () {
  36152. if ( this.materials.length > 0 ) {
  36153. return this.materials[ this.materials.length - 1 ];
  36154. }
  36155. return undefined;
  36156. },
  36157. _finalize: function ( end ) {
  36158. var lastMultiMaterial = this.currentMaterial();
  36159. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  36160. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  36161. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  36162. lastMultiMaterial.inherited = false;
  36163. }
  36164. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  36165. if ( end && this.materials.length > 1 ) {
  36166. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  36167. if ( this.materials[ mi ].groupCount <= 0 ) {
  36168. this.materials.splice( mi, 1 );
  36169. }
  36170. }
  36171. }
  36172. // Guarantee at least one empty material, this makes the creation later more straight forward.
  36173. if ( end && this.materials.length === 0 ) {
  36174. this.materials.push( {
  36175. name: '',
  36176. smooth: this.smooth
  36177. } );
  36178. }
  36179. return lastMultiMaterial;
  36180. }
  36181. };
  36182. // Inherit previous objects material.
  36183. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  36184. // If a usemtl declaration is encountered while this new object is being parsed, it will
  36185. // overwrite the inherited material. Exception being that there was already face declarations
  36186. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  36187. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  36188. var declared = previousMaterial.clone( 0 );
  36189. declared.inherited = true;
  36190. this.object.materials.push( declared );
  36191. }
  36192. this.objects.push( this.object );
  36193. },
  36194. finalize: function () {
  36195. if ( this.object && typeof this.object._finalize === 'function' ) {
  36196. this.object._finalize( true );
  36197. }
  36198. },
  36199. parseVertexIndex: function ( value, len ) {
  36200. var index = parseInt( value, 10 );
  36201. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36202. },
  36203. parseNormalIndex: function ( value, len ) {
  36204. var index = parseInt( value, 10 );
  36205. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  36206. },
  36207. parseUVIndex: function ( value, len ) {
  36208. var index = parseInt( value, 10 );
  36209. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  36210. },
  36211. addVertex: function ( a, b, c ) {
  36212. var src = this.vertices;
  36213. var dst = this.object.geometry.vertices;
  36214. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36215. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36216. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36217. },
  36218. addVertexLine: function ( a ) {
  36219. var src = this.vertices;
  36220. var dst = this.object.geometry.vertices;
  36221. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36222. },
  36223. addNormal: function ( a, b, c ) {
  36224. var src = this.normals;
  36225. var dst = this.object.geometry.normals;
  36226. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36227. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36228. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36229. },
  36230. addColor: function ( a, b, c ) {
  36231. var src = this.colors;
  36232. var dst = this.object.geometry.colors;
  36233. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  36234. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  36235. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  36236. },
  36237. addUV: function ( a, b, c ) {
  36238. var src = this.uvs;
  36239. var dst = this.object.geometry.uvs;
  36240. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36241. dst.push( src[ b + 0 ], src[ b + 1 ] );
  36242. dst.push( src[ c + 0 ], src[ c + 1 ] );
  36243. },
  36244. addUVLine: function ( a ) {
  36245. var src = this.uvs;
  36246. var dst = this.object.geometry.uvs;
  36247. dst.push( src[ a + 0 ], src[ a + 1 ] );
  36248. },
  36249. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  36250. var vLen = this.vertices.length;
  36251. var ia = this.parseVertexIndex( a, vLen );
  36252. var ib = this.parseVertexIndex( b, vLen );
  36253. var ic = this.parseVertexIndex( c, vLen );
  36254. this.addVertex( ia, ib, ic );
  36255. if ( ua !== undefined ) {
  36256. var uvLen = this.uvs.length;
  36257. ia = this.parseUVIndex( ua, uvLen );
  36258. ib = this.parseUVIndex( ub, uvLen );
  36259. ic = this.parseUVIndex( uc, uvLen );
  36260. this.addUV( ia, ib, ic );
  36261. }
  36262. if ( na !== undefined ) {
  36263. // Normals are many times the same. If so, skip function call and parseInt.
  36264. var nLen = this.normals.length;
  36265. ia = this.parseNormalIndex( na, nLen );
  36266. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  36267. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  36268. this.addNormal( ia, ib, ic );
  36269. }
  36270. if ( this.colors.length > 0 ) {
  36271. this.addColor( ia, ib, ic );
  36272. }
  36273. },
  36274. addLineGeometry: function ( vertices, uvs ) {
  36275. this.object.geometry.type = 'Line';
  36276. var vLen = this.vertices.length;
  36277. var uvLen = this.uvs.length;
  36278. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  36279. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  36280. }
  36281. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  36282. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  36283. }
  36284. }
  36285. };
  36286. state.startObject( '', false );
  36287. return state;
  36288. }
  36289. //
  36290. function OBJLoader( manager ) {
  36291. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  36292. this.materials = null;
  36293. }
  36294. OBJLoader.prototype = {
  36295. constructor: OBJLoader,
  36296. load: function ( url, onLoad, onProgress, onError ) {
  36297. var scope = this;
  36298. var loader = new THREE.FileLoader( scope.manager );
  36299. loader.setPath( this.path );
  36300. loader.load( url, function ( text ) {
  36301. onLoad( scope.parse( text ) );
  36302. }, onProgress, onError );
  36303. },
  36304. setPath: function ( value ) {
  36305. this.path = value;
  36306. },
  36307. setMaterials: function ( materials ) {
  36308. this.materials = materials;
  36309. return this;
  36310. },
  36311. parse: function ( text ) {
  36312. console.time( 'OBJLoader' );
  36313. var state = new ParserState();
  36314. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  36315. // This is faster than String.split with regex that splits on both
  36316. text = text.replace( /\r\n/g, '\n' );
  36317. }
  36318. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  36319. // join lines separated by a line continuation character (\)
  36320. text = text.replace( /\\\n/g, '' );
  36321. }
  36322. var lines = text.split( '\n' );
  36323. var line = '', lineFirstChar = '';
  36324. var lineLength = 0;
  36325. var result = [];
  36326. // Faster to just trim left side of the line. Use if available.
  36327. var trimLeft = ( typeof ''.trimLeft === 'function' );
  36328. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  36329. line = lines[ i ];
  36330. line = trimLeft ? line.trimLeft() : line.trim();
  36331. lineLength = line.length;
  36332. if ( lineLength === 0 ) continue;
  36333. lineFirstChar = line.charAt( 0 );
  36334. // @todo invoke passed in handler if any
  36335. if ( lineFirstChar === '#' ) continue;
  36336. if ( lineFirstChar === 'v' ) {
  36337. var data = line.split( /\s+/ );
  36338. switch ( data[ 0 ] ) {
  36339. case 'v':
  36340. state.vertices.push(
  36341. parseFloat( data[ 1 ] ),
  36342. parseFloat( data[ 2 ] ),
  36343. parseFloat( data[ 3 ] )
  36344. );
  36345. if ( data.length === 8 ) {
  36346. state.colors.push(
  36347. parseFloat( data[ 4 ] ),
  36348. parseFloat( data[ 5 ] ),
  36349. parseFloat( data[ 6 ] )
  36350. );
  36351. }
  36352. break;
  36353. case 'vn':
  36354. state.normals.push(
  36355. parseFloat( data[ 1 ] ),
  36356. parseFloat( data[ 2 ] ),
  36357. parseFloat( data[ 3 ] )
  36358. );
  36359. break;
  36360. case 'vt':
  36361. state.uvs.push(
  36362. parseFloat( data[ 1 ] ),
  36363. parseFloat( data[ 2 ] )
  36364. );
  36365. break;
  36366. }
  36367. } else if ( lineFirstChar === 'f' ) {
  36368. var lineData = line.substr( 1 ).trim();
  36369. var vertexData = lineData.split( /\s+/ );
  36370. var faceVertices = [];
  36371. // Parse the face vertex data into an easy to work with format
  36372. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  36373. var vertex = vertexData[ j ];
  36374. if ( vertex.length > 0 ) {
  36375. var vertexParts = vertex.split( '/' );
  36376. faceVertices.push( vertexParts );
  36377. }
  36378. }
  36379. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  36380. var v1 = faceVertices[ 0 ];
  36381. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  36382. var v2 = faceVertices[ j ];
  36383. var v3 = faceVertices[ j + 1 ];
  36384. state.addFace(
  36385. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  36386. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  36387. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  36388. );
  36389. }
  36390. } else if ( lineFirstChar === 'l' ) {
  36391. var lineParts = line.substring( 1 ).trim().split( " " );
  36392. var lineVertices = [], lineUVs = [];
  36393. if ( line.indexOf( "/" ) === - 1 ) {
  36394. lineVertices = lineParts;
  36395. } else {
  36396. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  36397. var parts = lineParts[ li ].split( "/" );
  36398. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  36399. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  36400. }
  36401. }
  36402. state.addLineGeometry( lineVertices, lineUVs );
  36403. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  36404. // o object_name
  36405. // or
  36406. // g group_name
  36407. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  36408. // var name = result[ 0 ].substr( 1 ).trim();
  36409. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  36410. state.startObject( name );
  36411. } else if ( material_use_pattern.test( line ) ) {
  36412. // material
  36413. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  36414. } else if ( material_library_pattern.test( line ) ) {
  36415. // mtl file
  36416. state.materialLibraries.push( line.substring( 7 ).trim() );
  36417. } else if ( lineFirstChar === 's' ) {
  36418. result = line.split( ' ' );
  36419. // smooth shading
  36420. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  36421. // but does not define a usemtl for each face set.
  36422. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  36423. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  36424. // where explicit usemtl defines geometry groups.
  36425. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  36426. /*
  36427. * http://paulbourke.net/dataformats/obj/
  36428. * or
  36429. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  36430. *
  36431. * From chapter "Grouping" Syntax explanation "s group_number":
  36432. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  36433. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  36434. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  36435. * than 0."
  36436. */
  36437. if ( result.length > 1 ) {
  36438. var value = result[ 1 ].trim().toLowerCase();
  36439. state.object.smooth = ( value !== '0' && value !== 'off' );
  36440. } else {
  36441. // ZBrush can produce "s" lines #11707
  36442. state.object.smooth = true;
  36443. }
  36444. var material = state.object.currentMaterial();
  36445. if ( material ) material.smooth = state.object.smooth;
  36446. } else {
  36447. // Handle null terminated files without exception
  36448. if ( line === '\0' ) continue;
  36449. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  36450. }
  36451. }
  36452. state.finalize();
  36453. var container = new THREE.Group();
  36454. container.materialLibraries = [].concat( state.materialLibraries );
  36455. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  36456. var object = state.objects[ i ];
  36457. var geometry = object.geometry;
  36458. var materials = object.materials;
  36459. var isLine = ( geometry.type === 'Line' );
  36460. // Skip o/g line declarations that did not follow with any faces
  36461. if ( geometry.vertices.length === 0 ) continue;
  36462. var buffergeometry = new THREE.BufferGeometry();
  36463. buffergeometry.addAttribute( 'position', new THREE.Float32BufferAttribute( geometry.vertices, 3 ) );
  36464. if ( geometry.normals.length > 0 ) {
  36465. buffergeometry.addAttribute( 'normal', new THREE.Float32BufferAttribute( geometry.normals, 3 ) );
  36466. } else {
  36467. buffergeometry.computeVertexNormals();
  36468. }
  36469. if ( geometry.colors.length > 0 ) {
  36470. buffergeometry.addAttribute( 'color', new THREE.Float32BufferAttribute( geometry.colors, 3 ) );
  36471. }
  36472. if ( geometry.uvs.length > 0 ) {
  36473. buffergeometry.addAttribute( 'uv', new THREE.Float32BufferAttribute( geometry.uvs, 2 ) );
  36474. }
  36475. // Create materials
  36476. var createdMaterials = [];
  36477. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  36478. var sourceMaterial = materials[ mi ];
  36479. var material = undefined;
  36480. if ( this.materials !== null ) {
  36481. material = this.materials.create( sourceMaterial.name );
  36482. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  36483. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  36484. var materialLine = new THREE.LineBasicMaterial();
  36485. materialLine.copy( material );
  36486. material = materialLine;
  36487. }
  36488. }
  36489. if ( ! material ) {
  36490. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  36491. material.name = sourceMaterial.name;
  36492. }
  36493. material.flatShading = sourceMaterial.smooth ? false : true;
  36494. createdMaterials.push( material );
  36495. }
  36496. // Create mesh
  36497. var mesh;
  36498. if ( createdMaterials.length > 1 ) {
  36499. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  36500. var sourceMaterial = materials[ mi ];
  36501. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  36502. }
  36503. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials ) : new THREE.LineSegments( buffergeometry, createdMaterials ) );
  36504. } else {
  36505. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  36506. }
  36507. mesh.name = object.name;
  36508. container.add( mesh );
  36509. }
  36510. console.timeEnd( 'OBJLoader' );
  36511. return container;
  36512. }
  36513. };
  36514. return OBJLoader;
  36515. } )();
  36516. },{}],46:[function(_dereq_,module,exports){
  36517. exports = module.exports = trim;
  36518. function trim(str){
  36519. return str.replace(/^\s*|\s*$/g, '');
  36520. }
  36521. exports.left = function(str){
  36522. return str.replace(/^\s*/, '');
  36523. };
  36524. exports.right = function(str){
  36525. return str.replace(/\s*$/, '');
  36526. };
  36527. },{}],47:[function(_dereq_,module,exports){
  36528. module.exports={
  36529. "_args": [
  36530. [
  36531. {
  36532. "raw": "webvr-polyfill@^0.9.40",
  36533. "scope": null,
  36534. "escapedName": "webvr-polyfill",
  36535. "name": "webvr-polyfill",
  36536. "rawSpec": "^0.9.40",
  36537. "spec": ">=0.9.40 <0.10.0",
  36538. "type": "range"
  36539. },
  36540. "/home/ubuntu/a-frobot/aframe"
  36541. ]
  36542. ],
  36543. "_from": "webvr-polyfill@>=0.9.40 <0.10.0",
  36544. "_id": "webvr-polyfill@0.9.40",
  36545. "_inCache": true,
  36546. "_location": "/webvr-polyfill",
  36547. "_nodeVersion": "8.6.0",
  36548. "_npmOperationalInternal": {
  36549. "host": "s3://npm-registry-packages",
  36550. "tmp": "tmp/webvr-polyfill-0.9.40.tgz_1507657755590_0.00047161197289824486"
  36551. },
  36552. "_npmUser": {
  36553. "name": "jsantell",
  36554. "email": "jsantell@gmail.com"
  36555. },
  36556. "_npmVersion": "5.3.0",
  36557. "_phantomChildren": {},
  36558. "_requested": {
  36559. "raw": "webvr-polyfill@^0.9.40",
  36560. "scope": null,
  36561. "escapedName": "webvr-polyfill",
  36562. "name": "webvr-polyfill",
  36563. "rawSpec": "^0.9.40",
  36564. "spec": ">=0.9.40 <0.10.0",
  36565. "type": "range"
  36566. },
  36567. "_requiredBy": [
  36568. "/"
  36569. ],
  36570. "_resolved": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.40.tgz",
  36571. "_shasum": "2cfa0ec0e0cc6ba7238c73a09cba4952fff59a63",
  36572. "_shrinkwrap": null,
  36573. "_spec": "webvr-polyfill@^0.9.40",
  36574. "_where": "/home/ubuntu/a-frobot/aframe",
  36575. "authors": [
  36576. "Boris Smus <boris@smus.com>",
  36577. "Brandon Jones <tojiro@gmail.com>",
  36578. "Jordan Santell <jordan@jsantell.com>"
  36579. ],
  36580. "bugs": {
  36581. "url": "https://github.com/googlevr/webvr-polyfill/issues"
  36582. },
  36583. "dependencies": {},
  36584. "description": "Use WebVR today, on mobile or desktop, without requiring a special browser build.",
  36585. "devDependencies": {
  36586. "chai": "^3.5.0",
  36587. "jsdom": "^9.12.0",
  36588. "mocha": "^3.2.0",
  36589. "semver": "^5.3.0",
  36590. "webpack": "^2.6.1",
  36591. "webpack-dev-server": "2.7.1"
  36592. },
  36593. "directories": {},
  36594. "dist": {
  36595. "integrity": "sha512-m7jhJHjFcUYPyPSNeGmly7a2h/cP7bARz0OZMoUn5SueVXEKeZ4P7bzbAUDBDvvqCsa5gHgM3PFIhYe13bqaWw==",
  36596. "shasum": "2cfa0ec0e0cc6ba7238c73a09cba4952fff59a63",
  36597. "tarball": "https://registry.npmjs.org/webvr-polyfill/-/webvr-polyfill-0.9.40.tgz"
  36598. },
  36599. "gitHead": "45828ffdb8c3e0f9bb90296d6039d3cc7909ba8e",
  36600. "homepage": "https://github.com/googlevr/webvr-polyfill",
  36601. "keywords": [
  36602. "vr",
  36603. "webvr"
  36604. ],
  36605. "license": "Apache-2.0",
  36606. "main": "src/node-entry",
  36607. "maintainers": [
  36608. {
  36609. "name": "jsantell",
  36610. "email": "jsantell@gmail.com"
  36611. },
  36612. {
  36613. "name": "toji",
  36614. "email": "tojiro@gmail.com"
  36615. },
  36616. {
  36617. "name": "smus",
  36618. "email": "boris@smus.com"
  36619. }
  36620. ],
  36621. "name": "webvr-polyfill",
  36622. "optionalDependencies": {},
  36623. "readme": "ERROR: No README data found!",
  36624. "repository": {
  36625. "type": "git",
  36626. "url": "git+https://github.com/googlevr/webvr-polyfill.git"
  36627. },
  36628. "scripts": {
  36629. "build": "webpack",
  36630. "start": "npm run watch",
  36631. "test": "mocha",
  36632. "watch": "webpack-dev-server"
  36633. },
  36634. "version": "0.9.40"
  36635. }
  36636. },{}],48:[function(_dereq_,module,exports){
  36637. /*
  36638. * Copyright 2015 Google Inc. All Rights Reserved.
  36639. * Licensed under the Apache License, Version 2.0 (the "License");
  36640. * you may not use this file except in compliance with the License.
  36641. * You may obtain a copy of the License at
  36642. *
  36643. * http://www.apache.org/licenses/LICENSE-2.0
  36644. *
  36645. * Unless required by applicable law or agreed to in writing, software
  36646. * distributed under the License is distributed on an "AS IS" BASIS,
  36647. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36648. * See the License for the specific language governing permissions and
  36649. * limitations under the License.
  36650. */
  36651. var Util = _dereq_('./util.js');
  36652. var WakeLock = _dereq_('./wakelock.js');
  36653. // Start at a higher number to reduce chance of conflict.
  36654. var nextDisplayId = 1000;
  36655. var hasShowDeprecationWarning = false;
  36656. var defaultLeftBounds = [0, 0, 0.5, 1];
  36657. var defaultRightBounds = [0.5, 0, 0.5, 1];
  36658. /**
  36659. * The base class for all VR frame data.
  36660. */
  36661. function VRFrameData() {
  36662. this.leftProjectionMatrix = new Float32Array(16);
  36663. this.leftViewMatrix = new Float32Array(16);
  36664. this.rightProjectionMatrix = new Float32Array(16);
  36665. this.rightViewMatrix = new Float32Array(16);
  36666. this.pose = null;
  36667. };
  36668. /**
  36669. * The base class for all VR displays.
  36670. */
  36671. function VRDisplay() {
  36672. this.isPolyfilled = true;
  36673. this.displayId = nextDisplayId++;
  36674. this.displayName = 'webvr-polyfill displayName';
  36675. this.depthNear = 0.01;
  36676. this.depthFar = 10000.0;
  36677. this.isConnected = true;
  36678. this.isPresenting = false;
  36679. this.capabilities = {
  36680. hasPosition: false,
  36681. hasOrientation: false,
  36682. hasExternalDisplay: false,
  36683. canPresent: false,
  36684. maxLayers: 1
  36685. };
  36686. this.stageParameters = null;
  36687. // "Private" members.
  36688. this.waitingForPresent_ = false;
  36689. this.layer_ = null;
  36690. this.fullscreenElement_ = null;
  36691. this.fullscreenWrapper_ = null;
  36692. this.fullscreenElementCachedStyle_ = null;
  36693. this.fullscreenEventTarget_ = null;
  36694. this.fullscreenChangeHandler_ = null;
  36695. this.fullscreenErrorHandler_ = null;
  36696. this.wakelock_ = new WakeLock();
  36697. }
  36698. VRDisplay.prototype.getFrameData = function(frameData) {
  36699. // TODO: Technically this should retain it's value for the duration of a frame
  36700. // but I doubt that's practical to do in javascript.
  36701. return Util.frameDataFromPose(frameData, this.getPose(), this);
  36702. };
  36703. VRDisplay.prototype.getPose = function() {
  36704. // TODO: Technically this should retain it's value for the duration of a frame
  36705. // but I doubt that's practical to do in javascript.
  36706. return this.getImmediatePose();
  36707. };
  36708. VRDisplay.prototype.requestAnimationFrame = function(callback) {
  36709. return window.requestAnimationFrame(callback);
  36710. };
  36711. VRDisplay.prototype.cancelAnimationFrame = function(id) {
  36712. return window.cancelAnimationFrame(id);
  36713. };
  36714. VRDisplay.prototype.wrapForFullscreen = function(element) {
  36715. // Don't wrap in iOS.
  36716. if (Util.isIOS()) {
  36717. return element;
  36718. }
  36719. if (!this.fullscreenWrapper_) {
  36720. this.fullscreenWrapper_ = document.createElement('div');
  36721. var cssProperties = [
  36722. 'height: ' + Math.min(screen.height, screen.width) + 'px !important',
  36723. 'top: 0 !important',
  36724. 'left: 0 !important',
  36725. 'right: 0 !important',
  36726. 'border: 0',
  36727. 'margin: 0',
  36728. 'padding: 0',
  36729. 'z-index: 999999 !important',
  36730. 'position: fixed',
  36731. ];
  36732. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  36733. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  36734. }
  36735. if (this.fullscreenElement_ == element) {
  36736. return this.fullscreenWrapper_;
  36737. }
  36738. // Remove any previously applied wrappers
  36739. this.removeFullscreenWrapper();
  36740. this.fullscreenElement_ = element;
  36741. var parent = this.fullscreenElement_.parentElement;
  36742. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  36743. parent.removeChild(this.fullscreenElement_);
  36744. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  36745. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  36746. var self = this;
  36747. function applyFullscreenElementStyle() {
  36748. if (!self.fullscreenElement_) {
  36749. return;
  36750. }
  36751. var cssProperties = [
  36752. 'position: absolute',
  36753. 'top: 0',
  36754. 'left: 0',
  36755. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  36756. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  36757. 'border: 0',
  36758. 'margin: 0',
  36759. 'padding: 0',
  36760. ];
  36761. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  36762. }
  36763. applyFullscreenElementStyle();
  36764. return this.fullscreenWrapper_;
  36765. };
  36766. VRDisplay.prototype.removeFullscreenWrapper = function() {
  36767. if (!this.fullscreenElement_) {
  36768. return;
  36769. }
  36770. var element = this.fullscreenElement_;
  36771. if (this.fullscreenElementCachedStyle_) {
  36772. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  36773. } else {
  36774. element.removeAttribute('style');
  36775. }
  36776. this.fullscreenElement_ = null;
  36777. this.fullscreenElementCachedStyle_ = null;
  36778. var parent = this.fullscreenWrapper_.parentElement;
  36779. this.fullscreenWrapper_.removeChild(element);
  36780. parent.insertBefore(element, this.fullscreenWrapper_);
  36781. parent.removeChild(this.fullscreenWrapper_);
  36782. return element;
  36783. };
  36784. VRDisplay.prototype.requestPresent = function(layers) {
  36785. var wasPresenting = this.isPresenting;
  36786. var self = this;
  36787. if (!(layers instanceof Array)) {
  36788. if (!hasShowDeprecationWarning) {
  36789. console.warn("Using a deprecated form of requestPresent. Should pass in an array of VRLayers.");
  36790. hasShowDeprecationWarning = true;
  36791. }
  36792. layers = [layers];
  36793. }
  36794. return new Promise(function(resolve, reject) {
  36795. if (!self.capabilities.canPresent) {
  36796. reject(new Error('VRDisplay is not capable of presenting.'));
  36797. return;
  36798. }
  36799. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  36800. reject(new Error('Invalid number of layers.'));
  36801. return;
  36802. }
  36803. var incomingLayer = layers[0];
  36804. if (!incomingLayer.source) {
  36805. /*
  36806. todo: figure out the correct behavior if the source is not provided.
  36807. see https://github.com/w3c/webvr/issues/58
  36808. */
  36809. resolve();
  36810. return;
  36811. }
  36812. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  36813. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  36814. if (wasPresenting) {
  36815. // Already presenting, just changing configuration
  36816. var layer = self.layer_;
  36817. if (layer.source !== incomingLayer.source) {
  36818. layer.source = incomingLayer.source;
  36819. }
  36820. for (var i = 0; i < 4; i++) {
  36821. layer.leftBounds[i] = leftBounds[i];
  36822. layer.rightBounds[i] = rightBounds[i];
  36823. }
  36824. resolve();
  36825. return;
  36826. }
  36827. // Was not already presenting.
  36828. self.layer_ = {
  36829. predistorted: incomingLayer.predistorted,
  36830. source: incomingLayer.source,
  36831. leftBounds: leftBounds.slice(0),
  36832. rightBounds: rightBounds.slice(0)
  36833. };
  36834. self.waitingForPresent_ = false;
  36835. if (self.layer_ && self.layer_.source) {
  36836. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  36837. var onFullscreenChange = function() {
  36838. var actualFullscreenElement = Util.getFullscreenElement();
  36839. self.isPresenting = (fullscreenElement === actualFullscreenElement);
  36840. if (self.isPresenting) {
  36841. if (screen.orientation && screen.orientation.lock) {
  36842. screen.orientation.lock('landscape-primary').catch(function(error){
  36843. console.error('screen.orientation.lock() failed due to', error.message)
  36844. });
  36845. }
  36846. self.waitingForPresent_ = false;
  36847. self.beginPresent_();
  36848. resolve();
  36849. } else {
  36850. if (screen.orientation && screen.orientation.unlock) {
  36851. screen.orientation.unlock();
  36852. }
  36853. self.removeFullscreenWrapper();
  36854. self.wakelock_.release();
  36855. self.endPresent_();
  36856. self.removeFullscreenListeners_();
  36857. }
  36858. self.fireVRDisplayPresentChange_();
  36859. }
  36860. var onFullscreenError = function() {
  36861. if (!self.waitingForPresent_) {
  36862. return;
  36863. }
  36864. self.removeFullscreenWrapper();
  36865. self.removeFullscreenListeners_();
  36866. self.wakelock_.release();
  36867. self.waitingForPresent_ = false;
  36868. self.isPresenting = false;
  36869. reject(new Error('Unable to present.'));
  36870. }
  36871. self.addFullscreenListeners_(fullscreenElement,
  36872. onFullscreenChange, onFullscreenError);
  36873. if (Util.requestFullscreen(fullscreenElement)) {
  36874. self.wakelock_.request();
  36875. self.waitingForPresent_ = true;
  36876. } else if (Util.isIOS() || Util.isWebViewAndroid()) {
  36877. // *sigh* Just fake it.
  36878. self.wakelock_.request();
  36879. self.isPresenting = true;
  36880. self.beginPresent_();
  36881. self.fireVRDisplayPresentChange_();
  36882. resolve();
  36883. }
  36884. }
  36885. if (!self.waitingForPresent_ && !Util.isIOS()) {
  36886. Util.exitFullscreen();
  36887. reject(new Error('Unable to present.'));
  36888. }
  36889. });
  36890. };
  36891. VRDisplay.prototype.exitPresent = function() {
  36892. var wasPresenting = this.isPresenting;
  36893. var self = this;
  36894. this.isPresenting = false;
  36895. this.layer_ = null;
  36896. this.wakelock_.release();
  36897. return new Promise(function(resolve, reject) {
  36898. if (wasPresenting) {
  36899. if (!Util.exitFullscreen() && Util.isIOS()) {
  36900. self.endPresent_();
  36901. self.fireVRDisplayPresentChange_();
  36902. }
  36903. if (Util.isWebViewAndroid()) {
  36904. self.removeFullscreenWrapper();
  36905. self.removeFullscreenListeners_();
  36906. self.endPresent_();
  36907. self.fireVRDisplayPresentChange_();
  36908. }
  36909. resolve();
  36910. } else {
  36911. reject(new Error('Was not presenting to VRDisplay.'));
  36912. }
  36913. });
  36914. };
  36915. VRDisplay.prototype.getLayers = function() {
  36916. if (this.layer_) {
  36917. return [this.layer_];
  36918. }
  36919. return [];
  36920. };
  36921. VRDisplay.prototype.fireVRDisplayPresentChange_ = function() {
  36922. // Important: unfortunately we cannot have full spec compliance here.
  36923. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  36924. // being e.detail.display, instead of e.display as per WebVR spec).
  36925. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: this}});
  36926. window.dispatchEvent(event);
  36927. };
  36928. VRDisplay.prototype.fireVRDisplayConnect_ = function() {
  36929. // Important: unfortunately we cannot have full spec compliance here.
  36930. // CustomEvent custom fields all go under e.detail (so the VRDisplay ends up
  36931. // being e.detail.display, instead of e.display as per WebVR spec).
  36932. var event = new CustomEvent('vrdisplayconnect', {detail: {display: this}});
  36933. window.dispatchEvent(event);
  36934. };
  36935. VRDisplay.prototype.addFullscreenListeners_ = function(element, changeHandler, errorHandler) {
  36936. this.removeFullscreenListeners_();
  36937. this.fullscreenEventTarget_ = element;
  36938. this.fullscreenChangeHandler_ = changeHandler;
  36939. this.fullscreenErrorHandler_ = errorHandler;
  36940. if (changeHandler) {
  36941. if (document.fullscreenEnabled) {
  36942. element.addEventListener('fullscreenchange', changeHandler, false);
  36943. } else if (document.webkitFullscreenEnabled) {
  36944. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  36945. } else if (document.mozFullScreenEnabled) {
  36946. document.addEventListener('mozfullscreenchange', changeHandler, false);
  36947. } else if (document.msFullscreenEnabled) {
  36948. element.addEventListener('msfullscreenchange', changeHandler, false);
  36949. }
  36950. }
  36951. if (errorHandler) {
  36952. if (document.fullscreenEnabled) {
  36953. element.addEventListener('fullscreenerror', errorHandler, false);
  36954. } else if (document.webkitFullscreenEnabled) {
  36955. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  36956. } else if (document.mozFullScreenEnabled) {
  36957. document.addEventListener('mozfullscreenerror', errorHandler, false);
  36958. } else if (document.msFullscreenEnabled) {
  36959. element.addEventListener('msfullscreenerror', errorHandler, false);
  36960. }
  36961. }
  36962. };
  36963. VRDisplay.prototype.removeFullscreenListeners_ = function() {
  36964. if (!this.fullscreenEventTarget_)
  36965. return;
  36966. var element = this.fullscreenEventTarget_;
  36967. if (this.fullscreenChangeHandler_) {
  36968. var changeHandler = this.fullscreenChangeHandler_;
  36969. element.removeEventListener('fullscreenchange', changeHandler, false);
  36970. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  36971. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  36972. element.removeEventListener('msfullscreenchange', changeHandler, false);
  36973. }
  36974. if (this.fullscreenErrorHandler_) {
  36975. var errorHandler = this.fullscreenErrorHandler_;
  36976. element.removeEventListener('fullscreenerror', errorHandler, false);
  36977. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  36978. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  36979. element.removeEventListener('msfullscreenerror', errorHandler, false);
  36980. }
  36981. this.fullscreenEventTarget_ = null;
  36982. this.fullscreenChangeHandler_ = null;
  36983. this.fullscreenErrorHandler_ = null;
  36984. };
  36985. VRDisplay.prototype.beginPresent_ = function() {
  36986. // Override to add custom behavior when presentation begins.
  36987. };
  36988. VRDisplay.prototype.endPresent_ = function() {
  36989. // Override to add custom behavior when presentation ends.
  36990. };
  36991. VRDisplay.prototype.submitFrame = function(pose) {
  36992. // Override to add custom behavior for frame submission.
  36993. };
  36994. VRDisplay.prototype.getEyeParameters = function(whichEye) {
  36995. // Override to return accurate eye parameters if canPresent is true.
  36996. return null;
  36997. };
  36998. /*
  36999. * Deprecated classes
  37000. */
  37001. /**
  37002. * The base class for all VR devices. (Deprecated)
  37003. */
  37004. function VRDevice() {
  37005. this.isPolyfilled = true;
  37006. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  37007. this.deviceId = 'webvr-polyfill deviceId';
  37008. this.deviceName = 'webvr-polyfill deviceName';
  37009. }
  37010. /**
  37011. * The base class for all VR HMD devices. (Deprecated)
  37012. */
  37013. function HMDVRDevice() {
  37014. }
  37015. HMDVRDevice.prototype = new VRDevice();
  37016. /**
  37017. * The base class for all VR position sensor devices. (Deprecated)
  37018. */
  37019. function PositionSensorVRDevice() {
  37020. }
  37021. PositionSensorVRDevice.prototype = new VRDevice();
  37022. module.exports.VRFrameData = VRFrameData;
  37023. module.exports.VRDisplay = VRDisplay;
  37024. module.exports.VRDevice = VRDevice;
  37025. module.exports.HMDVRDevice = HMDVRDevice;
  37026. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  37027. },{"./util.js":68,"./wakelock.js":70}],49:[function(_dereq_,module,exports){
  37028. /*
  37029. * Copyright 2016 Google Inc. All Rights Reserved.
  37030. * Licensed under the Apache License, Version 2.0 (the "License");
  37031. * you may not use this file except in compliance with the License.
  37032. * You may obtain a copy of the License at
  37033. *
  37034. * http://www.apache.org/licenses/LICENSE-2.0
  37035. *
  37036. * Unless required by applicable law or agreed to in writing, software
  37037. * distributed under the License is distributed on an "AS IS" BASIS,
  37038. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37039. * See the License for the specific language governing permissions and
  37040. * limitations under the License.
  37041. */
  37042. var CardboardUI = _dereq_('./cardboard-ui.js');
  37043. var Util = _dereq_('./util.js');
  37044. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37045. var distortionVS = [
  37046. 'attribute vec2 position;',
  37047. 'attribute vec3 texCoord;',
  37048. 'varying vec2 vTexCoord;',
  37049. 'uniform vec4 viewportOffsetScale[2];',
  37050. 'void main() {',
  37051. ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];',
  37052. ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;',
  37053. ' gl_Position = vec4( position, 1.0, 1.0 );',
  37054. '}',
  37055. ].join('\n');
  37056. var distortionFS = [
  37057. 'precision mediump float;',
  37058. 'uniform sampler2D diffuse;',
  37059. 'varying vec2 vTexCoord;',
  37060. 'void main() {',
  37061. ' gl_FragColor = texture2D(diffuse, vTexCoord);',
  37062. '}',
  37063. ].join('\n');
  37064. /**
  37065. * A mesh-based distorter.
  37066. */
  37067. function CardboardDistorter(gl) {
  37068. this.gl = gl;
  37069. this.ctxAttribs = gl.getContextAttributes();
  37070. this.meshWidth = 20;
  37071. this.meshHeight = 20;
  37072. this.bufferScale = window.WebVRConfig.BUFFER_SCALE;
  37073. this.bufferWidth = gl.drawingBufferWidth;
  37074. this.bufferHeight = gl.drawingBufferHeight;
  37075. // Patching support
  37076. this.realBindFramebuffer = gl.bindFramebuffer;
  37077. this.realEnable = gl.enable;
  37078. this.realDisable = gl.disable;
  37079. this.realColorMask = gl.colorMask;
  37080. this.realClearColor = gl.clearColor;
  37081. this.realViewport = gl.viewport;
  37082. if (!Util.isIOS()) {
  37083. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  37084. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  37085. }
  37086. this.isPatched = false;
  37087. // State tracking
  37088. this.lastBoundFramebuffer = null;
  37089. this.cullFace = false;
  37090. this.depthTest = false;
  37091. this.blend = false;
  37092. this.scissorTest = false;
  37093. this.stencilTest = false;
  37094. this.viewport = [0, 0, 0, 0];
  37095. this.colorMask = [true, true, true, true];
  37096. this.clearColor = [0, 0, 0, 0];
  37097. this.attribs = {
  37098. position: 0,
  37099. texCoord: 1
  37100. };
  37101. this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs);
  37102. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37103. this.viewportOffsetScale = new Float32Array(8);
  37104. this.setTextureBounds();
  37105. this.vertexBuffer = gl.createBuffer();
  37106. this.indexBuffer = gl.createBuffer();
  37107. this.indexCount = 0;
  37108. this.renderTarget = gl.createTexture();
  37109. this.framebuffer = gl.createFramebuffer();
  37110. this.depthStencilBuffer = null;
  37111. this.depthBuffer = null;
  37112. this.stencilBuffer = null;
  37113. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  37114. this.depthStencilBuffer = gl.createRenderbuffer();
  37115. } else if (this.ctxAttribs.depth) {
  37116. this.depthBuffer = gl.createRenderbuffer();
  37117. } else if (this.ctxAttribs.stencil) {
  37118. this.stencilBuffer = gl.createRenderbuffer();
  37119. }
  37120. this.patch();
  37121. this.onResize();
  37122. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  37123. this.cardboardUI = new CardboardUI(gl);
  37124. }
  37125. };
  37126. /**
  37127. * Tears down all the resources created by the distorter and removes any
  37128. * patches.
  37129. */
  37130. CardboardDistorter.prototype.destroy = function() {
  37131. var gl = this.gl;
  37132. this.unpatch();
  37133. gl.deleteProgram(this.program);
  37134. gl.deleteBuffer(this.vertexBuffer);
  37135. gl.deleteBuffer(this.indexBuffer);
  37136. gl.deleteTexture(this.renderTarget);
  37137. gl.deleteFramebuffer(this.framebuffer);
  37138. if (this.depthStencilBuffer) {
  37139. gl.deleteRenderbuffer(this.depthStencilBuffer);
  37140. }
  37141. if (this.depthBuffer) {
  37142. gl.deleteRenderbuffer(this.depthBuffer);
  37143. }
  37144. if (this.stencilBuffer) {
  37145. gl.deleteRenderbuffer(this.stencilBuffer);
  37146. }
  37147. if (this.cardboardUI) {
  37148. this.cardboardUI.destroy();
  37149. }
  37150. };
  37151. /**
  37152. * Resizes the backbuffer to match the canvas width and height.
  37153. */
  37154. CardboardDistorter.prototype.onResize = function() {
  37155. var gl = this.gl;
  37156. var self = this;
  37157. var glState = [
  37158. gl.RENDERBUFFER_BINDING,
  37159. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37160. ];
  37161. WGLUPreserveGLState(gl, glState, function(gl) {
  37162. // Bind real backbuffer and clear it once. We don't need to clear it again
  37163. // after that because we're overwriting the same area every frame.
  37164. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37165. // Put things in a good state
  37166. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37167. self.realColorMask.call(gl, true, true, true, true);
  37168. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37169. self.realClearColor.call(gl, 0, 0, 0, 1);
  37170. gl.clear(gl.COLOR_BUFFER_BIT);
  37171. // Now bind and resize the fake backbuffer
  37172. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  37173. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37174. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB,
  37175. self.bufferWidth, self.bufferHeight, 0,
  37176. self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  37177. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  37178. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  37179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  37180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  37181. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  37182. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  37183. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  37184. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL,
  37185. self.bufferWidth, self.bufferHeight);
  37186. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT,
  37187. gl.RENDERBUFFER, self.depthStencilBuffer);
  37188. } else if (self.ctxAttribs.depth) {
  37189. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  37190. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
  37191. self.bufferWidth, self.bufferHeight);
  37192. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  37193. gl.RENDERBUFFER, self.depthBuffer);
  37194. } else if (self.ctxAttribs.stencil) {
  37195. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  37196. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8,
  37197. self.bufferWidth, self.bufferHeight);
  37198. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT,
  37199. gl.RENDERBUFFER, self.stencilBuffer);
  37200. }
  37201. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  37202. console.error('Framebuffer incomplete!');
  37203. }
  37204. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37205. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37206. self.realColorMask.apply(gl, self.colorMask);
  37207. self.realViewport.apply(gl, self.viewport);
  37208. self.realClearColor.apply(gl, self.clearColor);
  37209. });
  37210. if (this.cardboardUI) {
  37211. this.cardboardUI.onResize();
  37212. }
  37213. };
  37214. CardboardDistorter.prototype.patch = function() {
  37215. if (this.isPatched) {
  37216. return;
  37217. }
  37218. var self = this;
  37219. var canvas = this.gl.canvas;
  37220. var gl = this.gl;
  37221. if (!Util.isIOS()) {
  37222. canvas.width = Util.getScreenWidth() * this.bufferScale;
  37223. canvas.height = Util.getScreenHeight() * this.bufferScale;
  37224. Object.defineProperty(canvas, 'width', {
  37225. configurable: true,
  37226. enumerable: true,
  37227. get: function() {
  37228. return self.bufferWidth;
  37229. },
  37230. set: function(value) {
  37231. self.bufferWidth = value;
  37232. self.realCanvasWidth.set.call(canvas, value);
  37233. self.onResize();
  37234. }
  37235. });
  37236. Object.defineProperty(canvas, 'height', {
  37237. configurable: true,
  37238. enumerable: true,
  37239. get: function() {
  37240. return self.bufferHeight;
  37241. },
  37242. set: function(value) {
  37243. self.bufferHeight = value;
  37244. self.realCanvasHeight.set.call(canvas, value);
  37245. self.onResize();
  37246. }
  37247. });
  37248. }
  37249. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  37250. if (this.lastBoundFramebuffer == null) {
  37251. this.lastBoundFramebuffer = this.framebuffer;
  37252. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  37253. }
  37254. this.gl.bindFramebuffer = function(target, framebuffer) {
  37255. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  37256. // Silently make calls to bind the default framebuffer bind ours instead.
  37257. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  37258. };
  37259. this.cullFace = gl.getParameter(gl.CULL_FACE);
  37260. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  37261. this.blend = gl.getParameter(gl.BLEND);
  37262. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  37263. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  37264. gl.enable = function(pname) {
  37265. switch (pname) {
  37266. case gl.CULL_FACE: self.cullFace = true; break;
  37267. case gl.DEPTH_TEST: self.depthTest = true; break;
  37268. case gl.BLEND: self.blend = true; break;
  37269. case gl.SCISSOR_TEST: self.scissorTest = true; break;
  37270. case gl.STENCIL_TEST: self.stencilTest = true; break;
  37271. }
  37272. self.realEnable.call(gl, pname);
  37273. };
  37274. gl.disable = function(pname) {
  37275. switch (pname) {
  37276. case gl.CULL_FACE: self.cullFace = false; break;
  37277. case gl.DEPTH_TEST: self.depthTest = false; break;
  37278. case gl.BLEND: self.blend = false; break;
  37279. case gl.SCISSOR_TEST: self.scissorTest = false; break;
  37280. case gl.STENCIL_TEST: self.stencilTest = false; break;
  37281. }
  37282. self.realDisable.call(gl, pname);
  37283. };
  37284. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  37285. gl.colorMask = function(r, g, b, a) {
  37286. self.colorMask[0] = r;
  37287. self.colorMask[1] = g;
  37288. self.colorMask[2] = b;
  37289. self.colorMask[3] = a;
  37290. self.realColorMask.call(gl, r, g, b, a);
  37291. };
  37292. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  37293. gl.clearColor = function(r, g, b, a) {
  37294. self.clearColor[0] = r;
  37295. self.clearColor[1] = g;
  37296. self.clearColor[2] = b;
  37297. self.clearColor[3] = a;
  37298. self.realClearColor.call(gl, r, g, b, a);
  37299. };
  37300. this.viewport = gl.getParameter(gl.VIEWPORT);
  37301. gl.viewport = function(x, y, w, h) {
  37302. self.viewport[0] = x;
  37303. self.viewport[1] = y;
  37304. self.viewport[2] = w;
  37305. self.viewport[3] = h;
  37306. self.realViewport.call(gl, x, y, w, h);
  37307. };
  37308. this.isPatched = true;
  37309. Util.safariCssSizeWorkaround(canvas);
  37310. };
  37311. CardboardDistorter.prototype.unpatch = function() {
  37312. if (!this.isPatched) {
  37313. return;
  37314. }
  37315. var gl = this.gl;
  37316. var canvas = this.gl.canvas;
  37317. if (!Util.isIOS()) {
  37318. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  37319. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  37320. }
  37321. canvas.width = this.bufferWidth;
  37322. canvas.height = this.bufferHeight;
  37323. gl.bindFramebuffer = this.realBindFramebuffer;
  37324. gl.enable = this.realEnable;
  37325. gl.disable = this.realDisable;
  37326. gl.colorMask = this.realColorMask;
  37327. gl.clearColor = this.realClearColor;
  37328. gl.viewport = this.realViewport;
  37329. // Check to see if our fake backbuffer is bound and bind the real backbuffer
  37330. // if that's the case.
  37331. if (this.lastBoundFramebuffer == this.framebuffer) {
  37332. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  37333. }
  37334. this.isPatched = false;
  37335. setTimeout(function() {
  37336. Util.safariCssSizeWorkaround(canvas);
  37337. }, 1);
  37338. };
  37339. CardboardDistorter.prototype.setTextureBounds = function(leftBounds, rightBounds) {
  37340. if (!leftBounds) {
  37341. leftBounds = [0, 0, 0.5, 1];
  37342. }
  37343. if (!rightBounds) {
  37344. rightBounds = [0.5, 0, 0.5, 1];
  37345. }
  37346. // Left eye
  37347. this.viewportOffsetScale[0] = leftBounds[0]; // X
  37348. this.viewportOffsetScale[1] = leftBounds[1]; // Y
  37349. this.viewportOffsetScale[2] = leftBounds[2]; // Width
  37350. this.viewportOffsetScale[3] = leftBounds[3]; // Height
  37351. // Right eye
  37352. this.viewportOffsetScale[4] = rightBounds[0]; // X
  37353. this.viewportOffsetScale[5] = rightBounds[1]; // Y
  37354. this.viewportOffsetScale[6] = rightBounds[2]; // Width
  37355. this.viewportOffsetScale[7] = rightBounds[3]; // Height
  37356. };
  37357. /**
  37358. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37359. * backbuffer.
  37360. */
  37361. CardboardDistorter.prototype.submitFrame = function() {
  37362. var gl = this.gl;
  37363. var self = this;
  37364. var glState = [];
  37365. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37366. glState.push(
  37367. gl.CURRENT_PROGRAM,
  37368. gl.ARRAY_BUFFER_BINDING,
  37369. gl.ELEMENT_ARRAY_BUFFER_BINDING,
  37370. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37371. );
  37372. }
  37373. WGLUPreserveGLState(gl, glState, function(gl) {
  37374. // Bind the real default framebuffer
  37375. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37376. // Make sure the GL state is in a good place
  37377. if (self.cullFace) { self.realDisable.call(gl, gl.CULL_FACE); }
  37378. if (self.depthTest) { self.realDisable.call(gl, gl.DEPTH_TEST); }
  37379. if (self.blend) { self.realDisable.call(gl, gl.BLEND); }
  37380. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37381. if (self.stencilTest) { self.realDisable.call(gl, gl.STENCIL_TEST); }
  37382. self.realColorMask.call(gl, true, true, true, true);
  37383. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37384. // If the backbuffer has an alpha channel clear every frame so the page
  37385. // doesn't show through.
  37386. if (self.ctxAttribs.alpha || Util.isIOS()) {
  37387. self.realClearColor.call(gl, 0, 0, 0, 1);
  37388. gl.clear(gl.COLOR_BUFFER_BIT);
  37389. }
  37390. // Bind distortion program and mesh
  37391. gl.useProgram(self.program);
  37392. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37393. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37394. gl.enableVertexAttribArray(self.attribs.position);
  37395. gl.enableVertexAttribArray(self.attribs.texCoord);
  37396. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  37397. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  37398. gl.activeTexture(gl.TEXTURE0);
  37399. gl.uniform1i(self.uniforms.diffuse, 0);
  37400. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37401. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  37402. // Draws both eyes
  37403. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  37404. if (self.cardboardUI) {
  37405. self.cardboardUI.renderNoState();
  37406. }
  37407. // Bind the fake default framebuffer again
  37408. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  37409. // If preserveDrawingBuffer == false clear the framebuffer
  37410. if (!self.ctxAttribs.preserveDrawingBuffer) {
  37411. self.realClearColor.call(gl, 0, 0, 0, 0);
  37412. gl.clear(gl.COLOR_BUFFER_BIT);
  37413. }
  37414. if (!window.WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37415. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37416. }
  37417. // Restore state
  37418. if (self.cullFace) { self.realEnable.call(gl, gl.CULL_FACE); }
  37419. if (self.depthTest) { self.realEnable.call(gl, gl.DEPTH_TEST); }
  37420. if (self.blend) { self.realEnable.call(gl, gl.BLEND); }
  37421. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37422. if (self.stencilTest) { self.realEnable.call(gl, gl.STENCIL_TEST); }
  37423. self.realColorMask.apply(gl, self.colorMask);
  37424. self.realViewport.apply(gl, self.viewport);
  37425. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  37426. self.realClearColor.apply(gl, self.clearColor);
  37427. }
  37428. });
  37429. // Workaround for the fact that Safari doesn't allow us to patch the canvas
  37430. // width and height correctly. After each submit frame check to see what the
  37431. // real backbuffer size has been set to and resize the fake backbuffer size
  37432. // to match.
  37433. if (Util.isIOS()) {
  37434. var canvas = gl.canvas;
  37435. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  37436. self.bufferWidth = canvas.width;
  37437. self.bufferHeight = canvas.height;
  37438. self.onResize();
  37439. }
  37440. }
  37441. };
  37442. /**
  37443. * Call when the deviceInfo has changed. At this point we need
  37444. * to re-calculate the distortion mesh.
  37445. */
  37446. CardboardDistorter.prototype.updateDeviceInfo = function(deviceInfo) {
  37447. var gl = this.gl;
  37448. var self = this;
  37449. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  37450. WGLUPreserveGLState(gl, glState, function(gl) {
  37451. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  37452. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37453. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  37454. // Indices don't change based on device parameters, so only compute once.
  37455. if (!self.indexCount) {
  37456. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  37457. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37458. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  37459. self.indexCount = indices.length;
  37460. }
  37461. });
  37462. };
  37463. /**
  37464. * Build the distortion mesh vertices.
  37465. * Based on code from the Unity cardboard plugin.
  37466. */
  37467. CardboardDistorter.prototype.computeMeshVertices_ = function(width, height, deviceInfo) {
  37468. var vertices = new Float32Array(2 * width * height * 5);
  37469. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  37470. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  37471. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  37472. var vidx = 0;
  37473. var iidx = 0;
  37474. for (var e = 0; e < 2; e++) {
  37475. for (var j = 0; j < height; j++) {
  37476. for (var i = 0; i < width; i++, vidx++) {
  37477. var u = i / (width - 1);
  37478. var v = j / (height - 1);
  37479. // Grid points regularly spaced in StreoScreen, and barrel distorted in
  37480. // the mesh.
  37481. var s = u;
  37482. var t = v;
  37483. var x = Util.lerp(lensFrustum[0], lensFrustum[2], u);
  37484. var y = Util.lerp(lensFrustum[3], lensFrustum[1], v);
  37485. var d = Math.sqrt(x * x + y * y);
  37486. var r = deviceInfo.distortion.distortInverse(d);
  37487. var p = x * r / d;
  37488. var q = y * r / d;
  37489. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  37490. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  37491. // Convert u,v to mesh screen coordinates.
  37492. var aspect = deviceInfo.device.widthMeters / deviceInfo.device.heightMeters;
  37493. // FIXME: The original Unity plugin multiplied U by the aspect ratio
  37494. // and didn't multiply either value by 2, but that seems to get it
  37495. // really close to correct looking for me. I hate this kind of "Don't
  37496. // know why it works" code though, and wold love a more logical
  37497. // explanation of what needs to happen here.
  37498. u = (viewport.x + u * viewport.width - 0.5) * 2.0; //* aspect;
  37499. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  37500. vertices[(vidx * 5) + 0] = u; // position.x
  37501. vertices[(vidx * 5) + 1] = v; // position.y
  37502. vertices[(vidx * 5) + 2] = s; // texCoord.x
  37503. vertices[(vidx * 5) + 3] = t; // texCoord.y
  37504. vertices[(vidx * 5) + 4] = e; // texCoord.z (viewport index)
  37505. }
  37506. }
  37507. var w = lensFrustum[2] - lensFrustum[0];
  37508. lensFrustum[0] = -(w + lensFrustum[0]);
  37509. lensFrustum[2] = w - lensFrustum[2];
  37510. w = noLensFrustum[2] - noLensFrustum[0];
  37511. noLensFrustum[0] = -(w + noLensFrustum[0]);
  37512. noLensFrustum[2] = w - noLensFrustum[2];
  37513. viewport.x = 1 - (viewport.x + viewport.width);
  37514. }
  37515. return vertices;
  37516. }
  37517. /**
  37518. * Build the distortion mesh indices.
  37519. * Based on code from the Unity cardboard plugin.
  37520. */
  37521. CardboardDistorter.prototype.computeMeshIndices_ = function(width, height) {
  37522. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  37523. var halfwidth = width / 2;
  37524. var halfheight = height / 2;
  37525. var vidx = 0;
  37526. var iidx = 0;
  37527. for (var e = 0; e < 2; e++) {
  37528. for (var j = 0; j < height; j++) {
  37529. for (var i = 0; i < width; i++, vidx++) {
  37530. if (i == 0 || j == 0)
  37531. continue;
  37532. // Build a quad. Lower right and upper left quadrants have quads with
  37533. // the triangle diagonal flipped to get the vignette to interpolate
  37534. // correctly.
  37535. if ((i <= halfwidth) == (j <= halfheight)) {
  37536. // Quad diagonal lower left to upper right.
  37537. indices[iidx++] = vidx;
  37538. indices[iidx++] = vidx - width - 1;
  37539. indices[iidx++] = vidx - width;
  37540. indices[iidx++] = vidx - width - 1;
  37541. indices[iidx++] = vidx;
  37542. indices[iidx++] = vidx - 1;
  37543. } else {
  37544. // Quad diagonal upper left to lower right.
  37545. indices[iidx++] = vidx - 1;
  37546. indices[iidx++] = vidx - width;
  37547. indices[iidx++] = vidx;
  37548. indices[iidx++] = vidx - width;
  37549. indices[iidx++] = vidx - 1;
  37550. indices[iidx++] = vidx - width - 1;
  37551. }
  37552. }
  37553. }
  37554. }
  37555. return indices;
  37556. };
  37557. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function(proto, attrName) {
  37558. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  37559. // In some cases (ahem... Safari), the descriptor returns undefined get and
  37560. // set fields. In this case, we need to create a synthetic property
  37561. // descriptor. This works around some of the issues in
  37562. // https://github.com/borismus/webvr-polyfill/issues/46
  37563. if (descriptor.get === undefined || descriptor.set === undefined) {
  37564. descriptor.configurable = true;
  37565. descriptor.enumerable = true;
  37566. descriptor.get = function() {
  37567. return this.getAttribute(attrName);
  37568. };
  37569. descriptor.set = function(val) {
  37570. this.setAttribute(attrName, val);
  37571. };
  37572. }
  37573. return descriptor;
  37574. };
  37575. module.exports = CardboardDistorter;
  37576. },{"./cardboard-ui.js":50,"./deps/wglu-preserve-state.js":52,"./util.js":68}],50:[function(_dereq_,module,exports){
  37577. /*
  37578. * Copyright 2016 Google Inc. All Rights Reserved.
  37579. * Licensed under the Apache License, Version 2.0 (the "License");
  37580. * you may not use this file except in compliance with the License.
  37581. * You may obtain a copy of the License at
  37582. *
  37583. * http://www.apache.org/licenses/LICENSE-2.0
  37584. *
  37585. * Unless required by applicable law or agreed to in writing, software
  37586. * distributed under the License is distributed on an "AS IS" BASIS,
  37587. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37588. * See the License for the specific language governing permissions and
  37589. * limitations under the License.
  37590. */
  37591. var Util = _dereq_('./util.js');
  37592. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37593. var uiVS = [
  37594. 'attribute vec2 position;',
  37595. 'uniform mat4 projectionMat;',
  37596. 'void main() {',
  37597. ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );',
  37598. '}',
  37599. ].join('\n');
  37600. var uiFS = [
  37601. 'precision mediump float;',
  37602. 'uniform vec4 color;',
  37603. 'void main() {',
  37604. ' gl_FragColor = color;',
  37605. '}',
  37606. ].join('\n');
  37607. var DEG2RAD = Math.PI/180.0;
  37608. // The gear has 6 identical sections, each spanning 60 degrees.
  37609. var kAnglePerGearSection = 60;
  37610. // Half-angle of the span of the outer rim.
  37611. var kOuterRimEndAngle = 12;
  37612. // Angle between the middle of the outer rim and the start of the inner rim.
  37613. var kInnerRimBeginAngle = 20;
  37614. // Distance from center to outer rim, normalized so that the entire model
  37615. // fits in a [-1, 1] x [-1, 1] square.
  37616. var kOuterRadius = 1;
  37617. // Distance from center to depressed rim, in model units.
  37618. var kMiddleRadius = 0.75;
  37619. // Radius of the inner hollow circle, in model units.
  37620. var kInnerRadius = 0.3125;
  37621. // Center line thickness in DP.
  37622. var kCenterLineThicknessDp = 4;
  37623. // Button width in DP.
  37624. var kButtonWidthDp = 28;
  37625. // Factor to scale the touch area that responds to the touch.
  37626. var kTouchSlopFactor = 1.5;
  37627. var Angles = [
  37628. 0, kOuterRimEndAngle, kInnerRimBeginAngle,
  37629. kAnglePerGearSection - kInnerRimBeginAngle,
  37630. kAnglePerGearSection - kOuterRimEndAngle
  37631. ];
  37632. /**
  37633. * Renders the alignment line and "options" gear. It is assumed that the canvas
  37634. * this is rendered into covers the entire screen (or close to it.)
  37635. */
  37636. function CardboardUI(gl) {
  37637. this.gl = gl;
  37638. this.attribs = {
  37639. position: 0
  37640. };
  37641. this.program = Util.linkProgram(gl, uiVS, uiFS, this.attribs);
  37642. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37643. this.vertexBuffer = gl.createBuffer();
  37644. this.gearOffset = 0;
  37645. this.gearVertexCount = 0;
  37646. this.arrowOffset = 0;
  37647. this.arrowVertexCount = 0;
  37648. this.projMat = new Float32Array(16);
  37649. this.listener = null;
  37650. this.onResize();
  37651. };
  37652. /**
  37653. * Tears down all the resources created by the UI renderer.
  37654. */
  37655. CardboardUI.prototype.destroy = function() {
  37656. var gl = this.gl;
  37657. if (this.listener) {
  37658. gl.canvas.removeEventListener('click', this.listener, false);
  37659. }
  37660. gl.deleteProgram(this.program);
  37661. gl.deleteBuffer(this.vertexBuffer);
  37662. };
  37663. /**
  37664. * Adds a listener to clicks on the gear and back icons
  37665. */
  37666. CardboardUI.prototype.listen = function(optionsCallback, backCallback) {
  37667. var canvas = this.gl.canvas;
  37668. this.listener = function(event) {
  37669. var midline = canvas.clientWidth / 2;
  37670. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  37671. // Check to see if the user clicked on (or around) the gear icon
  37672. if (event.clientX > midline - buttonSize &&
  37673. event.clientX < midline + buttonSize &&
  37674. event.clientY > canvas.clientHeight - buttonSize) {
  37675. optionsCallback(event);
  37676. }
  37677. // Check to see if the user clicked on (or around) the back icon
  37678. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  37679. backCallback(event);
  37680. }
  37681. };
  37682. canvas.addEventListener('click', this.listener, false);
  37683. };
  37684. /**
  37685. * Builds the UI mesh.
  37686. */
  37687. CardboardUI.prototype.onResize = function() {
  37688. var gl = this.gl;
  37689. var self = this;
  37690. var glState = [
  37691. gl.ARRAY_BUFFER_BINDING
  37692. ];
  37693. WGLUPreserveGLState(gl, glState, function(gl) {
  37694. var vertices = [];
  37695. var midline = gl.drawingBufferWidth / 2;
  37696. // The gl buffer size will likely be smaller than the physical pixel count.
  37697. // So we need to scale the dps down based on the actual buffer size vs physical pixel count.
  37698. // This will properly size the ui elements no matter what the gl buffer resolution is
  37699. var physicalPixels = Math.max(screen.width, screen.height) * window.devicePixelRatio;
  37700. var scalingRatio = gl.drawingBufferWidth / physicalPixels;
  37701. var dps = scalingRatio * window.devicePixelRatio;
  37702. var lineWidth = kCenterLineThicknessDp * dps / 2;
  37703. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  37704. var buttonScale = kButtonWidthDp * dps / 2;
  37705. var buttonBorder = ((kButtonWidthDp * kTouchSlopFactor) - kButtonWidthDp) * dps;
  37706. // Build centerline
  37707. vertices.push(midline - lineWidth, buttonSize);
  37708. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  37709. vertices.push(midline + lineWidth, buttonSize);
  37710. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  37711. // Build gear
  37712. self.gearOffset = (vertices.length / 2);
  37713. function addGearSegment(theta, r) {
  37714. var angle = (90 - theta) * DEG2RAD;
  37715. var x = Math.cos(angle);
  37716. var y = Math.sin(angle);
  37717. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  37718. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  37719. }
  37720. for (var i = 0; i <= 6; i++) {
  37721. var segmentTheta = i * kAnglePerGearSection;
  37722. addGearSegment(segmentTheta, kOuterRadius);
  37723. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  37724. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  37725. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  37726. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  37727. }
  37728. self.gearVertexCount = (vertices.length / 2) - self.gearOffset;
  37729. // Build back arrow
  37730. self.arrowOffset = (vertices.length / 2);
  37731. function addArrowVertex(x, y) {
  37732. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  37733. }
  37734. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  37735. addArrowVertex(0, buttonScale);
  37736. addArrowVertex(buttonScale, 0);
  37737. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  37738. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  37739. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37740. addArrowVertex(0, buttonScale);
  37741. addArrowVertex(buttonScale, buttonScale * 2);
  37742. addArrowVertex(buttonScale + angledLineWidth, (buttonScale * 2) - angledLineWidth);
  37743. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37744. addArrowVertex(0, buttonScale);
  37745. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  37746. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  37747. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  37748. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  37749. self.arrowVertexCount = (vertices.length / 2) - self.arrowOffset;
  37750. // Buffer data
  37751. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37752. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  37753. });
  37754. };
  37755. /**
  37756. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37757. * backbuffer.
  37758. */
  37759. CardboardUI.prototype.render = function() {
  37760. var gl = this.gl;
  37761. var self = this;
  37762. var glState = [
  37763. gl.CULL_FACE,
  37764. gl.DEPTH_TEST,
  37765. gl.BLEND,
  37766. gl.SCISSOR_TEST,
  37767. gl.STENCIL_TEST,
  37768. gl.COLOR_WRITEMASK,
  37769. gl.VIEWPORT,
  37770. gl.CURRENT_PROGRAM,
  37771. gl.ARRAY_BUFFER_BINDING
  37772. ];
  37773. WGLUPreserveGLState(gl, glState, function(gl) {
  37774. // Make sure the GL state is in a good place
  37775. gl.disable(gl.CULL_FACE);
  37776. gl.disable(gl.DEPTH_TEST);
  37777. gl.disable(gl.BLEND);
  37778. gl.disable(gl.SCISSOR_TEST);
  37779. gl.disable(gl.STENCIL_TEST);
  37780. gl.colorMask(true, true, true, true);
  37781. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37782. self.renderNoState();
  37783. });
  37784. };
  37785. CardboardUI.prototype.renderNoState = function() {
  37786. var gl = this.gl;
  37787. // Bind distortion program and mesh
  37788. gl.useProgram(this.program);
  37789. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37790. gl.enableVertexAttribArray(this.attribs.position);
  37791. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  37792. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  37793. Util.orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  37794. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  37795. // Draws UI element
  37796. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  37797. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  37798. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  37799. };
  37800. module.exports = CardboardUI;
  37801. },{"./deps/wglu-preserve-state.js":52,"./util.js":68}],51:[function(_dereq_,module,exports){
  37802. /*
  37803. * Copyright 2016 Google Inc. All Rights Reserved.
  37804. * Licensed under the Apache License, Version 2.0 (the "License");
  37805. * you may not use this file except in compliance with the License.
  37806. * You may obtain a copy of the License at
  37807. *
  37808. * http://www.apache.org/licenses/LICENSE-2.0
  37809. *
  37810. * Unless required by applicable law or agreed to in writing, software
  37811. * distributed under the License is distributed on an "AS IS" BASIS,
  37812. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37813. * See the License for the specific language governing permissions and
  37814. * limitations under the License.
  37815. */
  37816. var CardboardDistorter = _dereq_('./cardboard-distorter.js');
  37817. var CardboardUI = _dereq_('./cardboard-ui.js');
  37818. var DeviceInfo = _dereq_('./device-info.js');
  37819. var Dpdb = _dereq_('./dpdb/dpdb.js');
  37820. var FusionPoseSensor = _dereq_('./sensor-fusion/fusion-pose-sensor.js');
  37821. var RotateInstructions = _dereq_('./rotate-instructions.js');
  37822. var ViewerSelector = _dereq_('./viewer-selector.js');
  37823. var VRDisplay = _dereq_('./base.js').VRDisplay;
  37824. var Util = _dereq_('./util.js');
  37825. var Eye = {
  37826. LEFT: 'left',
  37827. RIGHT: 'right'
  37828. };
  37829. /**
  37830. * VRDisplay based on mobile device parameters and DeviceMotion APIs.
  37831. */
  37832. function CardboardVRDisplay() {
  37833. this.displayName = 'Cardboard VRDisplay (webvr-polyfill)';
  37834. this.capabilities.hasOrientation = true;
  37835. this.capabilities.canPresent = true;
  37836. // "Private" members.
  37837. this.bufferScale_ = window.WebVRConfig.BUFFER_SCALE;
  37838. this.poseSensor_ = new FusionPoseSensor();
  37839. this.distorter_ = null;
  37840. this.cardboardUI_ = null;
  37841. this.dpdb_ = new Dpdb(true, this.onDeviceParamsUpdated_.bind(this));
  37842. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  37843. this.viewerSelector_ = new ViewerSelector();
  37844. this.viewerSelector_.onChange(this.onViewerChanged_.bind(this));
  37845. // Set the correct initial viewer.
  37846. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  37847. if (!window.WebVRConfig.ROTATE_INSTRUCTIONS_DISABLED) {
  37848. this.rotateInstructions_ = new RotateInstructions();
  37849. }
  37850. if (Util.isIOS()) {
  37851. // Listen for resize events to workaround this awful Safari bug.
  37852. window.addEventListener('resize', this.onResize_.bind(this));
  37853. }
  37854. }
  37855. CardboardVRDisplay.prototype = new VRDisplay();
  37856. CardboardVRDisplay.prototype.getImmediatePose = function() {
  37857. return {
  37858. position: this.poseSensor_.getPosition(),
  37859. orientation: this.poseSensor_.getOrientation(),
  37860. linearVelocity: null,
  37861. linearAcceleration: null,
  37862. angularVelocity: null,
  37863. angularAcceleration: null
  37864. };
  37865. };
  37866. CardboardVRDisplay.prototype.resetPose = function() {
  37867. this.poseSensor_.resetPose();
  37868. };
  37869. CardboardVRDisplay.prototype.getEyeParameters = function(whichEye) {
  37870. var offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  37871. var fieldOfView;
  37872. // TODO: FoV can be a little expensive to compute. Cache when device params change.
  37873. if (whichEye == Eye.LEFT) {
  37874. offset[0] *= -1.0;
  37875. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  37876. } else if (whichEye == Eye.RIGHT) {
  37877. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  37878. } else {
  37879. console.error('Invalid eye provided: %s', whichEye);
  37880. return null;
  37881. }
  37882. return {
  37883. fieldOfView: fieldOfView,
  37884. offset: offset,
  37885. // TODO: Should be able to provide better values than these.
  37886. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  37887. renderHeight: this.deviceInfo_.device.height * this.bufferScale_,
  37888. };
  37889. };
  37890. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function(newParams) {
  37891. if (Util.isDebug()) {
  37892. console.log('DPDB reported that device params were updated.');
  37893. }
  37894. this.deviceInfo_.updateDeviceParams(newParams);
  37895. if (this.distorter_) {
  37896. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37897. }
  37898. };
  37899. CardboardVRDisplay.prototype.updateBounds_ = function () {
  37900. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  37901. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  37902. }
  37903. };
  37904. CardboardVRDisplay.prototype.beginPresent_ = function() {
  37905. var gl = this.layer_.source.getContext('webgl');
  37906. if (!gl)
  37907. gl = this.layer_.source.getContext('experimental-webgl');
  37908. if (!gl)
  37909. gl = this.layer_.source.getContext('webgl2');
  37910. if (!gl)
  37911. return; // Can't do distortion without a WebGL context.
  37912. // Provides a way to opt out of distortion
  37913. if (this.layer_.predistorted) {
  37914. if (!window.WebVRConfig.CARDBOARD_UI_DISABLED) {
  37915. gl.canvas.width = Util.getScreenWidth() * this.bufferScale_;
  37916. gl.canvas.height = Util.getScreenHeight() * this.bufferScale_;
  37917. this.cardboardUI_ = new CardboardUI(gl);
  37918. }
  37919. } else {
  37920. // Create a new distorter for the target context
  37921. this.distorter_ = new CardboardDistorter(gl);
  37922. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37923. this.cardboardUI_ = this.distorter_.cardboardUI;
  37924. }
  37925. if (this.cardboardUI_) {
  37926. this.cardboardUI_.listen(function(e) {
  37927. // Options clicked.
  37928. this.viewerSelector_.show(this.layer_.source.parentElement);
  37929. e.stopPropagation();
  37930. e.preventDefault();
  37931. }.bind(this), function(e) {
  37932. // Back clicked.
  37933. this.exitPresent();
  37934. e.stopPropagation();
  37935. e.preventDefault();
  37936. }.bind(this));
  37937. }
  37938. if (this.rotateInstructions_) {
  37939. if (Util.isLandscapeMode() && Util.isMobile()) {
  37940. // In landscape mode, temporarily show the "put into Cardboard"
  37941. // interstitial. Otherwise, do the default thing.
  37942. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  37943. } else {
  37944. this.rotateInstructions_.update();
  37945. }
  37946. }
  37947. // Listen for orientation change events in order to show interstitial.
  37948. this.orientationHandler = this.onOrientationChange_.bind(this);
  37949. window.addEventListener('orientationchange', this.orientationHandler);
  37950. // Listen for present display change events in order to update distorter dimensions
  37951. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  37952. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37953. // Fire this event initially, to give geometry-distortion clients the chance
  37954. // to do something custom.
  37955. this.fireVRDisplayDeviceParamsChange_();
  37956. };
  37957. CardboardVRDisplay.prototype.endPresent_ = function() {
  37958. if (this.distorter_) {
  37959. this.distorter_.destroy();
  37960. this.distorter_ = null;
  37961. }
  37962. if (this.cardboardUI_) {
  37963. this.cardboardUI_.destroy();
  37964. this.cardboardUI_ = null;
  37965. }
  37966. if (this.rotateInstructions_) {
  37967. this.rotateInstructions_.hide();
  37968. }
  37969. this.viewerSelector_.hide();
  37970. window.removeEventListener('orientationchange', this.orientationHandler);
  37971. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37972. };
  37973. CardboardVRDisplay.prototype.submitFrame = function(pose) {
  37974. if (this.distorter_) {
  37975. this.updateBounds_();
  37976. this.distorter_.submitFrame();
  37977. } else if (this.cardboardUI_ && this.layer_) {
  37978. // Hack for predistorted: true.
  37979. var canvas = this.layer_.source.getContext('webgl').canvas;
  37980. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  37981. this.cardboardUI_.onResize();
  37982. }
  37983. this.lastWidth = canvas.width;
  37984. this.lastHeight = canvas.height;
  37985. // Render the Cardboard UI.
  37986. this.cardboardUI_.render();
  37987. }
  37988. };
  37989. CardboardVRDisplay.prototype.onOrientationChange_ = function(e) {
  37990. // Hide the viewer selector.
  37991. this.viewerSelector_.hide();
  37992. // Update the rotate instructions.
  37993. if (this.rotateInstructions_) {
  37994. this.rotateInstructions_.update();
  37995. }
  37996. this.onResize_();
  37997. };
  37998. CardboardVRDisplay.prototype.onResize_ = function(e) {
  37999. if (this.layer_) {
  38000. var gl = this.layer_.source.getContext('webgl');
  38001. // Size the CSS canvas.
  38002. // Added padding on right and bottom because iPhone 5 will not
  38003. // hide the URL bar unless content is bigger than the screen.
  38004. // This will not be visible as long as the container element (e.g. body)
  38005. // is set to 'overflow: hidden'.
  38006. // Additionally, 'box-sizing: content-box' ensures renderWidth = width + padding.
  38007. // This is required when 'box-sizing: border-box' is used elsewhere in the page.
  38008. var cssProperties = [
  38009. 'position: absolute',
  38010. 'top: 0',
  38011. 'left: 0',
  38012. // Use vw/vh to handle implicitly devicePixelRatio; issue #282
  38013. 'width: 100vw',
  38014. 'height: 100vh',
  38015. 'border: 0',
  38016. 'margin: 0',
  38017. // Set no padding in the case where you don't have control over
  38018. // the content injection, like in Unity WebGL; issue #282
  38019. 'padding: 0px',
  38020. 'box-sizing: content-box',
  38021. ];
  38022. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  38023. Util.safariCssSizeWorkaround(gl.canvas);
  38024. }
  38025. };
  38026. CardboardVRDisplay.prototype.onViewerChanged_ = function(viewer) {
  38027. this.deviceInfo_.setViewer(viewer);
  38028. if (this.distorter_) {
  38029. // Update the distortion appropriately.
  38030. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  38031. }
  38032. // Fire a new event containing viewer and device parameters for clients that
  38033. // want to implement their own geometry-based distortion.
  38034. this.fireVRDisplayDeviceParamsChange_();
  38035. };
  38036. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function() {
  38037. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  38038. detail: {
  38039. vrdisplay: this,
  38040. deviceInfo: this.deviceInfo_,
  38041. }
  38042. });
  38043. window.dispatchEvent(event);
  38044. };
  38045. module.exports = CardboardVRDisplay;
  38046. },{"./base.js":48,"./cardboard-distorter.js":49,"./cardboard-ui.js":50,"./device-info.js":53,"./dpdb/dpdb.js":57,"./rotate-instructions.js":62,"./sensor-fusion/fusion-pose-sensor.js":64,"./util.js":68,"./viewer-selector.js":69}],52:[function(_dereq_,module,exports){
  38047. /**
  38048. * Copyright (c) 2016, Brandon Jones.
  38049. * https://github.com/toji/webgl-utils/blob/master/src/wglu-preserve-state.js
  38050. * LICENSE: https://github.com/toji/webgl-utils/blob/master/LICENSE.md
  38051. */
  38052. function WGLUPreserveGLState(gl, bindings, callback) {
  38053. if (!bindings) {
  38054. callback(gl);
  38055. return;
  38056. }
  38057. var boundValues = [];
  38058. var activeTexture = null;
  38059. for (var i = 0; i < bindings.length; ++i) {
  38060. var binding = bindings[i];
  38061. switch (binding) {
  38062. case gl.TEXTURE_BINDING_2D:
  38063. case gl.TEXTURE_BINDING_CUBE_MAP:
  38064. var textureUnit = bindings[++i];
  38065. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  38066. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  38067. boundValues.push(null, null);
  38068. break;
  38069. }
  38070. if (!activeTexture) {
  38071. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38072. }
  38073. gl.activeTexture(textureUnit);
  38074. boundValues.push(gl.getParameter(binding), null);
  38075. break;
  38076. case gl.ACTIVE_TEXTURE:
  38077. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  38078. boundValues.push(null);
  38079. break;
  38080. default:
  38081. boundValues.push(gl.getParameter(binding));
  38082. break;
  38083. }
  38084. }
  38085. callback(gl);
  38086. for (var i = 0; i < bindings.length; ++i) {
  38087. var binding = bindings[i];
  38088. var boundValue = boundValues[i];
  38089. switch (binding) {
  38090. case gl.ACTIVE_TEXTURE:
  38091. break; // Ignore this binding, since we special-case it to happen last.
  38092. case gl.ARRAY_BUFFER_BINDING:
  38093. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  38094. break;
  38095. case gl.COLOR_CLEAR_VALUE:
  38096. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38097. break;
  38098. case gl.COLOR_WRITEMASK:
  38099. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38100. break;
  38101. case gl.CURRENT_PROGRAM:
  38102. gl.useProgram(boundValue);
  38103. break;
  38104. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  38105. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  38106. break;
  38107. case gl.FRAMEBUFFER_BINDING:
  38108. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38109. break;
  38110. case gl.RENDERBUFFER_BINDING:
  38111. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38112. break;
  38113. case gl.TEXTURE_BINDING_2D:
  38114. var textureUnit = bindings[++i];
  38115. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38116. break;
  38117. gl.activeTexture(textureUnit);
  38118. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38119. break;
  38120. case gl.TEXTURE_BINDING_CUBE_MAP:
  38121. var textureUnit = bindings[++i];
  38122. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38123. break;
  38124. gl.activeTexture(textureUnit);
  38125. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38126. break;
  38127. case gl.VIEWPORT:
  38128. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38129. break;
  38130. case gl.BLEND:
  38131. case gl.CULL_FACE:
  38132. case gl.DEPTH_TEST:
  38133. case gl.SCISSOR_TEST:
  38134. case gl.STENCIL_TEST:
  38135. if (boundValue) {
  38136. gl.enable(binding);
  38137. } else {
  38138. gl.disable(binding);
  38139. }
  38140. break;
  38141. default:
  38142. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38143. break;
  38144. }
  38145. if (activeTexture) {
  38146. gl.activeTexture(activeTexture);
  38147. }
  38148. }
  38149. }
  38150. module.exports = WGLUPreserveGLState;
  38151. },{}],53:[function(_dereq_,module,exports){
  38152. /*
  38153. * Copyright 2015 Google Inc. All Rights Reserved.
  38154. * Licensed under the Apache License, Version 2.0 (the "License");
  38155. * you may not use this file except in compliance with the License.
  38156. * You may obtain a copy of the License at
  38157. *
  38158. * http://www.apache.org/licenses/LICENSE-2.0
  38159. *
  38160. * Unless required by applicable law or agreed to in writing, software
  38161. * distributed under the License is distributed on an "AS IS" BASIS,
  38162. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38163. * See the License for the specific language governing permissions and
  38164. * limitations under the License.
  38165. */
  38166. var Distortion = _dereq_('./distortion/distortion.js');
  38167. var MathUtil = _dereq_('./math-util.js');
  38168. var Util = _dereq_('./util.js');
  38169. function Device(params) {
  38170. this.width = params.width || Util.getScreenWidth();
  38171. this.height = params.height || Util.getScreenHeight();
  38172. this.widthMeters = params.widthMeters;
  38173. this.heightMeters = params.heightMeters;
  38174. this.bevelMeters = params.bevelMeters;
  38175. }
  38176. // Fallback Android device (based on Nexus 5 measurements) for use when
  38177. // we can't recognize an Android device.
  38178. var DEFAULT_ANDROID = new Device({
  38179. widthMeters: 0.110,
  38180. heightMeters: 0.062,
  38181. bevelMeters: 0.004
  38182. });
  38183. // Fallback iOS device (based on iPhone6) for use when
  38184. // we can't recognize an Android device.
  38185. var DEFAULT_IOS = new Device({
  38186. widthMeters: 0.1038,
  38187. heightMeters: 0.0584,
  38188. bevelMeters: 0.004
  38189. });
  38190. var Viewers = {
  38191. CardboardV1: new CardboardViewer({
  38192. id: 'CardboardV1',
  38193. label: 'Cardboard I/O 2014',
  38194. fov: 40,
  38195. interLensDistance: 0.060,
  38196. baselineLensDistance: 0.035,
  38197. screenLensDistance: 0.042,
  38198. distortionCoefficients: [0.441, 0.156],
  38199. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139,
  38200. -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841,
  38201. 0.0651772, -0.01488963, 0.001559834]
  38202. }),
  38203. CardboardV2: new CardboardViewer({
  38204. id: 'CardboardV2',
  38205. label: 'Cardboard I/O 2015',
  38206. fov: 60,
  38207. interLensDistance: 0.064,
  38208. baselineLensDistance: 0.035,
  38209. screenLensDistance: 0.039,
  38210. distortionCoefficients: [0.34, 0.55],
  38211. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051,
  38212. 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956,
  38213. -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  38214. })
  38215. };
  38216. var DEFAULT_LEFT_CENTER = {x: 0.5, y: 0.5};
  38217. var DEFAULT_RIGHT_CENTER = {x: 0.5, y: 0.5};
  38218. /**
  38219. * Manages information about the device and the viewer.
  38220. *
  38221. * deviceParams indicates the parameters of the device to use (generally
  38222. * obtained from dpdb.getDeviceParams()). Can be null to mean no device
  38223. * params were found.
  38224. */
  38225. function DeviceInfo(deviceParams) {
  38226. this.viewer = Viewers.CardboardV2;
  38227. this.updateDeviceParams(deviceParams);
  38228. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38229. }
  38230. DeviceInfo.prototype.updateDeviceParams = function(deviceParams) {
  38231. this.device = this.determineDevice_(deviceParams) || this.device;
  38232. };
  38233. DeviceInfo.prototype.getDevice = function() {
  38234. return this.device;
  38235. };
  38236. DeviceInfo.prototype.setViewer = function(viewer) {
  38237. this.viewer = viewer;
  38238. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38239. };
  38240. DeviceInfo.prototype.determineDevice_ = function(deviceParams) {
  38241. if (!deviceParams) {
  38242. // No parameters, so use a default.
  38243. if (Util.isIOS()) {
  38244. console.warn('Using fallback iOS device measurements.');
  38245. return DEFAULT_IOS;
  38246. } else {
  38247. console.warn('Using fallback Android device measurements.');
  38248. return DEFAULT_ANDROID;
  38249. }
  38250. }
  38251. // Compute device screen dimensions based on deviceParams.
  38252. var METERS_PER_INCH = 0.0254;
  38253. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  38254. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  38255. var width = Util.getScreenWidth();
  38256. var height = Util.getScreenHeight();
  38257. return new Device({
  38258. widthMeters: metersPerPixelX * width,
  38259. heightMeters: metersPerPixelY * height,
  38260. bevelMeters: deviceParams.bevelMm * 0.001,
  38261. });
  38262. };
  38263. /**
  38264. * Calculates field of view for the left eye.
  38265. */
  38266. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function() {
  38267. var viewer = this.viewer;
  38268. var device = this.device;
  38269. var distortion = this.distortion;
  38270. // Device.height and device.width for device in portrait mode, so transpose.
  38271. var eyeToScreenDistance = viewer.screenLensDistance;
  38272. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  38273. var innerDist = viewer.interLensDistance / 2;
  38274. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  38275. var topDist = device.heightMeters - bottomDist;
  38276. var outerAngle = MathUtil.radToDeg * Math.atan(
  38277. distortion.distort(outerDist / eyeToScreenDistance));
  38278. var innerAngle = MathUtil.radToDeg * Math.atan(
  38279. distortion.distort(innerDist / eyeToScreenDistance));
  38280. var bottomAngle = MathUtil.radToDeg * Math.atan(
  38281. distortion.distort(bottomDist / eyeToScreenDistance));
  38282. var topAngle = MathUtil.radToDeg * Math.atan(
  38283. distortion.distort(topDist / eyeToScreenDistance));
  38284. return {
  38285. leftDegrees: Math.min(outerAngle, viewer.fov),
  38286. rightDegrees: Math.min(innerAngle, viewer.fov),
  38287. downDegrees: Math.min(bottomAngle, viewer.fov),
  38288. upDegrees: Math.min(topAngle, viewer.fov)
  38289. };
  38290. };
  38291. /**
  38292. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38293. * current device and screen parameters.
  38294. */
  38295. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function() {
  38296. var viewer = this.viewer;
  38297. var device = this.device;
  38298. var distortion = this.distortion;
  38299. // Tan-angles from the max FOV.
  38300. var fovLeft = Math.tan(-MathUtil.degToRad * viewer.fov);
  38301. var fovTop = Math.tan(MathUtil.degToRad * viewer.fov);
  38302. var fovRight = Math.tan(MathUtil.degToRad * viewer.fov);
  38303. var fovBottom = Math.tan(-MathUtil.degToRad * viewer.fov);
  38304. // Viewport size.
  38305. var halfWidth = device.widthMeters / 4;
  38306. var halfHeight = device.heightMeters / 2;
  38307. // Viewport center, measured from left lens position.
  38308. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38309. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38310. var centerY = -verticalLensOffset;
  38311. var centerZ = viewer.screenLensDistance;
  38312. // Tan-angles of the viewport edges, as seen through the lens.
  38313. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  38314. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  38315. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  38316. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  38317. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38318. var result = new Float32Array(4);
  38319. result[0] = Math.max(fovLeft, screenLeft);
  38320. result[1] = Math.min(fovTop, screenTop);
  38321. result[2] = Math.min(fovRight, screenRight);
  38322. result[3] = Math.max(fovBottom, screenBottom);
  38323. return result;
  38324. };
  38325. /**
  38326. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38327. * current device and screen parameters, assuming no lenses.
  38328. */
  38329. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function() {
  38330. var viewer = this.viewer;
  38331. var device = this.device;
  38332. var distortion = this.distortion;
  38333. var result = new Float32Array(4);
  38334. // Tan-angles from the max FOV.
  38335. var fovLeft = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38336. var fovTop = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38337. var fovRight = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38338. var fovBottom = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38339. // Viewport size.
  38340. var halfWidth = device.widthMeters / 4;
  38341. var halfHeight = device.heightMeters / 2;
  38342. // Viewport center, measured from left lens position.
  38343. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38344. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38345. var centerY = -verticalLensOffset;
  38346. var centerZ = viewer.screenLensDistance;
  38347. // Tan-angles of the viewport edges, as seen through the lens.
  38348. var screenLeft = (centerX - halfWidth) / centerZ;
  38349. var screenTop = (centerY + halfHeight) / centerZ;
  38350. var screenRight = (centerX + halfWidth) / centerZ;
  38351. var screenBottom = (centerY - halfHeight) / centerZ;
  38352. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38353. result[0] = Math.max(fovLeft, screenLeft);
  38354. result[1] = Math.min(fovTop, screenTop);
  38355. result[2] = Math.min(fovRight, screenRight);
  38356. result[3] = Math.max(fovBottom, screenBottom);
  38357. return result;
  38358. };
  38359. /**
  38360. * Calculates the screen rectangle visible from the left eye for the
  38361. * current device and screen parameters.
  38362. */
  38363. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function(undistortedFrustum) {
  38364. var viewer = this.viewer;
  38365. var device = this.device;
  38366. var dist = viewer.screenLensDistance;
  38367. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  38368. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  38369. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  38370. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  38371. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  38372. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  38373. return {
  38374. x: left,
  38375. y: bottom,
  38376. width: right - left,
  38377. height: top - bottom
  38378. };
  38379. };
  38380. DeviceInfo.prototype.getFieldOfViewLeftEye = function(opt_isUndistorted) {
  38381. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() :
  38382. this.getDistortedFieldOfViewLeftEye();
  38383. };
  38384. DeviceInfo.prototype.getFieldOfViewRightEye = function(opt_isUndistorted) {
  38385. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  38386. return {
  38387. leftDegrees: fov.rightDegrees,
  38388. rightDegrees: fov.leftDegrees,
  38389. upDegrees: fov.upDegrees,
  38390. downDegrees: fov.downDegrees
  38391. };
  38392. };
  38393. /**
  38394. * Calculates undistorted field of view for the left eye.
  38395. */
  38396. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function() {
  38397. var p = this.getUndistortedParams_();
  38398. return {
  38399. leftDegrees: MathUtil.radToDeg * Math.atan(p.outerDist),
  38400. rightDegrees: MathUtil.radToDeg * Math.atan(p.innerDist),
  38401. downDegrees: MathUtil.radToDeg * Math.atan(p.bottomDist),
  38402. upDegrees: MathUtil.radToDeg * Math.atan(p.topDist)
  38403. };
  38404. };
  38405. DeviceInfo.prototype.getUndistortedViewportLeftEye = function() {
  38406. var p = this.getUndistortedParams_();
  38407. var viewer = this.viewer;
  38408. var device = this.device;
  38409. // Distances stored in local variables are in tan-angle units unless otherwise
  38410. // noted.
  38411. var eyeToScreenDistance = viewer.screenLensDistance;
  38412. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38413. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38414. var xPxPerTanAngle = device.width / screenWidth;
  38415. var yPxPerTanAngle = device.height / screenHeight;
  38416. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38417. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38418. return {
  38419. x: x,
  38420. y: y,
  38421. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38422. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38423. };
  38424. };
  38425. DeviceInfo.prototype.getUndistortedParams_ = function() {
  38426. var viewer = this.viewer;
  38427. var device = this.device;
  38428. var distortion = this.distortion;
  38429. // Most of these variables in tan-angle units.
  38430. var eyeToScreenDistance = viewer.screenLensDistance;
  38431. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38432. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38433. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38434. var eyePosX = screenWidth / 2 - halfLensDistance;
  38435. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38436. var maxFov = viewer.fov;
  38437. var viewerMax = distortion.distortInverse(Math.tan(MathUtil.degToRad * maxFov));
  38438. var outerDist = Math.min(eyePosX, viewerMax);
  38439. var innerDist = Math.min(halfLensDistance, viewerMax);
  38440. var bottomDist = Math.min(eyePosY, viewerMax);
  38441. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38442. return {
  38443. outerDist: outerDist,
  38444. innerDist: innerDist,
  38445. topDist: topDist,
  38446. bottomDist: bottomDist,
  38447. eyePosX: eyePosX,
  38448. eyePosY: eyePosY
  38449. };
  38450. };
  38451. function CardboardViewer(params) {
  38452. // A machine readable ID.
  38453. this.id = params.id;
  38454. // A human readable label.
  38455. this.label = params.label;
  38456. // Field of view in degrees (per side).
  38457. this.fov = params.fov;
  38458. // Distance between lens centers in meters.
  38459. this.interLensDistance = params.interLensDistance;
  38460. // Distance between viewer baseline and lens center in meters.
  38461. this.baselineLensDistance = params.baselineLensDistance;
  38462. // Screen-to-lens distance in meters.
  38463. this.screenLensDistance = params.screenLensDistance;
  38464. // Distortion coefficients.
  38465. this.distortionCoefficients = params.distortionCoefficients;
  38466. // Inverse distortion coefficients.
  38467. // TODO: Calculate these from distortionCoefficients in the future.
  38468. this.inverseCoefficients = params.inverseCoefficients;
  38469. }
  38470. // Export viewer information.
  38471. DeviceInfo.Viewers = Viewers;
  38472. module.exports = DeviceInfo;
  38473. },{"./distortion/distortion.js":55,"./math-util.js":59,"./util.js":68}],54:[function(_dereq_,module,exports){
  38474. /*
  38475. * Copyright 2016 Google Inc. All Rights Reserved.
  38476. * Licensed under the Apache License, Version 2.0 (the "License");
  38477. * you may not use this file except in compliance with the License.
  38478. * You may obtain a copy of the License at
  38479. *
  38480. * http://www.apache.org/licenses/LICENSE-2.0
  38481. *
  38482. * Unless required by applicable law or agreed to in writing, software
  38483. * distributed under the License is distributed on an "AS IS" BASIS,
  38484. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38485. * See the License for the specific language governing permissions and
  38486. * limitations under the License.
  38487. */
  38488. var VRDisplay = _dereq_('./base.js').VRDisplay;
  38489. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  38490. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  38491. /**
  38492. * Wraps a VRDisplay and exposes it as a HMDVRDevice
  38493. */
  38494. function VRDisplayHMDDevice(display) {
  38495. this.display = display;
  38496. this.hardwareUnitId = display.displayId;
  38497. this.deviceId = 'webvr-polyfill:HMD:' + display.displayId;
  38498. this.deviceName = display.displayName + ' (HMD)';
  38499. }
  38500. VRDisplayHMDDevice.prototype = new HMDVRDevice();
  38501. VRDisplayHMDDevice.prototype.getEyeParameters = function(whichEye) {
  38502. var eyeParameters = this.display.getEyeParameters(whichEye);
  38503. return {
  38504. currentFieldOfView: eyeParameters.fieldOfView,
  38505. maximumFieldOfView: eyeParameters.fieldOfView,
  38506. minimumFieldOfView: eyeParameters.fieldOfView,
  38507. recommendedFieldOfView: eyeParameters.fieldOfView,
  38508. eyeTranslation: { x: eyeParameters.offset[0], y: eyeParameters.offset[1], z: eyeParameters.offset[2] },
  38509. renderRect: {
  38510. x: (whichEye == 'right') ? eyeParameters.renderWidth : 0,
  38511. y: 0,
  38512. width: eyeParameters.renderWidth,
  38513. height: eyeParameters.renderHeight
  38514. }
  38515. };
  38516. };
  38517. VRDisplayHMDDevice.prototype.setFieldOfView =
  38518. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  38519. // Not supported. getEyeParameters reports that the min, max, and recommended
  38520. // FoV is all the same, so no adjustment can be made.
  38521. };
  38522. // TODO: Need to hook requestFullscreen to see if a wrapped VRDisplay was passed
  38523. // in as an option. If so we should prevent the default fullscreen behavior and
  38524. // call VRDisplay.requestPresent instead.
  38525. /**
  38526. * Wraps a VRDisplay and exposes it as a PositionSensorVRDevice
  38527. */
  38528. function VRDisplayPositionSensorDevice(display) {
  38529. this.display = display;
  38530. this.hardwareUnitId = display.displayId;
  38531. this.deviceId = 'webvr-polyfill:PositionSensor: ' + display.displayId;
  38532. this.deviceName = display.displayName + ' (PositionSensor)';
  38533. }
  38534. VRDisplayPositionSensorDevice.prototype = new PositionSensorVRDevice();
  38535. VRDisplayPositionSensorDevice.prototype.getState = function() {
  38536. var pose = this.display.getPose();
  38537. return {
  38538. position: pose.position ? { x: pose.position[0], y: pose.position[1], z: pose.position[2] } : null,
  38539. orientation: pose.orientation ? { x: pose.orientation[0], y: pose.orientation[1], z: pose.orientation[2], w: pose.orientation[3] } : null,
  38540. linearVelocity: null,
  38541. linearAcceleration: null,
  38542. angularVelocity: null,
  38543. angularAcceleration: null
  38544. };
  38545. };
  38546. VRDisplayPositionSensorDevice.prototype.resetState = function() {
  38547. return this.positionDevice.resetPose();
  38548. };
  38549. module.exports.VRDisplayHMDDevice = VRDisplayHMDDevice;
  38550. module.exports.VRDisplayPositionSensorDevice = VRDisplayPositionSensorDevice;
  38551. },{"./base.js":48}],55:[function(_dereq_,module,exports){
  38552. /**
  38553. * TODO(smus): Implement coefficient inversion.
  38554. */
  38555. function Distortion(coefficients) {
  38556. this.coefficients = coefficients;
  38557. }
  38558. /**
  38559. * Calculates the inverse distortion for a radius.
  38560. * </p><p>
  38561. * Allows to compute the original undistorted radius from a distorted one.
  38562. * See also getApproximateInverseDistortion() for a faster but potentially
  38563. * less accurate method.
  38564. *
  38565. * @param {Number} radius Distorted radius from the lens center in tan-angle units.
  38566. * @return {Number} The undistorted radius in tan-angle units.
  38567. */
  38568. Distortion.prototype.distortInverse = function(radius) {
  38569. // Secant method.
  38570. var r0 = 0;
  38571. var r1 = 1;
  38572. var dr0 = radius - this.distort(r0);
  38573. while (Math.abs(r1 - r0) > 0.0001 /** 0.1mm */) {
  38574. var dr1 = radius - this.distort(r1);
  38575. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38576. r0 = r1;
  38577. r1 = r2;
  38578. dr0 = dr1;
  38579. }
  38580. return r1;
  38581. };
  38582. /**
  38583. * Distorts a radius by its distortion factor from the center of the lenses.
  38584. *
  38585. * @param {Number} radius Radius from the lens center in tan-angle units.
  38586. * @return {Number} The distorted radius in tan-angle units.
  38587. */
  38588. Distortion.prototype.distort = function(radius) {
  38589. var r2 = radius * radius;
  38590. var ret = 0;
  38591. for (var i = 0; i < this.coefficients.length; i++) {
  38592. ret = r2 * (ret + this.coefficients[i]);
  38593. }
  38594. return (ret + 1) * radius;
  38595. };
  38596. module.exports = Distortion;
  38597. },{}],56:[function(_dereq_,module,exports){
  38598. module.exports={
  38599. "format": 1,
  38600. "last_updated": "2017-08-27T14:39:31Z",
  38601. "devices": [
  38602. {
  38603. "type": "android",
  38604. "rules": [
  38605. {
  38606. "mdmh": "asus/*/Nexus 7/*"
  38607. },
  38608. {
  38609. "ua": "Nexus 7"
  38610. }
  38611. ],
  38612. "dpi": [
  38613. 320.8,
  38614. 323
  38615. ],
  38616. "bw": 3,
  38617. "ac": 500
  38618. },
  38619. {
  38620. "type": "android",
  38621. "rules": [
  38622. {
  38623. "mdmh": "asus/*/ASUS_Z00AD/*"
  38624. },
  38625. {
  38626. "ua": "ASUS_Z00AD"
  38627. }
  38628. ],
  38629. "dpi": [
  38630. 403,
  38631. 404.6
  38632. ],
  38633. "bw": 3,
  38634. "ac": 1000
  38635. },
  38636. {
  38637. "type": "android",
  38638. "rules": [
  38639. {
  38640. "mdmh": "Google/*/Pixel XL/*"
  38641. },
  38642. {
  38643. "ua": "Pixel XL"
  38644. }
  38645. ],
  38646. "dpi": [
  38647. 537.9,
  38648. 533
  38649. ],
  38650. "bw": 3,
  38651. "ac": 1000
  38652. },
  38653. {
  38654. "type": "android",
  38655. "rules": [
  38656. {
  38657. "mdmh": "Google/*/Pixel/*"
  38658. },
  38659. {
  38660. "ua": "Pixel"
  38661. }
  38662. ],
  38663. "dpi": [
  38664. 432.6,
  38665. 436.7
  38666. ],
  38667. "bw": 3,
  38668. "ac": 1000
  38669. },
  38670. {
  38671. "type": "android",
  38672. "rules": [
  38673. {
  38674. "mdmh": "HTC/*/HTC6435LVW/*"
  38675. },
  38676. {
  38677. "ua": "HTC6435LVW"
  38678. }
  38679. ],
  38680. "dpi": [
  38681. 449.7,
  38682. 443.3
  38683. ],
  38684. "bw": 3,
  38685. "ac": 1000
  38686. },
  38687. {
  38688. "type": "android",
  38689. "rules": [
  38690. {
  38691. "mdmh": "HTC/*/HTC One XL/*"
  38692. },
  38693. {
  38694. "ua": "HTC One XL"
  38695. }
  38696. ],
  38697. "dpi": [
  38698. 315.3,
  38699. 314.6
  38700. ],
  38701. "bw": 3,
  38702. "ac": 1000
  38703. },
  38704. {
  38705. "type": "android",
  38706. "rules": [
  38707. {
  38708. "mdmh": "htc/*/Nexus 9/*"
  38709. },
  38710. {
  38711. "ua": "Nexus 9"
  38712. }
  38713. ],
  38714. "dpi": 289,
  38715. "bw": 3,
  38716. "ac": 500
  38717. },
  38718. {
  38719. "type": "android",
  38720. "rules": [
  38721. {
  38722. "mdmh": "HTC/*/HTC One M9/*"
  38723. },
  38724. {
  38725. "ua": "HTC One M9"
  38726. }
  38727. ],
  38728. "dpi": [
  38729. 442.5,
  38730. 443.3
  38731. ],
  38732. "bw": 3,
  38733. "ac": 500
  38734. },
  38735. {
  38736. "type": "android",
  38737. "rules": [
  38738. {
  38739. "mdmh": "HTC/*/HTC One_M8/*"
  38740. },
  38741. {
  38742. "ua": "HTC One_M8"
  38743. }
  38744. ],
  38745. "dpi": [
  38746. 449.7,
  38747. 447.4
  38748. ],
  38749. "bw": 3,
  38750. "ac": 500
  38751. },
  38752. {
  38753. "type": "android",
  38754. "rules": [
  38755. {
  38756. "mdmh": "HTC/*/HTC One/*"
  38757. },
  38758. {
  38759. "ua": "HTC One"
  38760. }
  38761. ],
  38762. "dpi": 472.8,
  38763. "bw": 3,
  38764. "ac": 1000
  38765. },
  38766. {
  38767. "type": "android",
  38768. "rules": [
  38769. {
  38770. "mdmh": "Huawei/*/Nexus 6P/*"
  38771. },
  38772. {
  38773. "ua": "Nexus 6P"
  38774. }
  38775. ],
  38776. "dpi": [
  38777. 515.1,
  38778. 518
  38779. ],
  38780. "bw": 3,
  38781. "ac": 1000
  38782. },
  38783. {
  38784. "type": "android",
  38785. "rules": [
  38786. {
  38787. "mdmh": "LENOVO/*/Lenovo PB2-690Y/*"
  38788. },
  38789. {
  38790. "ua": "Lenovo PB2-690Y"
  38791. }
  38792. ],
  38793. "dpi": [
  38794. 457.2,
  38795. 454.713
  38796. ],
  38797. "bw": 3,
  38798. "ac": 500
  38799. },
  38800. {
  38801. "type": "android",
  38802. "rules": [
  38803. {
  38804. "mdmh": "LGE/*/Nexus 5X/*"
  38805. },
  38806. {
  38807. "ua": "Nexus 5X"
  38808. }
  38809. ],
  38810. "dpi": [
  38811. 422,
  38812. 419.9
  38813. ],
  38814. "bw": 3,
  38815. "ac": 1000
  38816. },
  38817. {
  38818. "type": "android",
  38819. "rules": [
  38820. {
  38821. "mdmh": "LGE/*/LGMS345/*"
  38822. },
  38823. {
  38824. "ua": "LGMS345"
  38825. }
  38826. ],
  38827. "dpi": [
  38828. 221.7,
  38829. 219.1
  38830. ],
  38831. "bw": 3,
  38832. "ac": 500
  38833. },
  38834. {
  38835. "type": "android",
  38836. "rules": [
  38837. {
  38838. "mdmh": "LGE/*/LG-D800/*"
  38839. },
  38840. {
  38841. "ua": "LG-D800"
  38842. }
  38843. ],
  38844. "dpi": [
  38845. 422,
  38846. 424.1
  38847. ],
  38848. "bw": 3,
  38849. "ac": 500
  38850. },
  38851. {
  38852. "type": "android",
  38853. "rules": [
  38854. {
  38855. "mdmh": "LGE/*/LG-D850/*"
  38856. },
  38857. {
  38858. "ua": "LG-D850"
  38859. }
  38860. ],
  38861. "dpi": [
  38862. 537.9,
  38863. 541.9
  38864. ],
  38865. "bw": 3,
  38866. "ac": 500
  38867. },
  38868. {
  38869. "type": "android",
  38870. "rules": [
  38871. {
  38872. "mdmh": "LGE/*/VS985 4G/*"
  38873. },
  38874. {
  38875. "ua": "VS985 4G"
  38876. }
  38877. ],
  38878. "dpi": [
  38879. 537.9,
  38880. 535.6
  38881. ],
  38882. "bw": 3,
  38883. "ac": 1000
  38884. },
  38885. {
  38886. "type": "android",
  38887. "rules": [
  38888. {
  38889. "mdmh": "LGE/*/Nexus 5/*"
  38890. },
  38891. {
  38892. "ua": "Nexus 5 B"
  38893. }
  38894. ],
  38895. "dpi": [
  38896. 442.4,
  38897. 444.8
  38898. ],
  38899. "bw": 3,
  38900. "ac": 1000
  38901. },
  38902. {
  38903. "type": "android",
  38904. "rules": [
  38905. {
  38906. "mdmh": "LGE/*/Nexus 4/*"
  38907. },
  38908. {
  38909. "ua": "Nexus 4"
  38910. }
  38911. ],
  38912. "dpi": [
  38913. 319.8,
  38914. 318.4
  38915. ],
  38916. "bw": 3,
  38917. "ac": 1000
  38918. },
  38919. {
  38920. "type": "android",
  38921. "rules": [
  38922. {
  38923. "mdmh": "LGE/*/LG-P769/*"
  38924. },
  38925. {
  38926. "ua": "LG-P769"
  38927. }
  38928. ],
  38929. "dpi": [
  38930. 240.6,
  38931. 247.5
  38932. ],
  38933. "bw": 3,
  38934. "ac": 1000
  38935. },
  38936. {
  38937. "type": "android",
  38938. "rules": [
  38939. {
  38940. "mdmh": "LGE/*/LGMS323/*"
  38941. },
  38942. {
  38943. "ua": "LGMS323"
  38944. }
  38945. ],
  38946. "dpi": [
  38947. 206.6,
  38948. 204.6
  38949. ],
  38950. "bw": 3,
  38951. "ac": 1000
  38952. },
  38953. {
  38954. "type": "android",
  38955. "rules": [
  38956. {
  38957. "mdmh": "LGE/*/LGLS996/*"
  38958. },
  38959. {
  38960. "ua": "LGLS996"
  38961. }
  38962. ],
  38963. "dpi": [
  38964. 403.4,
  38965. 401.5
  38966. ],
  38967. "bw": 3,
  38968. "ac": 1000
  38969. },
  38970. {
  38971. "type": "android",
  38972. "rules": [
  38973. {
  38974. "mdmh": "Micromax/*/4560MMX/*"
  38975. },
  38976. {
  38977. "ua": "4560MMX"
  38978. }
  38979. ],
  38980. "dpi": [
  38981. 240,
  38982. 219.4
  38983. ],
  38984. "bw": 3,
  38985. "ac": 1000
  38986. },
  38987. {
  38988. "type": "android",
  38989. "rules": [
  38990. {
  38991. "mdmh": "Micromax/*/A250/*"
  38992. },
  38993. {
  38994. "ua": "Micromax A250"
  38995. }
  38996. ],
  38997. "dpi": [
  38998. 480,
  38999. 446.4
  39000. ],
  39001. "bw": 3,
  39002. "ac": 1000
  39003. },
  39004. {
  39005. "type": "android",
  39006. "rules": [
  39007. {
  39008. "mdmh": "Micromax/*/Micromax AQ4501/*"
  39009. },
  39010. {
  39011. "ua": "Micromax AQ4501"
  39012. }
  39013. ],
  39014. "dpi": 240,
  39015. "bw": 3,
  39016. "ac": 500
  39017. },
  39018. {
  39019. "type": "android",
  39020. "rules": [
  39021. {
  39022. "mdmh": "motorola/*/DROID RAZR/*"
  39023. },
  39024. {
  39025. "ua": "DROID RAZR"
  39026. }
  39027. ],
  39028. "dpi": [
  39029. 368.1,
  39030. 256.7
  39031. ],
  39032. "bw": 3,
  39033. "ac": 1000
  39034. },
  39035. {
  39036. "type": "android",
  39037. "rules": [
  39038. {
  39039. "mdmh": "motorola/*/XT830C/*"
  39040. },
  39041. {
  39042. "ua": "XT830C"
  39043. }
  39044. ],
  39045. "dpi": [
  39046. 254,
  39047. 255.9
  39048. ],
  39049. "bw": 3,
  39050. "ac": 1000
  39051. },
  39052. {
  39053. "type": "android",
  39054. "rules": [
  39055. {
  39056. "mdmh": "motorola/*/XT1021/*"
  39057. },
  39058. {
  39059. "ua": "XT1021"
  39060. }
  39061. ],
  39062. "dpi": [
  39063. 254,
  39064. 256.7
  39065. ],
  39066. "bw": 3,
  39067. "ac": 500
  39068. },
  39069. {
  39070. "type": "android",
  39071. "rules": [
  39072. {
  39073. "mdmh": "motorola/*/XT1023/*"
  39074. },
  39075. {
  39076. "ua": "XT1023"
  39077. }
  39078. ],
  39079. "dpi": [
  39080. 254,
  39081. 256.7
  39082. ],
  39083. "bw": 3,
  39084. "ac": 500
  39085. },
  39086. {
  39087. "type": "android",
  39088. "rules": [
  39089. {
  39090. "mdmh": "motorola/*/XT1028/*"
  39091. },
  39092. {
  39093. "ua": "XT1028"
  39094. }
  39095. ],
  39096. "dpi": [
  39097. 326.6,
  39098. 327.6
  39099. ],
  39100. "bw": 3,
  39101. "ac": 1000
  39102. },
  39103. {
  39104. "type": "android",
  39105. "rules": [
  39106. {
  39107. "mdmh": "motorola/*/XT1034/*"
  39108. },
  39109. {
  39110. "ua": "XT1034"
  39111. }
  39112. ],
  39113. "dpi": [
  39114. 326.6,
  39115. 328.4
  39116. ],
  39117. "bw": 3,
  39118. "ac": 500
  39119. },
  39120. {
  39121. "type": "android",
  39122. "rules": [
  39123. {
  39124. "mdmh": "motorola/*/XT1053/*"
  39125. },
  39126. {
  39127. "ua": "XT1053"
  39128. }
  39129. ],
  39130. "dpi": [
  39131. 315.3,
  39132. 316.1
  39133. ],
  39134. "bw": 3,
  39135. "ac": 1000
  39136. },
  39137. {
  39138. "type": "android",
  39139. "rules": [
  39140. {
  39141. "mdmh": "motorola/*/XT1562/*"
  39142. },
  39143. {
  39144. "ua": "XT1562"
  39145. }
  39146. ],
  39147. "dpi": [
  39148. 403.4,
  39149. 402.7
  39150. ],
  39151. "bw": 3,
  39152. "ac": 1000
  39153. },
  39154. {
  39155. "type": "android",
  39156. "rules": [
  39157. {
  39158. "mdmh": "motorola/*/Nexus 6/*"
  39159. },
  39160. {
  39161. "ua": "Nexus 6 B"
  39162. }
  39163. ],
  39164. "dpi": [
  39165. 494.3,
  39166. 489.7
  39167. ],
  39168. "bw": 3,
  39169. "ac": 1000
  39170. },
  39171. {
  39172. "type": "android",
  39173. "rules": [
  39174. {
  39175. "mdmh": "motorola/*/XT1063/*"
  39176. },
  39177. {
  39178. "ua": "XT1063"
  39179. }
  39180. ],
  39181. "dpi": [
  39182. 295,
  39183. 296.6
  39184. ],
  39185. "bw": 3,
  39186. "ac": 1000
  39187. },
  39188. {
  39189. "type": "android",
  39190. "rules": [
  39191. {
  39192. "mdmh": "motorola/*/XT1064/*"
  39193. },
  39194. {
  39195. "ua": "XT1064"
  39196. }
  39197. ],
  39198. "dpi": [
  39199. 295,
  39200. 295.6
  39201. ],
  39202. "bw": 3,
  39203. "ac": 500
  39204. },
  39205. {
  39206. "type": "android",
  39207. "rules": [
  39208. {
  39209. "mdmh": "motorola/*/XT1092/*"
  39210. },
  39211. {
  39212. "ua": "XT1092"
  39213. }
  39214. ],
  39215. "dpi": [
  39216. 422,
  39217. 424.1
  39218. ],
  39219. "bw": 3,
  39220. "ac": 500
  39221. },
  39222. {
  39223. "type": "android",
  39224. "rules": [
  39225. {
  39226. "mdmh": "motorola/*/XT1095/*"
  39227. },
  39228. {
  39229. "ua": "XT1095"
  39230. }
  39231. ],
  39232. "dpi": [
  39233. 422,
  39234. 423.4
  39235. ],
  39236. "bw": 3,
  39237. "ac": 1000
  39238. },
  39239. {
  39240. "type": "android",
  39241. "rules": [
  39242. {
  39243. "mdmh": "motorola/*/G4/*"
  39244. },
  39245. {
  39246. "ua": "Moto G (4)"
  39247. }
  39248. ],
  39249. "dpi": 401,
  39250. "bw": 4,
  39251. "ac": 1000
  39252. },
  39253. {
  39254. "type": "android",
  39255. "rules": [
  39256. {
  39257. "mdmh": "OnePlus/*/A0001/*"
  39258. },
  39259. {
  39260. "ua": "A0001"
  39261. }
  39262. ],
  39263. "dpi": [
  39264. 403.4,
  39265. 401
  39266. ],
  39267. "bw": 3,
  39268. "ac": 1000
  39269. },
  39270. {
  39271. "type": "android",
  39272. "rules": [
  39273. {
  39274. "mdmh": "OnePlus/*/ONE E1005/*"
  39275. },
  39276. {
  39277. "ua": "ONE E1005"
  39278. }
  39279. ],
  39280. "dpi": [
  39281. 442.4,
  39282. 441.4
  39283. ],
  39284. "bw": 3,
  39285. "ac": 1000
  39286. },
  39287. {
  39288. "type": "android",
  39289. "rules": [
  39290. {
  39291. "mdmh": "OnePlus/*/ONE A2005/*"
  39292. },
  39293. {
  39294. "ua": "ONE A2005"
  39295. }
  39296. ],
  39297. "dpi": [
  39298. 391.9,
  39299. 405.4
  39300. ],
  39301. "bw": 3,
  39302. "ac": 1000
  39303. },
  39304. {
  39305. "type": "android",
  39306. "rules": [
  39307. {
  39308. "mdmh": "OPPO/*/X909/*"
  39309. },
  39310. {
  39311. "ua": "X909"
  39312. }
  39313. ],
  39314. "dpi": [
  39315. 442.4,
  39316. 444.1
  39317. ],
  39318. "bw": 3,
  39319. "ac": 1000
  39320. },
  39321. {
  39322. "type": "android",
  39323. "rules": [
  39324. {
  39325. "mdmh": "samsung/*/GT-I9082/*"
  39326. },
  39327. {
  39328. "ua": "GT-I9082"
  39329. }
  39330. ],
  39331. "dpi": [
  39332. 184.7,
  39333. 185.4
  39334. ],
  39335. "bw": 3,
  39336. "ac": 1000
  39337. },
  39338. {
  39339. "type": "android",
  39340. "rules": [
  39341. {
  39342. "mdmh": "samsung/*/SM-G360P/*"
  39343. },
  39344. {
  39345. "ua": "SM-G360P"
  39346. }
  39347. ],
  39348. "dpi": [
  39349. 196.7,
  39350. 205.4
  39351. ],
  39352. "bw": 3,
  39353. "ac": 1000
  39354. },
  39355. {
  39356. "type": "android",
  39357. "rules": [
  39358. {
  39359. "mdmh": "samsung/*/Nexus S/*"
  39360. },
  39361. {
  39362. "ua": "Nexus S"
  39363. }
  39364. ],
  39365. "dpi": [
  39366. 234.5,
  39367. 229.8
  39368. ],
  39369. "bw": 3,
  39370. "ac": 1000
  39371. },
  39372. {
  39373. "type": "android",
  39374. "rules": [
  39375. {
  39376. "mdmh": "samsung/*/GT-I9300/*"
  39377. },
  39378. {
  39379. "ua": "GT-I9300"
  39380. }
  39381. ],
  39382. "dpi": [
  39383. 304.8,
  39384. 303.9
  39385. ],
  39386. "bw": 5,
  39387. "ac": 500
  39388. },
  39389. {
  39390. "type": "android",
  39391. "rules": [
  39392. {
  39393. "mdmh": "samsung/*/SM-T230NU/*"
  39394. },
  39395. {
  39396. "ua": "SM-T230NU"
  39397. }
  39398. ],
  39399. "dpi": 216,
  39400. "bw": 3,
  39401. "ac": 500
  39402. },
  39403. {
  39404. "type": "android",
  39405. "rules": [
  39406. {
  39407. "mdmh": "samsung/*/SGH-T399/*"
  39408. },
  39409. {
  39410. "ua": "SGH-T399"
  39411. }
  39412. ],
  39413. "dpi": [
  39414. 217.7,
  39415. 231.4
  39416. ],
  39417. "bw": 3,
  39418. "ac": 1000
  39419. },
  39420. {
  39421. "type": "android",
  39422. "rules": [
  39423. {
  39424. "mdmh": "samsung/*/SGH-M919/*"
  39425. },
  39426. {
  39427. "ua": "SGH-M919"
  39428. }
  39429. ],
  39430. "dpi": [
  39431. 440.8,
  39432. 437.7
  39433. ],
  39434. "bw": 3,
  39435. "ac": 1000
  39436. },
  39437. {
  39438. "type": "android",
  39439. "rules": [
  39440. {
  39441. "mdmh": "samsung/*/SM-N9005/*"
  39442. },
  39443. {
  39444. "ua": "SM-N9005"
  39445. }
  39446. ],
  39447. "dpi": [
  39448. 386.4,
  39449. 387
  39450. ],
  39451. "bw": 3,
  39452. "ac": 500
  39453. },
  39454. {
  39455. "type": "android",
  39456. "rules": [
  39457. {
  39458. "mdmh": "samsung/*/SAMSUNG-SM-N900A/*"
  39459. },
  39460. {
  39461. "ua": "SAMSUNG-SM-N900A"
  39462. }
  39463. ],
  39464. "dpi": [
  39465. 386.4,
  39466. 387.7
  39467. ],
  39468. "bw": 3,
  39469. "ac": 1000
  39470. },
  39471. {
  39472. "type": "android",
  39473. "rules": [
  39474. {
  39475. "mdmh": "samsung/*/GT-I9500/*"
  39476. },
  39477. {
  39478. "ua": "GT-I9500"
  39479. }
  39480. ],
  39481. "dpi": [
  39482. 442.5,
  39483. 443.3
  39484. ],
  39485. "bw": 3,
  39486. "ac": 500
  39487. },
  39488. {
  39489. "type": "android",
  39490. "rules": [
  39491. {
  39492. "mdmh": "samsung/*/GT-I9505/*"
  39493. },
  39494. {
  39495. "ua": "GT-I9505"
  39496. }
  39497. ],
  39498. "dpi": 439.4,
  39499. "bw": 4,
  39500. "ac": 1000
  39501. },
  39502. {
  39503. "type": "android",
  39504. "rules": [
  39505. {
  39506. "mdmh": "samsung/*/SM-G900F/*"
  39507. },
  39508. {
  39509. "ua": "SM-G900F"
  39510. }
  39511. ],
  39512. "dpi": [
  39513. 415.6,
  39514. 431.6
  39515. ],
  39516. "bw": 5,
  39517. "ac": 1000
  39518. },
  39519. {
  39520. "type": "android",
  39521. "rules": [
  39522. {
  39523. "mdmh": "samsung/*/SM-G900M/*"
  39524. },
  39525. {
  39526. "ua": "SM-G900M"
  39527. }
  39528. ],
  39529. "dpi": [
  39530. 415.6,
  39531. 431.6
  39532. ],
  39533. "bw": 5,
  39534. "ac": 1000
  39535. },
  39536. {
  39537. "type": "android",
  39538. "rules": [
  39539. {
  39540. "mdmh": "samsung/*/SM-G800F/*"
  39541. },
  39542. {
  39543. "ua": "SM-G800F"
  39544. }
  39545. ],
  39546. "dpi": 326.8,
  39547. "bw": 3,
  39548. "ac": 1000
  39549. },
  39550. {
  39551. "type": "android",
  39552. "rules": [
  39553. {
  39554. "mdmh": "samsung/*/SM-G906S/*"
  39555. },
  39556. {
  39557. "ua": "SM-G906S"
  39558. }
  39559. ],
  39560. "dpi": [
  39561. 562.7,
  39562. 572.4
  39563. ],
  39564. "bw": 3,
  39565. "ac": 1000
  39566. },
  39567. {
  39568. "type": "android",
  39569. "rules": [
  39570. {
  39571. "mdmh": "samsung/*/GT-I9300/*"
  39572. },
  39573. {
  39574. "ua": "GT-I9300"
  39575. }
  39576. ],
  39577. "dpi": [
  39578. 306.7,
  39579. 304.8
  39580. ],
  39581. "bw": 5,
  39582. "ac": 1000
  39583. },
  39584. {
  39585. "type": "android",
  39586. "rules": [
  39587. {
  39588. "mdmh": "samsung/*/SM-T535/*"
  39589. },
  39590. {
  39591. "ua": "SM-T535"
  39592. }
  39593. ],
  39594. "dpi": [
  39595. 142.6,
  39596. 136.4
  39597. ],
  39598. "bw": 3,
  39599. "ac": 500
  39600. },
  39601. {
  39602. "type": "android",
  39603. "rules": [
  39604. {
  39605. "mdmh": "samsung/*/SM-N920C/*"
  39606. },
  39607. {
  39608. "ua": "SM-N920C"
  39609. }
  39610. ],
  39611. "dpi": [
  39612. 515.1,
  39613. 518.4
  39614. ],
  39615. "bw": 3,
  39616. "ac": 1000
  39617. },
  39618. {
  39619. "type": "android",
  39620. "rules": [
  39621. {
  39622. "mdmh": "samsung/*/SM-N920W8/*"
  39623. },
  39624. {
  39625. "ua": "SM-N920W8"
  39626. }
  39627. ],
  39628. "dpi": [
  39629. 515.1,
  39630. 518.4
  39631. ],
  39632. "bw": 3,
  39633. "ac": 1000
  39634. },
  39635. {
  39636. "type": "android",
  39637. "rules": [
  39638. {
  39639. "mdmh": "samsung/*/GT-I9300I/*"
  39640. },
  39641. {
  39642. "ua": "GT-I9300I"
  39643. }
  39644. ],
  39645. "dpi": [
  39646. 304.8,
  39647. 305.8
  39648. ],
  39649. "bw": 3,
  39650. "ac": 1000
  39651. },
  39652. {
  39653. "type": "android",
  39654. "rules": [
  39655. {
  39656. "mdmh": "samsung/*/GT-I9195/*"
  39657. },
  39658. {
  39659. "ua": "GT-I9195"
  39660. }
  39661. ],
  39662. "dpi": [
  39663. 249.4,
  39664. 256.7
  39665. ],
  39666. "bw": 3,
  39667. "ac": 500
  39668. },
  39669. {
  39670. "type": "android",
  39671. "rules": [
  39672. {
  39673. "mdmh": "samsung/*/SPH-L520/*"
  39674. },
  39675. {
  39676. "ua": "SPH-L520"
  39677. }
  39678. ],
  39679. "dpi": [
  39680. 249.4,
  39681. 255.9
  39682. ],
  39683. "bw": 3,
  39684. "ac": 1000
  39685. },
  39686. {
  39687. "type": "android",
  39688. "rules": [
  39689. {
  39690. "mdmh": "samsung/*/SAMSUNG-SGH-I717/*"
  39691. },
  39692. {
  39693. "ua": "SAMSUNG-SGH-I717"
  39694. }
  39695. ],
  39696. "dpi": 285.8,
  39697. "bw": 3,
  39698. "ac": 1000
  39699. },
  39700. {
  39701. "type": "android",
  39702. "rules": [
  39703. {
  39704. "mdmh": "samsung/*/SPH-D710/*"
  39705. },
  39706. {
  39707. "ua": "SPH-D710"
  39708. }
  39709. ],
  39710. "dpi": [
  39711. 217.7,
  39712. 204.2
  39713. ],
  39714. "bw": 3,
  39715. "ac": 1000
  39716. },
  39717. {
  39718. "type": "android",
  39719. "rules": [
  39720. {
  39721. "mdmh": "samsung/*/GT-N7100/*"
  39722. },
  39723. {
  39724. "ua": "GT-N7100"
  39725. }
  39726. ],
  39727. "dpi": 265.1,
  39728. "bw": 3,
  39729. "ac": 1000
  39730. },
  39731. {
  39732. "type": "android",
  39733. "rules": [
  39734. {
  39735. "mdmh": "samsung/*/SCH-I605/*"
  39736. },
  39737. {
  39738. "ua": "SCH-I605"
  39739. }
  39740. ],
  39741. "dpi": 265.1,
  39742. "bw": 3,
  39743. "ac": 1000
  39744. },
  39745. {
  39746. "type": "android",
  39747. "rules": [
  39748. {
  39749. "mdmh": "samsung/*/Galaxy Nexus/*"
  39750. },
  39751. {
  39752. "ua": "Galaxy Nexus"
  39753. }
  39754. ],
  39755. "dpi": [
  39756. 315.3,
  39757. 314.2
  39758. ],
  39759. "bw": 3,
  39760. "ac": 1000
  39761. },
  39762. {
  39763. "type": "android",
  39764. "rules": [
  39765. {
  39766. "mdmh": "samsung/*/SM-N910H/*"
  39767. },
  39768. {
  39769. "ua": "SM-N910H"
  39770. }
  39771. ],
  39772. "dpi": [
  39773. 515.1,
  39774. 518
  39775. ],
  39776. "bw": 3,
  39777. "ac": 1000
  39778. },
  39779. {
  39780. "type": "android",
  39781. "rules": [
  39782. {
  39783. "mdmh": "samsung/*/SM-N910C/*"
  39784. },
  39785. {
  39786. "ua": "SM-N910C"
  39787. }
  39788. ],
  39789. "dpi": [
  39790. 515.2,
  39791. 520.2
  39792. ],
  39793. "bw": 3,
  39794. "ac": 500
  39795. },
  39796. {
  39797. "type": "android",
  39798. "rules": [
  39799. {
  39800. "mdmh": "samsung/*/SM-G130M/*"
  39801. },
  39802. {
  39803. "ua": "SM-G130M"
  39804. }
  39805. ],
  39806. "dpi": [
  39807. 165.9,
  39808. 164.8
  39809. ],
  39810. "bw": 3,
  39811. "ac": 500
  39812. },
  39813. {
  39814. "type": "android",
  39815. "rules": [
  39816. {
  39817. "mdmh": "samsung/*/SM-G928I/*"
  39818. },
  39819. {
  39820. "ua": "SM-G928I"
  39821. }
  39822. ],
  39823. "dpi": [
  39824. 515.1,
  39825. 518.4
  39826. ],
  39827. "bw": 3,
  39828. "ac": 1000
  39829. },
  39830. {
  39831. "type": "android",
  39832. "rules": [
  39833. {
  39834. "mdmh": "samsung/*/SM-G920F/*"
  39835. },
  39836. {
  39837. "ua": "SM-G920F"
  39838. }
  39839. ],
  39840. "dpi": 580.6,
  39841. "bw": 3,
  39842. "ac": 500
  39843. },
  39844. {
  39845. "type": "android",
  39846. "rules": [
  39847. {
  39848. "mdmh": "samsung/*/SM-G920P/*"
  39849. },
  39850. {
  39851. "ua": "SM-G920P"
  39852. }
  39853. ],
  39854. "dpi": [
  39855. 522.5,
  39856. 577
  39857. ],
  39858. "bw": 3,
  39859. "ac": 1000
  39860. },
  39861. {
  39862. "type": "android",
  39863. "rules": [
  39864. {
  39865. "mdmh": "samsung/*/SM-G925F/*"
  39866. },
  39867. {
  39868. "ua": "SM-G925F"
  39869. }
  39870. ],
  39871. "dpi": 580.6,
  39872. "bw": 3,
  39873. "ac": 500
  39874. },
  39875. {
  39876. "type": "android",
  39877. "rules": [
  39878. {
  39879. "mdmh": "samsung/*/SM-G925V/*"
  39880. },
  39881. {
  39882. "ua": "SM-G925V"
  39883. }
  39884. ],
  39885. "dpi": [
  39886. 522.5,
  39887. 576.6
  39888. ],
  39889. "bw": 3,
  39890. "ac": 1000
  39891. },
  39892. {
  39893. "type": "android",
  39894. "rules": [
  39895. {
  39896. "mdmh": "samsung/*/SM-G930F/*"
  39897. },
  39898. {
  39899. "ua": "SM-G930F"
  39900. }
  39901. ],
  39902. "dpi": 576.6,
  39903. "bw": 3,
  39904. "ac": 1000
  39905. },
  39906. {
  39907. "type": "android",
  39908. "rules": [
  39909. {
  39910. "mdmh": "samsung/*/SM-G935F/*"
  39911. },
  39912. {
  39913. "ua": "SM-G935F"
  39914. }
  39915. ],
  39916. "dpi": 533,
  39917. "bw": 3,
  39918. "ac": 500
  39919. },
  39920. {
  39921. "type": "android",
  39922. "rules": [
  39923. {
  39924. "mdmh": "samsung/*/SM-G950F/*"
  39925. },
  39926. {
  39927. "ua": "SM-G950F"
  39928. }
  39929. ],
  39930. "dpi": [
  39931. 562.707,
  39932. 565.293
  39933. ],
  39934. "bw": 3,
  39935. "ac": 500
  39936. },
  39937. {
  39938. "type": "android",
  39939. "rules": [
  39940. {
  39941. "mdmh": "samsung/*/SM-G955U/*"
  39942. },
  39943. {
  39944. "ua": "SM-G955U"
  39945. }
  39946. ],
  39947. "dpi": [
  39948. 522.514,
  39949. 525.762
  39950. ],
  39951. "bw": 3,
  39952. "ac": 500
  39953. },
  39954. {
  39955. "type": "android",
  39956. "rules": [
  39957. {
  39958. "mdmh": "Sony/*/C6903/*"
  39959. },
  39960. {
  39961. "ua": "C6903"
  39962. }
  39963. ],
  39964. "dpi": [
  39965. 442.5,
  39966. 443.3
  39967. ],
  39968. "bw": 3,
  39969. "ac": 500
  39970. },
  39971. {
  39972. "type": "android",
  39973. "rules": [
  39974. {
  39975. "mdmh": "Sony/*/D6653/*"
  39976. },
  39977. {
  39978. "ua": "D6653"
  39979. }
  39980. ],
  39981. "dpi": [
  39982. 428.6,
  39983. 427.6
  39984. ],
  39985. "bw": 3,
  39986. "ac": 1000
  39987. },
  39988. {
  39989. "type": "android",
  39990. "rules": [
  39991. {
  39992. "mdmh": "Sony/*/E6653/*"
  39993. },
  39994. {
  39995. "ua": "E6653"
  39996. }
  39997. ],
  39998. "dpi": [
  39999. 428.6,
  40000. 425.7
  40001. ],
  40002. "bw": 3,
  40003. "ac": 1000
  40004. },
  40005. {
  40006. "type": "android",
  40007. "rules": [
  40008. {
  40009. "mdmh": "Sony/*/E6853/*"
  40010. },
  40011. {
  40012. "ua": "E6853"
  40013. }
  40014. ],
  40015. "dpi": [
  40016. 403.4,
  40017. 401.9
  40018. ],
  40019. "bw": 3,
  40020. "ac": 1000
  40021. },
  40022. {
  40023. "type": "android",
  40024. "rules": [
  40025. {
  40026. "mdmh": "Sony/*/SGP321/*"
  40027. },
  40028. {
  40029. "ua": "SGP321"
  40030. }
  40031. ],
  40032. "dpi": [
  40033. 224.7,
  40034. 224.1
  40035. ],
  40036. "bw": 3,
  40037. "ac": 500
  40038. },
  40039. {
  40040. "type": "android",
  40041. "rules": [
  40042. {
  40043. "mdmh": "TCT/*/ALCATEL ONE TOUCH Fierce/*"
  40044. },
  40045. {
  40046. "ua": "ALCATEL ONE TOUCH Fierce"
  40047. }
  40048. ],
  40049. "dpi": [
  40050. 240,
  40051. 247.5
  40052. ],
  40053. "bw": 3,
  40054. "ac": 1000
  40055. },
  40056. {
  40057. "type": "android",
  40058. "rules": [
  40059. {
  40060. "mdmh": "THL/*/thl 5000/*"
  40061. },
  40062. {
  40063. "ua": "thl 5000"
  40064. }
  40065. ],
  40066. "dpi": [
  40067. 480,
  40068. 443.3
  40069. ],
  40070. "bw": 3,
  40071. "ac": 1000
  40072. },
  40073. {
  40074. "type": "android",
  40075. "rules": [
  40076. {
  40077. "mdmh": "ZTE/*/ZTE Blade L2/*"
  40078. },
  40079. {
  40080. "ua": "ZTE Blade L2"
  40081. }
  40082. ],
  40083. "dpi": 240,
  40084. "bw": 3,
  40085. "ac": 500
  40086. },
  40087. {
  40088. "type": "ios",
  40089. "rules": [
  40090. {
  40091. "res": [
  40092. 640,
  40093. 960
  40094. ]
  40095. }
  40096. ],
  40097. "dpi": [
  40098. 325.1,
  40099. 328.4
  40100. ],
  40101. "bw": 4,
  40102. "ac": 1000
  40103. },
  40104. {
  40105. "type": "ios",
  40106. "rules": [
  40107. {
  40108. "res": [
  40109. 640,
  40110. 1136
  40111. ]
  40112. }
  40113. ],
  40114. "dpi": [
  40115. 317.1,
  40116. 320.2
  40117. ],
  40118. "bw": 3,
  40119. "ac": 1000
  40120. },
  40121. {
  40122. "type": "ios",
  40123. "rules": [
  40124. {
  40125. "res": [
  40126. 750,
  40127. 1334
  40128. ]
  40129. }
  40130. ],
  40131. "dpi": 326.4,
  40132. "bw": 4,
  40133. "ac": 1000
  40134. },
  40135. {
  40136. "type": "ios",
  40137. "rules": [
  40138. {
  40139. "res": [
  40140. 1242,
  40141. 2208
  40142. ]
  40143. }
  40144. ],
  40145. "dpi": [
  40146. 453.6,
  40147. 458.4
  40148. ],
  40149. "bw": 4,
  40150. "ac": 1000
  40151. },
  40152. {
  40153. "type": "ios",
  40154. "rules": [
  40155. {
  40156. "res": [
  40157. 1125,
  40158. 2001
  40159. ]
  40160. }
  40161. ],
  40162. "dpi": [
  40163. 410.9,
  40164. 415.4
  40165. ],
  40166. "bw": 4,
  40167. "ac": 1000
  40168. }
  40169. ]
  40170. }
  40171. },{}],57:[function(_dereq_,module,exports){
  40172. /*
  40173. * Copyright 2015 Google Inc. All Rights Reserved.
  40174. * Licensed under the Apache License, Version 2.0 (the "License");
  40175. * you may not use this file except in compliance with the License.
  40176. * You may obtain a copy of the License at
  40177. *
  40178. * http://www.apache.org/licenses/LICENSE-2.0
  40179. *
  40180. * Unless required by applicable law or agreed to in writing, software
  40181. * distributed under the License is distributed on an "AS IS" BASIS,
  40182. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40183. * See the License for the specific language governing permissions and
  40184. * limitations under the License.
  40185. */
  40186. // Offline cache of the DPDB, to be used until we load the online one (and
  40187. // as a fallback in case we can't load the online one).
  40188. var DPDB_CACHE = _dereq_('./dpdb.json');
  40189. var Util = _dereq_('../util.js');
  40190. // Online DPDB URL.
  40191. var ONLINE_DPDB_URL =
  40192. 'https://dpdb.webvr.rocks/dpdb.json';
  40193. /**
  40194. * Calculates device parameters based on the DPDB (Device Parameter Database).
  40195. * Initially, uses the cached DPDB values.
  40196. *
  40197. * If fetchOnline == true, then this object tries to fetch the online version
  40198. * of the DPDB and updates the device info if a better match is found.
  40199. * Calls the onDeviceParamsUpdated callback when there is an update to the
  40200. * device information.
  40201. */
  40202. function Dpdb(fetchOnline, onDeviceParamsUpdated) {
  40203. // Start with the offline DPDB cache while we are loading the real one.
  40204. this.dpdb = DPDB_CACHE;
  40205. // Calculate device params based on the offline version of the DPDB.
  40206. this.recalculateDeviceParams_();
  40207. // XHR to fetch online DPDB file, if requested.
  40208. if (fetchOnline) {
  40209. // Set the callback.
  40210. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  40211. var xhr = new XMLHttpRequest();
  40212. var obj = this;
  40213. xhr.open('GET', ONLINE_DPDB_URL, true);
  40214. xhr.addEventListener('load', function() {
  40215. obj.loading = false;
  40216. if (xhr.status >= 200 && xhr.status <= 299) {
  40217. // Success.
  40218. obj.dpdb = JSON.parse(xhr.response);
  40219. obj.recalculateDeviceParams_();
  40220. } else {
  40221. // Error loading the DPDB.
  40222. console.error('Error loading online DPDB!');
  40223. }
  40224. });
  40225. xhr.send();
  40226. }
  40227. }
  40228. // Returns the current device parameters.
  40229. Dpdb.prototype.getDeviceParams = function() {
  40230. return this.deviceParams;
  40231. };
  40232. // Recalculates this device's parameters based on the DPDB.
  40233. Dpdb.prototype.recalculateDeviceParams_ = function() {
  40234. var newDeviceParams = this.calcDeviceParams_();
  40235. if (newDeviceParams) {
  40236. this.deviceParams = newDeviceParams;
  40237. // Invoke callback, if it is set.
  40238. if (this.onDeviceParamsUpdated) {
  40239. this.onDeviceParamsUpdated(this.deviceParams);
  40240. }
  40241. } else {
  40242. console.error('Failed to recalculate device parameters.');
  40243. }
  40244. };
  40245. // Returns a DeviceParams object that represents the best guess as to this
  40246. // device's parameters. Can return null if the device does not match any
  40247. // known devices.
  40248. Dpdb.prototype.calcDeviceParams_ = function() {
  40249. var db = this.dpdb; // shorthand
  40250. if (!db) {
  40251. console.error('DPDB not available.');
  40252. return null;
  40253. }
  40254. if (db.format != 1) {
  40255. console.error('DPDB has unexpected format version.');
  40256. return null;
  40257. }
  40258. if (!db.devices || !db.devices.length) {
  40259. console.error('DPDB does not have a devices section.');
  40260. return null;
  40261. }
  40262. // Get the actual user agent and screen dimensions in pixels.
  40263. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  40264. var width = Util.getScreenWidth();
  40265. var height = Util.getScreenHeight();
  40266. if (!db.devices) {
  40267. console.error('DPDB has no devices section.');
  40268. return null;
  40269. }
  40270. for (var i = 0; i < db.devices.length; i++) {
  40271. var device = db.devices[i];
  40272. if (!device.rules) {
  40273. console.warn('Device[' + i + '] has no rules section.');
  40274. continue;
  40275. }
  40276. if (device.type != 'ios' && device.type != 'android') {
  40277. console.warn('Device[' + i + '] has invalid type.');
  40278. continue;
  40279. }
  40280. // See if this device is of the appropriate type.
  40281. if (Util.isIOS() != (device.type == 'ios')) continue;
  40282. // See if this device matches any of the rules:
  40283. var matched = false;
  40284. for (var j = 0; j < device.rules.length; j++) {
  40285. var rule = device.rules[j];
  40286. if (this.matchRule_(rule, userAgent, width, height)) {
  40287. matched = true;
  40288. break;
  40289. }
  40290. }
  40291. if (!matched) continue;
  40292. // device.dpi might be an array of [ xdpi, ydpi] or just a scalar.
  40293. var xdpi = device.dpi[0] || device.dpi;
  40294. var ydpi = device.dpi[1] || device.dpi;
  40295. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  40296. }
  40297. console.warn('No DPDB device match.');
  40298. return null;
  40299. };
  40300. Dpdb.prototype.matchRule_ = function(rule, ua, screenWidth, screenHeight) {
  40301. // We can only match 'ua' and 'res' rules, not other types like 'mdmh'
  40302. // (which are meant for native platforms).
  40303. if (!rule.ua && !rule.res) return false;
  40304. // If our user agent string doesn't contain the indicated user agent string,
  40305. // the match fails.
  40306. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  40307. // If the rule specifies screen dimensions that don't correspond to ours,
  40308. // the match fails.
  40309. if (rule.res) {
  40310. if (!rule.res[0] || !rule.res[1]) return false;
  40311. var resX = rule.res[0];
  40312. var resY = rule.res[1];
  40313. // Compare min and max so as to make the order not matter, i.e., it should
  40314. // be true that 640x480 == 480x640.
  40315. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) ||
  40316. (Math.max(screenWidth, screenHeight) != Math.max(resX, resY))) {
  40317. return false;
  40318. }
  40319. }
  40320. return true;
  40321. }
  40322. function DeviceParams(params) {
  40323. this.xdpi = params.xdpi;
  40324. this.ydpi = params.ydpi;
  40325. this.bevelMm = params.bevelMm;
  40326. }
  40327. module.exports = Dpdb;
  40328. },{"../util.js":68,"./dpdb.json":56}],58:[function(_dereq_,module,exports){
  40329. /*
  40330. * Copyright 2015 Google Inc. All Rights Reserved.
  40331. * Licensed under the Apache License, Version 2.0 (the "License");
  40332. * you may not use this file except in compliance with the License.
  40333. * You may obtain a copy of the License at
  40334. *
  40335. * http://www.apache.org/licenses/LICENSE-2.0
  40336. *
  40337. * Unless required by applicable law or agreed to in writing, software
  40338. * distributed under the License is distributed on an "AS IS" BASIS,
  40339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40340. * See the License for the specific language governing permissions and
  40341. * limitations under the License.
  40342. */
  40343. var Util = _dereq_('./util.js');
  40344. var WebVRPolyfill = _dereq_('./webvr-polyfill.js').WebVRPolyfill;
  40345. // Initialize a WebVRConfig just in case.
  40346. window.WebVRConfig = Util.extend({
  40347. // Forces availability of VR mode, even for non-mobile devices.
  40348. FORCE_ENABLE_VR: false,
  40349. // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  40350. K_FILTER: 0.98,
  40351. // How far into the future to predict during fast motion (in seconds).
  40352. PREDICTION_TIME_S: 0.040,
  40353. // Flag to enable touch panner. In case you have your own touch controls.
  40354. TOUCH_PANNER_DISABLED: true,
  40355. // Flag to disabled the UI in VR Mode.
  40356. CARDBOARD_UI_DISABLED: false, // Default: false
  40357. // Flag to disable the instructions to rotate your device.
  40358. ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.
  40359. // Enable yaw panning only, disabling roll and pitch. This can be useful
  40360. // for panoramas with nothing interesting above or below.
  40361. YAW_ONLY: false,
  40362. // To disable keyboard and mouse controls, if you want to use your own
  40363. // implementation.
  40364. MOUSE_KEYBOARD_CONTROLS_DISABLED: false,
  40365. // Prevent the polyfill from initializing immediately. Requires the app
  40366. // to call InitializeWebVRPolyfill() before it can be used.
  40367. DEFER_INITIALIZATION: false,
  40368. // Enable the deprecated version of the API (navigator.getVRDevices).
  40369. ENABLE_DEPRECATED_API: false,
  40370. // Scales the recommended buffer size reported by WebVR, which can improve
  40371. // performance.
  40372. // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  40373. // perform well on many mobile devices.
  40374. BUFFER_SCALE: 0.5,
  40375. // Allow VRDisplay.submitFrame to change gl bindings, which is more
  40376. // efficient if the application code will re-bind its resources on the
  40377. // next frame anyway. This has been seen to cause rendering glitches with
  40378. // THREE.js.
  40379. // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  40380. // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  40381. // and gl.TEXTURE_BINDING_2D for texture unit 0.
  40382. DIRTY_SUBMIT_FRAME_BINDINGS: false,
  40383. // When set to true, this will cause a polyfilled VRDisplay to always be
  40384. // appended to the list returned by navigator.getVRDisplays(), even if that
  40385. // list includes a native VRDisplay.
  40386. ALWAYS_APPEND_POLYFILL_DISPLAY: false,
  40387. // There are versions of Chrome (M58-M60?) where the native WebVR API exists,
  40388. // and instead of returning 0 VR displays when none are detected,
  40389. // `navigator.getVRDisplays()`'s promise never resolves. This results
  40390. // in the polyfill hanging and not being able to provide fallback
  40391. // displays, so set a timeout in milliseconds to stop waiting for a response
  40392. // and just use polyfilled displays.
  40393. // https://bugs.chromium.org/p/chromium/issues/detail?id=727969
  40394. GET_VR_DISPLAYS_TIMEOUT: 1000,
  40395. }, window.WebVRConfig);
  40396. if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  40397. new WebVRPolyfill();
  40398. } else {
  40399. window.InitializeWebVRPolyfill = function() {
  40400. new WebVRPolyfill();
  40401. }
  40402. }
  40403. window.WebVRPolyfill = WebVRPolyfill;
  40404. },{"./util.js":68,"./webvr-polyfill.js":71}],59:[function(_dereq_,module,exports){
  40405. /*
  40406. * Copyright 2016 Google Inc. All Rights Reserved.
  40407. * Licensed under the Apache License, Version 2.0 (the "License");
  40408. * you may not use this file except in compliance with the License.
  40409. * You may obtain a copy of the License at
  40410. *
  40411. * http://www.apache.org/licenses/LICENSE-2.0
  40412. *
  40413. * Unless required by applicable law or agreed to in writing, software
  40414. * distributed under the License is distributed on an "AS IS" BASIS,
  40415. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40416. * See the License for the specific language governing permissions and
  40417. * limitations under the License.
  40418. */
  40419. var MathUtil = window.MathUtil || {};
  40420. MathUtil.degToRad = Math.PI / 180;
  40421. MathUtil.radToDeg = 180 / Math.PI;
  40422. // Some minimal math functionality borrowed from THREE.Math and stripped down
  40423. // for the purposes of this library.
  40424. MathUtil.Vector2 = function ( x, y ) {
  40425. this.x = x || 0;
  40426. this.y = y || 0;
  40427. };
  40428. MathUtil.Vector2.prototype = {
  40429. constructor: MathUtil.Vector2,
  40430. set: function ( x, y ) {
  40431. this.x = x;
  40432. this.y = y;
  40433. return this;
  40434. },
  40435. copy: function ( v ) {
  40436. this.x = v.x;
  40437. this.y = v.y;
  40438. return this;
  40439. },
  40440. subVectors: function ( a, b ) {
  40441. this.x = a.x - b.x;
  40442. this.y = a.y - b.y;
  40443. return this;
  40444. },
  40445. };
  40446. MathUtil.Vector3 = function ( x, y, z ) {
  40447. this.x = x || 0;
  40448. this.y = y || 0;
  40449. this.z = z || 0;
  40450. };
  40451. MathUtil.Vector3.prototype = {
  40452. constructor: MathUtil.Vector3,
  40453. set: function ( x, y, z ) {
  40454. this.x = x;
  40455. this.y = y;
  40456. this.z = z;
  40457. return this;
  40458. },
  40459. copy: function ( v ) {
  40460. this.x = v.x;
  40461. this.y = v.y;
  40462. this.z = v.z;
  40463. return this;
  40464. },
  40465. length: function () {
  40466. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  40467. },
  40468. normalize: function () {
  40469. var scalar = this.length();
  40470. if ( scalar !== 0 ) {
  40471. var invScalar = 1 / scalar;
  40472. this.multiplyScalar(invScalar);
  40473. } else {
  40474. this.x = 0;
  40475. this.y = 0;
  40476. this.z = 0;
  40477. }
  40478. return this;
  40479. },
  40480. multiplyScalar: function ( scalar ) {
  40481. this.x *= scalar;
  40482. this.y *= scalar;
  40483. this.z *= scalar;
  40484. },
  40485. applyQuaternion: function ( q ) {
  40486. var x = this.x;
  40487. var y = this.y;
  40488. var z = this.z;
  40489. var qx = q.x;
  40490. var qy = q.y;
  40491. var qz = q.z;
  40492. var qw = q.w;
  40493. // calculate quat * vector
  40494. var ix = qw * x + qy * z - qz * y;
  40495. var iy = qw * y + qz * x - qx * z;
  40496. var iz = qw * z + qx * y - qy * x;
  40497. var iw = - qx * x - qy * y - qz * z;
  40498. // calculate result * inverse quat
  40499. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  40500. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  40501. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  40502. return this;
  40503. },
  40504. dot: function ( v ) {
  40505. return this.x * v.x + this.y * v.y + this.z * v.z;
  40506. },
  40507. crossVectors: function ( a, b ) {
  40508. var ax = a.x, ay = a.y, az = a.z;
  40509. var bx = b.x, by = b.y, bz = b.z;
  40510. this.x = ay * bz - az * by;
  40511. this.y = az * bx - ax * bz;
  40512. this.z = ax * by - ay * bx;
  40513. return this;
  40514. },
  40515. };
  40516. MathUtil.Quaternion = function ( x, y, z, w ) {
  40517. this.x = x || 0;
  40518. this.y = y || 0;
  40519. this.z = z || 0;
  40520. this.w = ( w !== undefined ) ? w : 1;
  40521. };
  40522. MathUtil.Quaternion.prototype = {
  40523. constructor: MathUtil.Quaternion,
  40524. set: function ( x, y, z, w ) {
  40525. this.x = x;
  40526. this.y = y;
  40527. this.z = z;
  40528. this.w = w;
  40529. return this;
  40530. },
  40531. copy: function ( quaternion ) {
  40532. this.x = quaternion.x;
  40533. this.y = quaternion.y;
  40534. this.z = quaternion.z;
  40535. this.w = quaternion.w;
  40536. return this;
  40537. },
  40538. setFromEulerXYZ: function( x, y, z ) {
  40539. var c1 = Math.cos( x / 2 );
  40540. var c2 = Math.cos( y / 2 );
  40541. var c3 = Math.cos( z / 2 );
  40542. var s1 = Math.sin( x / 2 );
  40543. var s2 = Math.sin( y / 2 );
  40544. var s3 = Math.sin( z / 2 );
  40545. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40546. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40547. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  40548. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  40549. return this;
  40550. },
  40551. setFromEulerYXZ: function( x, y, z ) {
  40552. var c1 = Math.cos( x / 2 );
  40553. var c2 = Math.cos( y / 2 );
  40554. var c3 = Math.cos( z / 2 );
  40555. var s1 = Math.sin( x / 2 );
  40556. var s2 = Math.sin( y / 2 );
  40557. var s3 = Math.sin( z / 2 );
  40558. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  40559. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  40560. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  40561. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  40562. return this;
  40563. },
  40564. setFromAxisAngle: function ( axis, angle ) {
  40565. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  40566. // assumes axis is normalized
  40567. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  40568. this.x = axis.x * s;
  40569. this.y = axis.y * s;
  40570. this.z = axis.z * s;
  40571. this.w = Math.cos( halfAngle );
  40572. return this;
  40573. },
  40574. multiply: function ( q ) {
  40575. return this.multiplyQuaternions( this, q );
  40576. },
  40577. multiplyQuaternions: function ( a, b ) {
  40578. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  40579. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  40580. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  40581. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  40582. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  40583. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  40584. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  40585. return this;
  40586. },
  40587. inverse: function () {
  40588. this.x *= -1;
  40589. this.y *= -1;
  40590. this.z *= -1;
  40591. this.normalize();
  40592. return this;
  40593. },
  40594. normalize: function () {
  40595. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  40596. if ( l === 0 ) {
  40597. this.x = 0;
  40598. this.y = 0;
  40599. this.z = 0;
  40600. this.w = 1;
  40601. } else {
  40602. l = 1 / l;
  40603. this.x = this.x * l;
  40604. this.y = this.y * l;
  40605. this.z = this.z * l;
  40606. this.w = this.w * l;
  40607. }
  40608. return this;
  40609. },
  40610. slerp: function ( qb, t ) {
  40611. if ( t === 0 ) return this;
  40612. if ( t === 1 ) return this.copy( qb );
  40613. var x = this.x, y = this.y, z = this.z, w = this.w;
  40614. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  40615. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  40616. if ( cosHalfTheta < 0 ) {
  40617. this.w = - qb.w;
  40618. this.x = - qb.x;
  40619. this.y = - qb.y;
  40620. this.z = - qb.z;
  40621. cosHalfTheta = - cosHalfTheta;
  40622. } else {
  40623. this.copy( qb );
  40624. }
  40625. if ( cosHalfTheta >= 1.0 ) {
  40626. this.w = w;
  40627. this.x = x;
  40628. this.y = y;
  40629. this.z = z;
  40630. return this;
  40631. }
  40632. var halfTheta = Math.acos( cosHalfTheta );
  40633. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  40634. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  40635. this.w = 0.5 * ( w + this.w );
  40636. this.x = 0.5 * ( x + this.x );
  40637. this.y = 0.5 * ( y + this.y );
  40638. this.z = 0.5 * ( z + this.z );
  40639. return this;
  40640. }
  40641. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  40642. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  40643. this.w = ( w * ratioA + this.w * ratioB );
  40644. this.x = ( x * ratioA + this.x * ratioB );
  40645. this.y = ( y * ratioA + this.y * ratioB );
  40646. this.z = ( z * ratioA + this.z * ratioB );
  40647. return this;
  40648. },
  40649. setFromUnitVectors: function () {
  40650. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  40651. // assumes direction vectors vFrom and vTo are normalized
  40652. var v1, r;
  40653. var EPS = 0.000001;
  40654. return function ( vFrom, vTo ) {
  40655. if ( v1 === undefined ) v1 = new MathUtil.Vector3();
  40656. r = vFrom.dot( vTo ) + 1;
  40657. if ( r < EPS ) {
  40658. r = 0;
  40659. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  40660. v1.set( - vFrom.y, vFrom.x, 0 );
  40661. } else {
  40662. v1.set( 0, - vFrom.z, vFrom.y );
  40663. }
  40664. } else {
  40665. v1.crossVectors( vFrom, vTo );
  40666. }
  40667. this.x = v1.x;
  40668. this.y = v1.y;
  40669. this.z = v1.z;
  40670. this.w = r;
  40671. this.normalize();
  40672. return this;
  40673. }
  40674. }(),
  40675. };
  40676. module.exports = MathUtil;
  40677. },{}],60:[function(_dereq_,module,exports){
  40678. /*
  40679. * Copyright 2016 Google Inc. All Rights Reserved.
  40680. * Licensed under the Apache License, Version 2.0 (the "License");
  40681. * you may not use this file except in compliance with the License.
  40682. * You may obtain a copy of the License at
  40683. *
  40684. * http://www.apache.org/licenses/LICENSE-2.0
  40685. *
  40686. * Unless required by applicable law or agreed to in writing, software
  40687. * distributed under the License is distributed on an "AS IS" BASIS,
  40688. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40689. * See the License for the specific language governing permissions and
  40690. * limitations under the License.
  40691. */
  40692. var VRDisplay = _dereq_('./base.js').VRDisplay;
  40693. var MathUtil = _dereq_('./math-util.js');
  40694. var Util = _dereq_('./util.js');
  40695. // How much to rotate per key stroke.
  40696. var KEY_SPEED = 0.15;
  40697. var KEY_ANIMATION_DURATION = 80;
  40698. // How much to rotate for mouse events.
  40699. var MOUSE_SPEED_X = 0.5;
  40700. var MOUSE_SPEED_Y = 0.3;
  40701. /**
  40702. * VRDisplay based on mouse and keyboard input. Designed for desktops/laptops
  40703. * where orientation events aren't supported. Cannot present.
  40704. */
  40705. function MouseKeyboardVRDisplay() {
  40706. this.displayName = 'Mouse and Keyboard VRDisplay (webvr-polyfill)';
  40707. this.capabilities.hasOrientation = true;
  40708. // Attach to mouse and keyboard events.
  40709. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  40710. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  40711. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  40712. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  40713. // "Private" members.
  40714. this.phi_ = 0;
  40715. this.theta_ = 0;
  40716. // Variables for keyboard-based rotation animation.
  40717. this.targetAngle_ = null;
  40718. this.angleAnimation_ = null;
  40719. // State variables for calculations.
  40720. this.orientation_ = new MathUtil.Quaternion();
  40721. // Variables for mouse-based rotation.
  40722. this.rotateStart_ = new MathUtil.Vector2();
  40723. this.rotateEnd_ = new MathUtil.Vector2();
  40724. this.rotateDelta_ = new MathUtil.Vector2();
  40725. this.isDragging_ = false;
  40726. this.orientationOut_ = new Float32Array(4);
  40727. }
  40728. MouseKeyboardVRDisplay.prototype = new VRDisplay();
  40729. MouseKeyboardVRDisplay.prototype.getImmediatePose = function() {
  40730. this.orientation_.setFromEulerYXZ(this.phi_, this.theta_, 0);
  40731. this.orientationOut_[0] = this.orientation_.x;
  40732. this.orientationOut_[1] = this.orientation_.y;
  40733. this.orientationOut_[2] = this.orientation_.z;
  40734. this.orientationOut_[3] = this.orientation_.w;
  40735. return {
  40736. position: null,
  40737. orientation: this.orientationOut_,
  40738. linearVelocity: null,
  40739. linearAcceleration: null,
  40740. angularVelocity: null,
  40741. angularAcceleration: null
  40742. };
  40743. };
  40744. MouseKeyboardVRDisplay.prototype.onKeyDown_ = function(e) {
  40745. // Track WASD and arrow keys.
  40746. if (e.keyCode == 38) { // Up key.
  40747. this.animatePhi_(this.phi_ + KEY_SPEED);
  40748. } else if (e.keyCode == 39) { // Right key.
  40749. this.animateTheta_(this.theta_ - KEY_SPEED);
  40750. } else if (e.keyCode == 40) { // Down key.
  40751. this.animatePhi_(this.phi_ - KEY_SPEED);
  40752. } else if (e.keyCode == 37) { // Left key.
  40753. this.animateTheta_(this.theta_ + KEY_SPEED);
  40754. }
  40755. };
  40756. MouseKeyboardVRDisplay.prototype.animateTheta_ = function(targetAngle) {
  40757. this.animateKeyTransitions_('theta_', targetAngle);
  40758. };
  40759. MouseKeyboardVRDisplay.prototype.animatePhi_ = function(targetAngle) {
  40760. // Prevent looking too far up or down.
  40761. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  40762. this.animateKeyTransitions_('phi_', targetAngle);
  40763. };
  40764. /**
  40765. * Start an animation to transition an angle from one value to another.
  40766. */
  40767. MouseKeyboardVRDisplay.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  40768. // If an animation is currently running, cancel it.
  40769. if (this.angleAnimation_) {
  40770. cancelAnimationFrame(this.angleAnimation_);
  40771. }
  40772. var startAngle = this[angleName];
  40773. var startTime = new Date();
  40774. // Set up an interval timer to perform the animation.
  40775. this.angleAnimation_ = requestAnimationFrame(function animate() {
  40776. // Once we're finished the animation, we're done.
  40777. var elapsed = new Date() - startTime;
  40778. if (elapsed >= KEY_ANIMATION_DURATION) {
  40779. this[angleName] = targetAngle;
  40780. cancelAnimationFrame(this.angleAnimation_);
  40781. return;
  40782. }
  40783. // loop with requestAnimationFrame
  40784. this.angleAnimation_ = requestAnimationFrame(animate.bind(this))
  40785. // Linearly interpolate the angle some amount.
  40786. var percent = elapsed / KEY_ANIMATION_DURATION;
  40787. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  40788. }.bind(this));
  40789. };
  40790. MouseKeyboardVRDisplay.prototype.onMouseDown_ = function(e) {
  40791. this.rotateStart_.set(e.clientX, e.clientY);
  40792. this.isDragging_ = true;
  40793. };
  40794. // Very similar to https://gist.github.com/mrflix/8351020
  40795. MouseKeyboardVRDisplay.prototype.onMouseMove_ = function(e) {
  40796. if (!this.isDragging_ && !this.isPointerLocked_()) {
  40797. return;
  40798. }
  40799. // Support pointer lock API.
  40800. if (this.isPointerLocked_()) {
  40801. var movementX = e.movementX || e.mozMovementX || 0;
  40802. var movementY = e.movementY || e.mozMovementY || 0;
  40803. this.rotateEnd_.set(this.rotateStart_.x - movementX, this.rotateStart_.y - movementY);
  40804. } else {
  40805. this.rotateEnd_.set(e.clientX, e.clientY);
  40806. }
  40807. // Calculate how much we moved in mouse space.
  40808. this.rotateDelta_.subVectors(this.rotateEnd_, this.rotateStart_);
  40809. this.rotateStart_.copy(this.rotateEnd_);
  40810. // Keep track of the cumulative euler angles.
  40811. this.phi_ += 2 * Math.PI * this.rotateDelta_.y / screen.height * MOUSE_SPEED_Y;
  40812. this.theta_ += 2 * Math.PI * this.rotateDelta_.x / screen.width * MOUSE_SPEED_X;
  40813. // Prevent looking too far up or down.
  40814. this.phi_ = Util.clamp(this.phi_, -Math.PI/2, Math.PI/2);
  40815. };
  40816. MouseKeyboardVRDisplay.prototype.onMouseUp_ = function(e) {
  40817. this.isDragging_ = false;
  40818. };
  40819. MouseKeyboardVRDisplay.prototype.isPointerLocked_ = function() {
  40820. var el = document.pointerLockElement || document.mozPointerLockElement ||
  40821. document.webkitPointerLockElement;
  40822. return el !== undefined;
  40823. };
  40824. MouseKeyboardVRDisplay.prototype.resetPose = function() {
  40825. this.phi_ = 0;
  40826. this.theta_ = 0;
  40827. };
  40828. module.exports = MouseKeyboardVRDisplay;
  40829. },{"./base.js":48,"./math-util.js":59,"./util.js":68}],61:[function(_dereq_,module,exports){
  40830. (function (global){
  40831. // This is the entry point if requiring/importing via node, or
  40832. // a build tool that uses package.json entry (like browserify, webpack).
  40833. // If running in node with a window mock available, globalize its members
  40834. // if needed. Otherwise, just continue to `./main`
  40835. if (typeof global !== 'undefined' && global.window) {
  40836. global.document = global.window.document;
  40837. global.navigator = global.window.navigator;
  40838. }
  40839. _dereq_('./main');
  40840. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  40841. },{"./main":58}],62:[function(_dereq_,module,exports){
  40842. /*
  40843. * Copyright 2015 Google Inc. All Rights Reserved.
  40844. * Licensed under the Apache License, Version 2.0 (the "License");
  40845. * you may not use this file except in compliance with the License.
  40846. * You may obtain a copy of the License at
  40847. *
  40848. * http://www.apache.org/licenses/LICENSE-2.0
  40849. *
  40850. * Unless required by applicable law or agreed to in writing, software
  40851. * distributed under the License is distributed on an "AS IS" BASIS,
  40852. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40853. * See the License for the specific language governing permissions and
  40854. * limitations under the License.
  40855. */
  40856. var Util = _dereq_('./util.js');
  40857. function RotateInstructions() {
  40858. this.loadIcon_();
  40859. var overlay = document.createElement('div');
  40860. var s = overlay.style;
  40861. s.position = 'fixed';
  40862. s.top = 0;
  40863. s.right = 0;
  40864. s.bottom = 0;
  40865. s.left = 0;
  40866. s.backgroundColor = 'gray';
  40867. s.fontFamily = 'sans-serif';
  40868. // Force this to be above the fullscreen canvas, which is at zIndex: 999999.
  40869. s.zIndex = 1000000;
  40870. var img = document.createElement('img');
  40871. img.src = this.icon;
  40872. var s = img.style;
  40873. s.marginLeft = '25%';
  40874. s.marginTop = '25%';
  40875. s.width = '50%';
  40876. overlay.appendChild(img);
  40877. var text = document.createElement('div');
  40878. var s = text.style;
  40879. s.textAlign = 'center';
  40880. s.fontSize = '16px';
  40881. s.lineHeight = '24px';
  40882. s.margin = '24px 25%';
  40883. s.width = '50%';
  40884. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  40885. overlay.appendChild(text);
  40886. var snackbar = document.createElement('div');
  40887. var s = snackbar.style;
  40888. s.backgroundColor = '#CFD8DC';
  40889. s.position = 'fixed';
  40890. s.bottom = 0;
  40891. s.width = '100%';
  40892. s.height = '48px';
  40893. s.padding = '14px 24px';
  40894. s.boxSizing = 'border-box';
  40895. s.color = '#656A6B';
  40896. overlay.appendChild(snackbar);
  40897. var snackbarText = document.createElement('div');
  40898. snackbarText.style.float = 'left';
  40899. snackbarText.innerHTML = 'No Cardboard viewer?';
  40900. var snackbarButton = document.createElement('a');
  40901. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  40902. snackbarButton.innerHTML = 'get one';
  40903. snackbarButton.target = '_blank';
  40904. var s = snackbarButton.style;
  40905. s.float = 'right';
  40906. s.fontWeight = 600;
  40907. s.textTransform = 'uppercase';
  40908. s.borderLeft = '1px solid gray';
  40909. s.paddingLeft = '24px';
  40910. s.textDecoration = 'none';
  40911. s.color = '#656A6B';
  40912. snackbar.appendChild(snackbarText);
  40913. snackbar.appendChild(snackbarButton);
  40914. this.overlay = overlay;
  40915. this.text = text;
  40916. this.hide();
  40917. }
  40918. RotateInstructions.prototype.show = function(parent) {
  40919. if (!parent && !this.overlay.parentElement) {
  40920. document.body.appendChild(this.overlay);
  40921. } else if (parent) {
  40922. if (this.overlay.parentElement && this.overlay.parentElement != parent)
  40923. this.overlay.parentElement.removeChild(this.overlay);
  40924. parent.appendChild(this.overlay);
  40925. }
  40926. this.overlay.style.display = 'block';
  40927. var img = this.overlay.querySelector('img');
  40928. var s = img.style;
  40929. if (Util.isLandscapeMode()) {
  40930. s.width = '20%';
  40931. s.marginLeft = '40%';
  40932. s.marginTop = '3%';
  40933. } else {
  40934. s.width = '50%';
  40935. s.marginLeft = '25%';
  40936. s.marginTop = '25%';
  40937. }
  40938. };
  40939. RotateInstructions.prototype.hide = function() {
  40940. this.overlay.style.display = 'none';
  40941. };
  40942. RotateInstructions.prototype.showTemporarily = function(ms, parent) {
  40943. this.show(parent);
  40944. this.timer = setTimeout(this.hide.bind(this), ms);
  40945. };
  40946. RotateInstructions.prototype.disableShowTemporarily = function() {
  40947. clearTimeout(this.timer);
  40948. };
  40949. RotateInstructions.prototype.update = function() {
  40950. this.disableShowTemporarily();
  40951. // In portrait VR mode, tell the user to rotate to landscape. Otherwise, hide
  40952. // the instructions.
  40953. if (!Util.isLandscapeMode() && Util.isMobile()) {
  40954. this.show();
  40955. } else {
  40956. this.hide();
  40957. }
  40958. };
  40959. RotateInstructions.prototype.loadIcon_ = function() {
  40960. // Encoded asset_src/rotate-instructions.svg
  40961. this.icon = Util.base64('image/svg+xml', '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+');
  40962. };
  40963. module.exports = RotateInstructions;
  40964. },{"./util.js":68}],63:[function(_dereq_,module,exports){
  40965. /*
  40966. * Copyright 2015 Google Inc. All Rights Reserved.
  40967. * Licensed under the Apache License, Version 2.0 (the "License");
  40968. * you may not use this file except in compliance with the License.
  40969. * You may obtain a copy of the License at
  40970. *
  40971. * http://www.apache.org/licenses/LICENSE-2.0
  40972. *
  40973. * Unless required by applicable law or agreed to in writing, software
  40974. * distributed under the License is distributed on an "AS IS" BASIS,
  40975. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40976. * See the License for the specific language governing permissions and
  40977. * limitations under the License.
  40978. */
  40979. var SensorSample = _dereq_('./sensor-sample.js');
  40980. var MathUtil = _dereq_('../math-util.js');
  40981. var Util = _dereq_('../util.js');
  40982. /**
  40983. * An implementation of a simple complementary filter, which fuses gyroscope and
  40984. * accelerometer data from the 'devicemotion' event.
  40985. *
  40986. * Accelerometer data is very noisy, but stable over the long term.
  40987. * Gyroscope data is smooth, but tends to drift over the long term.
  40988. *
  40989. * This fusion is relatively simple:
  40990. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  40991. * on that data.
  40992. * 2. Get orientation estimates from gyroscope by integrating over time.
  40993. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  40994. * short term.
  40995. */
  40996. function ComplementaryFilter(kFilter) {
  40997. this.kFilter = kFilter;
  40998. // Raw sensor measurements.
  40999. this.currentAccelMeasurement = new SensorSample();
  41000. this.currentGyroMeasurement = new SensorSample();
  41001. this.previousGyroMeasurement = new SensorSample();
  41002. // Set default look direction to be in the correct direction.
  41003. if (Util.isIOS()) {
  41004. this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1);
  41005. } else {
  41006. this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1);
  41007. }
  41008. this.previousFilterQ = new MathUtil.Quaternion();
  41009. this.previousFilterQ.copy(this.filterQ);
  41010. // Orientation based on the accelerometer.
  41011. this.accelQ = new MathUtil.Quaternion();
  41012. // Whether or not the orientation has been initialized.
  41013. this.isOrientationInitialized = false;
  41014. // Running estimate of gravity based on the current orientation.
  41015. this.estimatedGravity = new MathUtil.Vector3();
  41016. // Measured gravity based on accelerometer.
  41017. this.measuredGravity = new MathUtil.Vector3();
  41018. // Debug only quaternion of gyro-based orientation.
  41019. this.gyroIntegralQ = new MathUtil.Quaternion();
  41020. }
  41021. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  41022. this.currentAccelMeasurement.set(vector, timestampS);
  41023. };
  41024. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  41025. this.currentGyroMeasurement.set(vector, timestampS);
  41026. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  41027. if (Util.isTimestampDeltaValid(deltaT)) {
  41028. this.run_();
  41029. }
  41030. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  41031. };
  41032. ComplementaryFilter.prototype.run_ = function() {
  41033. if (!this.isOrientationInitialized) {
  41034. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  41035. this.previousFilterQ.copy(this.accelQ);
  41036. this.isOrientationInitialized = true;
  41037. return;
  41038. }
  41039. var deltaT = this.currentGyroMeasurement.timestampS -
  41040. this.previousGyroMeasurement.timestampS;
  41041. // Convert gyro rotation vector to a quaternion delta.
  41042. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  41043. this.gyroIntegralQ.multiply(gyroDeltaQ);
  41044. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  41045. this.filterQ.copy(this.previousFilterQ);
  41046. this.filterQ.multiply(gyroDeltaQ);
  41047. // Calculate the delta between the current estimated gravity and the real
  41048. // gravity vector from accelerometer.
  41049. var invFilterQ = new MathUtil.Quaternion();
  41050. invFilterQ.copy(this.filterQ);
  41051. invFilterQ.inverse();
  41052. this.estimatedGravity.set(0, 0, -1);
  41053. this.estimatedGravity.applyQuaternion(invFilterQ);
  41054. this.estimatedGravity.normalize();
  41055. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  41056. this.measuredGravity.normalize();
  41057. // Compare estimated gravity with measured gravity, get the delta quaternion
  41058. // between the two.
  41059. var deltaQ = new MathUtil.Quaternion();
  41060. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  41061. deltaQ.inverse();
  41062. if (Util.isDebug()) {
  41063. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  41064. MathUtil.radToDeg * Util.getQuaternionAngle(deltaQ),
  41065. (this.estimatedGravity.x).toFixed(1),
  41066. (this.estimatedGravity.y).toFixed(1),
  41067. (this.estimatedGravity.z).toFixed(1),
  41068. (this.measuredGravity.x).toFixed(1),
  41069. (this.measuredGravity.y).toFixed(1),
  41070. (this.measuredGravity.z).toFixed(1));
  41071. }
  41072. // Calculate the SLERP target: current orientation plus the measured-estimated
  41073. // quaternion delta.
  41074. var targetQ = new MathUtil.Quaternion();
  41075. targetQ.copy(this.filterQ);
  41076. targetQ.multiply(deltaQ);
  41077. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  41078. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  41079. this.previousFilterQ.copy(this.filterQ);
  41080. };
  41081. ComplementaryFilter.prototype.getOrientation = function() {
  41082. return this.filterQ;
  41083. };
  41084. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  41085. var normAccel = new MathUtil.Vector3();
  41086. normAccel.copy(accel);
  41087. normAccel.normalize();
  41088. var quat = new MathUtil.Quaternion();
  41089. quat.setFromUnitVectors(new MathUtil.Vector3(0, 0, -1), normAccel);
  41090. quat.inverse();
  41091. return quat;
  41092. };
  41093. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  41094. // Extract axis and angle from the gyroscope data.
  41095. var quat = new MathUtil.Quaternion();
  41096. var axis = new MathUtil.Vector3();
  41097. axis.copy(gyro);
  41098. axis.normalize();
  41099. quat.setFromAxisAngle(axis, gyro.length() * dt);
  41100. return quat;
  41101. };
  41102. module.exports = ComplementaryFilter;
  41103. },{"../math-util.js":59,"../util.js":68,"./sensor-sample.js":66}],64:[function(_dereq_,module,exports){
  41104. /*
  41105. * Copyright 2015 Google Inc. All Rights Reserved.
  41106. * Licensed under the Apache License, Version 2.0 (the "License");
  41107. * you may not use this file except in compliance with the License.
  41108. * You may obtain a copy of the License at
  41109. *
  41110. * http://www.apache.org/licenses/LICENSE-2.0
  41111. *
  41112. * Unless required by applicable law or agreed to in writing, software
  41113. * distributed under the License is distributed on an "AS IS" BASIS,
  41114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41115. * See the License for the specific language governing permissions and
  41116. * limitations under the License.
  41117. */
  41118. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  41119. var PosePredictor = _dereq_('./pose-predictor.js');
  41120. var TouchPanner = _dereq_('../touch-panner.js');
  41121. var MathUtil = _dereq_('../math-util.js');
  41122. var Util = _dereq_('../util.js');
  41123. /**
  41124. * The pose sensor, implemented using DeviceMotion APIs.
  41125. */
  41126. function FusionPoseSensor() {
  41127. this.deviceId = 'webvr-polyfill:fused';
  41128. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  41129. this.accelerometer = new MathUtil.Vector3();
  41130. this.gyroscope = new MathUtil.Vector3();
  41131. this.start();
  41132. this.filter = new ComplementaryFilter(window.WebVRConfig.K_FILTER);
  41133. this.posePredictor = new PosePredictor(window.WebVRConfig.PREDICTION_TIME_S);
  41134. this.touchPanner = new TouchPanner();
  41135. this.filterToWorldQ = new MathUtil.Quaternion();
  41136. // Set the filter to world transform, depending on OS.
  41137. if (Util.isIOS()) {
  41138. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2);
  41139. } else {
  41140. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2);
  41141. }
  41142. this.inverseWorldToScreenQ = new MathUtil.Quaternion();
  41143. this.worldToScreenQ = new MathUtil.Quaternion();
  41144. this.originalPoseAdjustQ = new MathUtil.Quaternion();
  41145. this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1),
  41146. -window.orientation * Math.PI / 180);
  41147. this.setScreenTransform_();
  41148. // Adjust this filter for being in landscape mode.
  41149. if (Util.isLandscapeMode()) {
  41150. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  41151. }
  41152. // Keep track of a reset transform for resetSensor.
  41153. this.resetQ = new MathUtil.Quaternion();
  41154. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  41155. this.isIOS = Util.isIOS();
  41156. this.orientationOut_ = new Float32Array(4);
  41157. }
  41158. FusionPoseSensor.prototype.getPosition = function() {
  41159. // This PoseSensor doesn't support position
  41160. return null;
  41161. };
  41162. FusionPoseSensor.prototype.getOrientation = function() {
  41163. // Convert from filter space to the the same system used by the
  41164. // deviceorientation event.
  41165. var orientation = this.filter.getOrientation();
  41166. // Predict orientation.
  41167. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  41168. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  41169. var out = new MathUtil.Quaternion();
  41170. out.copy(this.filterToWorldQ);
  41171. out.multiply(this.resetQ);
  41172. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  41173. out.multiply(this.touchPanner.getOrientation());
  41174. }
  41175. out.multiply(this.predictedQ);
  41176. out.multiply(this.worldToScreenQ);
  41177. // Handle the yaw-only case.
  41178. if (window.WebVRConfig.YAW_ONLY) {
  41179. // Make a quaternion that only turns around the Y-axis.
  41180. out.x = 0;
  41181. out.z = 0;
  41182. out.normalize();
  41183. }
  41184. this.orientationOut_[0] = out.x;
  41185. this.orientationOut_[1] = out.y;
  41186. this.orientationOut_[2] = out.z;
  41187. this.orientationOut_[3] = out.w;
  41188. return this.orientationOut_;
  41189. };
  41190. FusionPoseSensor.prototype.resetPose = function() {
  41191. // Reduce to inverted yaw-only.
  41192. this.resetQ.copy(this.filter.getOrientation());
  41193. this.resetQ.x = 0;
  41194. this.resetQ.y = 0;
  41195. this.resetQ.z *= -1;
  41196. this.resetQ.normalize();
  41197. // Take into account extra transformations in landscape mode.
  41198. if (Util.isLandscapeMode()) {
  41199. this.resetQ.multiply(this.inverseWorldToScreenQ);
  41200. }
  41201. // Take into account original pose.
  41202. this.resetQ.multiply(this.originalPoseAdjustQ);
  41203. if (!window.WebVRConfig.TOUCH_PANNER_DISABLED) {
  41204. this.touchPanner.resetSensor();
  41205. }
  41206. };
  41207. FusionPoseSensor.prototype.onDeviceMotion_ = function(deviceMotion) {
  41208. this.updateDeviceMotion_(deviceMotion);
  41209. };
  41210. FusionPoseSensor.prototype.updateDeviceMotion_ = function(deviceMotion) {
  41211. var accGravity = deviceMotion.accelerationIncludingGravity;
  41212. var rotRate = deviceMotion.rotationRate;
  41213. var timestampS = deviceMotion.timeStamp / 1000;
  41214. var deltaS = timestampS - this.previousTimestampS;
  41215. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  41216. console.warn('Invalid timestamps detected. Time step between successive ' +
  41217. 'gyroscope sensor samples is very small or not monotonic');
  41218. this.previousTimestampS = timestampS;
  41219. return;
  41220. }
  41221. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  41222. if (Util.isR7()) {
  41223. this.gyroscope.set(-rotRate.beta, rotRate.alpha, rotRate.gamma);
  41224. } else {
  41225. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  41226. }
  41227. // With iOS and Firefox Android, rotationRate is reported in degrees,
  41228. // so we first convert to radians.
  41229. if (this.isIOS || this.isFirefoxAndroid) {
  41230. this.gyroscope.multiplyScalar(Math.PI / 180);
  41231. }
  41232. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  41233. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  41234. this.previousTimestampS = timestampS;
  41235. };
  41236. FusionPoseSensor.prototype.onOrientationChange_ = function(screenOrientation) {
  41237. this.setScreenTransform_();
  41238. };
  41239. /**
  41240. * This is only needed if we are in an cross origin iframe on iOS to work around
  41241. * this issue: https://bugs.webkit.org/show_bug.cgi?id=152299.
  41242. */
  41243. FusionPoseSensor.prototype.onMessage_ = function(event) {
  41244. var message = event.data;
  41245. // If there's no message type, ignore it.
  41246. if (!message || !message.type) {
  41247. return;
  41248. }
  41249. // Ignore all messages that aren't devicemotion.
  41250. var type = message.type.toLowerCase();
  41251. if (type !== 'devicemotion') {
  41252. return;
  41253. }
  41254. // Update device motion.
  41255. this.updateDeviceMotion_(message.deviceMotionEvent);
  41256. };
  41257. FusionPoseSensor.prototype.setScreenTransform_ = function() {
  41258. this.worldToScreenQ.set(0, 0, 0, 1);
  41259. switch (window.orientation) {
  41260. case 0:
  41261. break;
  41262. case 90:
  41263. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -Math.PI / 2);
  41264. break;
  41265. case -90:
  41266. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), Math.PI / 2);
  41267. break;
  41268. case 180:
  41269. // TODO.
  41270. break;
  41271. }
  41272. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  41273. this.inverseWorldToScreenQ.inverse();
  41274. };
  41275. FusionPoseSensor.prototype.start = function() {
  41276. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  41277. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  41278. this.onMessageCallback_ = this.onMessage_.bind(this);
  41279. // Only listen for postMessages if we're in an iOS and embedded inside a cross
  41280. // domain IFrame. In this case, the polyfill can still work if the containing
  41281. // page sends synthetic devicemotion events. For an example of this, see
  41282. // iframe-message-sender.js in VR View: https://goo.gl/XDtvFZ
  41283. if (Util.isIOS() && Util.isInsideCrossDomainIFrame()) {
  41284. window.addEventListener('message', this.onMessageCallback_);
  41285. }
  41286. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  41287. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  41288. };
  41289. FusionPoseSensor.prototype.stop = function() {
  41290. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  41291. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  41292. window.removeEventListener('message', this.onMessageCallback_);
  41293. };
  41294. module.exports = FusionPoseSensor;
  41295. },{"../math-util.js":59,"../touch-panner.js":67,"../util.js":68,"./complementary-filter.js":63,"./pose-predictor.js":65}],65:[function(_dereq_,module,exports){
  41296. /*
  41297. * Copyright 2015 Google Inc. All Rights Reserved.
  41298. * Licensed under the Apache License, Version 2.0 (the "License");
  41299. * you may not use this file except in compliance with the License.
  41300. * You may obtain a copy of the License at
  41301. *
  41302. * http://www.apache.org/licenses/LICENSE-2.0
  41303. *
  41304. * Unless required by applicable law or agreed to in writing, software
  41305. * distributed under the License is distributed on an "AS IS" BASIS,
  41306. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41307. * See the License for the specific language governing permissions and
  41308. * limitations under the License.
  41309. */
  41310. var MathUtil = _dereq_('../math-util');
  41311. var Util = _dereq_('../util');
  41312. /**
  41313. * Given an orientation and the gyroscope data, predicts the future orientation
  41314. * of the head. This makes rendering appear faster.
  41315. *
  41316. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  41317. *
  41318. * @param {Number} predictionTimeS time from head movement to the appearance of
  41319. * the corresponding image.
  41320. */
  41321. function PosePredictor(predictionTimeS) {
  41322. this.predictionTimeS = predictionTimeS;
  41323. // The quaternion corresponding to the previous state.
  41324. this.previousQ = new MathUtil.Quaternion();
  41325. // Previous time a prediction occurred.
  41326. this.previousTimestampS = null;
  41327. // The delta quaternion that adjusts the current pose.
  41328. this.deltaQ = new MathUtil.Quaternion();
  41329. // The output quaternion.
  41330. this.outQ = new MathUtil.Quaternion();
  41331. }
  41332. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  41333. if (!this.previousTimestampS) {
  41334. this.previousQ.copy(currentQ);
  41335. this.previousTimestampS = timestampS;
  41336. return currentQ;
  41337. }
  41338. // Calculate axis and angle based on gyroscope rotation rate data.
  41339. var axis = new MathUtil.Vector3();
  41340. axis.copy(gyro);
  41341. axis.normalize();
  41342. var angularSpeed = gyro.length();
  41343. // If we're rotating slowly, don't do prediction.
  41344. if (angularSpeed < MathUtil.degToRad * 20) {
  41345. if (Util.isDebug()) {
  41346. console.log('Moving slowly, at %s deg/s: no prediction',
  41347. (MathUtil.radToDeg * angularSpeed).toFixed(1));
  41348. }
  41349. this.outQ.copy(currentQ);
  41350. this.previousQ.copy(currentQ);
  41351. return this.outQ;
  41352. }
  41353. // Get the predicted angle based on the time delta and latency.
  41354. var deltaT = timestampS - this.previousTimestampS;
  41355. var predictAngle = angularSpeed * this.predictionTimeS;
  41356. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  41357. this.outQ.copy(this.previousQ);
  41358. this.outQ.multiply(this.deltaQ);
  41359. this.previousQ.copy(currentQ);
  41360. this.previousTimestampS = timestampS;
  41361. return this.outQ;
  41362. };
  41363. module.exports = PosePredictor;
  41364. },{"../math-util":59,"../util":68}],66:[function(_dereq_,module,exports){
  41365. function SensorSample(sample, timestampS) {
  41366. this.set(sample, timestampS);
  41367. };
  41368. SensorSample.prototype.set = function(sample, timestampS) {
  41369. this.sample = sample;
  41370. this.timestampS = timestampS;
  41371. };
  41372. SensorSample.prototype.copy = function(sensorSample) {
  41373. this.set(sensorSample.sample, sensorSample.timestampS);
  41374. };
  41375. module.exports = SensorSample;
  41376. },{}],67:[function(_dereq_,module,exports){
  41377. /*
  41378. * Copyright 2015 Google Inc. All Rights Reserved.
  41379. * Licensed under the Apache License, Version 2.0 (the "License");
  41380. * you may not use this file except in compliance with the License.
  41381. * You may obtain a copy of the License at
  41382. *
  41383. * http://www.apache.org/licenses/LICENSE-2.0
  41384. *
  41385. * Unless required by applicable law or agreed to in writing, software
  41386. * distributed under the License is distributed on an "AS IS" BASIS,
  41387. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41388. * See the License for the specific language governing permissions and
  41389. * limitations under the License.
  41390. */
  41391. var MathUtil = _dereq_('./math-util.js');
  41392. var Util = _dereq_('./util.js');
  41393. var ROTATE_SPEED = 0.5;
  41394. /**
  41395. * Provides a quaternion responsible for pre-panning the scene before further
  41396. * transformations due to device sensors.
  41397. */
  41398. function TouchPanner() {
  41399. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  41400. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  41401. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  41402. this.isTouching = false;
  41403. this.rotateStart = new MathUtil.Vector2();
  41404. this.rotateEnd = new MathUtil.Vector2();
  41405. this.rotateDelta = new MathUtil.Vector2();
  41406. this.theta = 0;
  41407. this.orientation = new MathUtil.Quaternion();
  41408. }
  41409. TouchPanner.prototype.getOrientation = function() {
  41410. this.orientation.setFromEulerXYZ(0, 0, this.theta);
  41411. return this.orientation;
  41412. };
  41413. TouchPanner.prototype.resetSensor = function() {
  41414. this.theta = 0;
  41415. };
  41416. TouchPanner.prototype.onTouchStart_ = function(e) {
  41417. // Only respond if there is exactly one touch.
  41418. // Note that the Daydream controller passes in a `touchstart` event with
  41419. // no `touches` property, so we must check for that case too.
  41420. if (!e.touches || e.touches.length != 1) {
  41421. return;
  41422. }
  41423. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  41424. this.isTouching = true;
  41425. };
  41426. TouchPanner.prototype.onTouchMove_ = function(e) {
  41427. if (!this.isTouching) {
  41428. return;
  41429. }
  41430. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  41431. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  41432. this.rotateStart.copy(this.rotateEnd);
  41433. // On iOS, direction is inverted.
  41434. if (Util.isIOS()) {
  41435. this.rotateDelta.x *= -1;
  41436. }
  41437. var element = document.body;
  41438. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  41439. };
  41440. TouchPanner.prototype.onTouchEnd_ = function(e) {
  41441. this.isTouching = false;
  41442. };
  41443. module.exports = TouchPanner;
  41444. },{"./math-util.js":59,"./util.js":68}],68:[function(_dereq_,module,exports){
  41445. /*
  41446. * Copyright 2015 Google Inc. All Rights Reserved.
  41447. * Licensed under the Apache License, Version 2.0 (the "License");
  41448. * you may not use this file except in compliance with the License.
  41449. * You may obtain a copy of the License at
  41450. *
  41451. * http://www.apache.org/licenses/LICENSE-2.0
  41452. *
  41453. * Unless required by applicable law or agreed to in writing, software
  41454. * distributed under the License is distributed on an "AS IS" BASIS,
  41455. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41456. * See the License for the specific language governing permissions and
  41457. * limitations under the License.
  41458. */
  41459. var Util = window.Util || {};
  41460. Util.MIN_TIMESTEP = 0.001;
  41461. Util.MAX_TIMESTEP = 1;
  41462. Util.base64 = function(mimeType, base64) {
  41463. return 'data:' + mimeType + ';base64,' + base64;
  41464. };
  41465. Util.clamp = function(value, min, max) {
  41466. return Math.min(Math.max(min, value), max);
  41467. };
  41468. Util.lerp = function(a, b, t) {
  41469. return a + ((b - a) * t);
  41470. };
  41471. /**
  41472. * Light polyfill for `Promise.race`. Returns
  41473. * a promise that resolves when the first promise
  41474. * provided resolves.
  41475. *
  41476. * @param {Array<Promise>} promises
  41477. */
  41478. Util.race = function(promises) {
  41479. if (Promise.race) {
  41480. return Promise.race(promises);
  41481. }
  41482. return new Promise(function (resolve, reject) {
  41483. for (var i = 0; i < promises.length; i++) {
  41484. promises[i].then(resolve, reject);
  41485. }
  41486. });
  41487. };
  41488. Util.isIOS = (function() {
  41489. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  41490. return function() {
  41491. return isIOS;
  41492. };
  41493. })();
  41494. Util.isWebViewAndroid = (function() {
  41495. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 &&
  41496. navigator.userAgent.indexOf('Android') !== -1 &&
  41497. navigator.userAgent.indexOf('Chrome') !== -1;
  41498. return function() {
  41499. return isWebViewAndroid;
  41500. };
  41501. })();
  41502. Util.isSafari = (function() {
  41503. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  41504. return function() {
  41505. return isSafari;
  41506. };
  41507. })();
  41508. Util.isFirefoxAndroid = (function() {
  41509. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 &&
  41510. navigator.userAgent.indexOf('Android') !== -1;
  41511. return function() {
  41512. return isFirefoxAndroid;
  41513. };
  41514. })();
  41515. Util.isR7 = (function() {
  41516. var isR7 = navigator.userAgent.indexOf('R7 Build') !== -1;
  41517. return function() {
  41518. return isR7;
  41519. };
  41520. })();
  41521. Util.isLandscapeMode = function() {
  41522. var rtn = (window.orientation == 90 || window.orientation == -90);
  41523. return Util.isR7() ? !rtn : rtn;
  41524. };
  41525. // Helper method to validate the time steps of sensor timestamps.
  41526. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  41527. if (isNaN(timestampDeltaS)) {
  41528. return false;
  41529. }
  41530. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  41531. return false;
  41532. }
  41533. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  41534. return false;
  41535. }
  41536. return true;
  41537. };
  41538. Util.getScreenWidth = function() {
  41539. return Math.max(window.screen.width, window.screen.height) *
  41540. window.devicePixelRatio;
  41541. };
  41542. Util.getScreenHeight = function() {
  41543. return Math.min(window.screen.width, window.screen.height) *
  41544. window.devicePixelRatio;
  41545. };
  41546. Util.requestFullscreen = function(element) {
  41547. if (Util.isWebViewAndroid()) {
  41548. return false;
  41549. }
  41550. if (element.requestFullscreen) {
  41551. element.requestFullscreen();
  41552. } else if (element.webkitRequestFullscreen) {
  41553. element.webkitRequestFullscreen();
  41554. } else if (element.mozRequestFullScreen) {
  41555. element.mozRequestFullScreen();
  41556. } else if (element.msRequestFullscreen) {
  41557. element.msRequestFullscreen();
  41558. } else {
  41559. return false;
  41560. }
  41561. return true;
  41562. };
  41563. Util.exitFullscreen = function() {
  41564. if (document.exitFullscreen) {
  41565. document.exitFullscreen();
  41566. } else if (document.webkitExitFullscreen) {
  41567. document.webkitExitFullscreen();
  41568. } else if (document.mozCancelFullScreen) {
  41569. document.mozCancelFullScreen();
  41570. } else if (document.msExitFullscreen) {
  41571. document.msExitFullscreen();
  41572. } else {
  41573. return false;
  41574. }
  41575. return true;
  41576. };
  41577. Util.getFullscreenElement = function() {
  41578. return document.fullscreenElement ||
  41579. document.webkitFullscreenElement ||
  41580. document.mozFullScreenElement ||
  41581. document.msFullscreenElement;
  41582. };
  41583. Util.linkProgram = function(gl, vertexSource, fragmentSource, attribLocationMap) {
  41584. // No error checking for brevity.
  41585. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  41586. gl.shaderSource(vertexShader, vertexSource);
  41587. gl.compileShader(vertexShader);
  41588. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  41589. gl.shaderSource(fragmentShader, fragmentSource);
  41590. gl.compileShader(fragmentShader);
  41591. var program = gl.createProgram();
  41592. gl.attachShader(program, vertexShader);
  41593. gl.attachShader(program, fragmentShader);
  41594. for (var attribName in attribLocationMap)
  41595. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  41596. gl.linkProgram(program);
  41597. gl.deleteShader(vertexShader);
  41598. gl.deleteShader(fragmentShader);
  41599. return program;
  41600. };
  41601. Util.getProgramUniforms = function(gl, program) {
  41602. var uniforms = {};
  41603. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  41604. var uniformName = '';
  41605. for (var i = 0; i < uniformCount; i++) {
  41606. var uniformInfo = gl.getActiveUniform(program, i);
  41607. uniformName = uniformInfo.name.replace('[0]', '');
  41608. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  41609. }
  41610. return uniforms;
  41611. };
  41612. Util.orthoMatrix = function (out, left, right, bottom, top, near, far) {
  41613. var lr = 1 / (left - right),
  41614. bt = 1 / (bottom - top),
  41615. nf = 1 / (near - far);
  41616. out[0] = -2 * lr;
  41617. out[1] = 0;
  41618. out[2] = 0;
  41619. out[3] = 0;
  41620. out[4] = 0;
  41621. out[5] = -2 * bt;
  41622. out[6] = 0;
  41623. out[7] = 0;
  41624. out[8] = 0;
  41625. out[9] = 0;
  41626. out[10] = 2 * nf;
  41627. out[11] = 0;
  41628. out[12] = (left + right) * lr;
  41629. out[13] = (top + bottom) * bt;
  41630. out[14] = (far + near) * nf;
  41631. out[15] = 1;
  41632. return out;
  41633. };
  41634. Util.copyArray = function (source, dest) {
  41635. for (var i = 0, n = source.length; i < n; i++) {
  41636. dest[i] = source[i];
  41637. }
  41638. };
  41639. Util.isMobile = function() {
  41640. var check = false;
  41641. (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);
  41642. return check;
  41643. };
  41644. Util.extend = function(dest, src) {
  41645. for (var key in src) {
  41646. if (src.hasOwnProperty(key)) {
  41647. dest[key] = src[key];
  41648. }
  41649. }
  41650. return dest;
  41651. }
  41652. Util.safariCssSizeWorkaround = function(canvas) {
  41653. // TODO(smus): Remove this workaround when Safari for iOS is fixed.
  41654. // iOS only workaround (for https://bugs.webkit.org/show_bug.cgi?id=152556).
  41655. //
  41656. // "To the last I grapple with thee;
  41657. // from hell's heart I stab at thee;
  41658. // for hate's sake I spit my last breath at thee."
  41659. // -- Moby Dick, by Herman Melville
  41660. if (Util.isIOS()) {
  41661. var width = canvas.style.width;
  41662. var height = canvas.style.height;
  41663. canvas.style.width = (parseInt(width) + 1) + 'px';
  41664. canvas.style.height = (parseInt(height)) + 'px';
  41665. setTimeout(function() {
  41666. canvas.style.width = width;
  41667. canvas.style.height = height;
  41668. }, 100);
  41669. }
  41670. // Debug only.
  41671. window.Util = Util;
  41672. window.canvas = canvas;
  41673. };
  41674. Util.isDebug = function() {
  41675. return Util.getQueryParameter('debug');
  41676. };
  41677. Util.getQueryParameter = function(name) {
  41678. var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  41679. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  41680. results = regex.exec(location.search);
  41681. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  41682. };
  41683. Util.frameDataFromPose = (function() {
  41684. var piOver180 = Math.PI / 180.0;
  41685. var rad45 = Math.PI * 0.25;
  41686. // Borrowed from glMatrix.
  41687. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  41688. var upTan = Math.tan(fov ? (fov.upDegrees * piOver180) : rad45),
  41689. downTan = Math.tan(fov ? (fov.downDegrees * piOver180) : rad45),
  41690. leftTan = Math.tan(fov ? (fov.leftDegrees * piOver180) : rad45),
  41691. rightTan = Math.tan(fov ? (fov.rightDegrees * piOver180) : rad45),
  41692. xScale = 2.0 / (leftTan + rightTan),
  41693. yScale = 2.0 / (upTan + downTan);
  41694. out[0] = xScale;
  41695. out[1] = 0.0;
  41696. out[2] = 0.0;
  41697. out[3] = 0.0;
  41698. out[4] = 0.0;
  41699. out[5] = yScale;
  41700. out[6] = 0.0;
  41701. out[7] = 0.0;
  41702. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  41703. out[9] = ((upTan - downTan) * yScale * 0.5);
  41704. out[10] = far / (near - far);
  41705. out[11] = -1.0;
  41706. out[12] = 0.0;
  41707. out[13] = 0.0;
  41708. out[14] = (far * near) / (near - far);
  41709. out[15] = 0.0;
  41710. return out;
  41711. }
  41712. function mat4_fromRotationTranslation(out, q, v) {
  41713. // Quaternion math
  41714. var x = q[0], y = q[1], z = q[2], w = q[3],
  41715. x2 = x + x,
  41716. y2 = y + y,
  41717. z2 = z + z,
  41718. xx = x * x2,
  41719. xy = x * y2,
  41720. xz = x * z2,
  41721. yy = y * y2,
  41722. yz = y * z2,
  41723. zz = z * z2,
  41724. wx = w * x2,
  41725. wy = w * y2,
  41726. wz = w * z2;
  41727. out[0] = 1 - (yy + zz);
  41728. out[1] = xy + wz;
  41729. out[2] = xz - wy;
  41730. out[3] = 0;
  41731. out[4] = xy - wz;
  41732. out[5] = 1 - (xx + zz);
  41733. out[6] = yz + wx;
  41734. out[7] = 0;
  41735. out[8] = xz + wy;
  41736. out[9] = yz - wx;
  41737. out[10] = 1 - (xx + yy);
  41738. out[11] = 0;
  41739. out[12] = v[0];
  41740. out[13] = v[1];
  41741. out[14] = v[2];
  41742. out[15] = 1;
  41743. return out;
  41744. };
  41745. function mat4_translate(out, a, v) {
  41746. var x = v[0], y = v[1], z = v[2],
  41747. a00, a01, a02, a03,
  41748. a10, a11, a12, a13,
  41749. a20, a21, a22, a23;
  41750. if (a === out) {
  41751. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  41752. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  41753. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  41754. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  41755. } else {
  41756. a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
  41757. a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
  41758. a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
  41759. out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
  41760. out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
  41761. out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
  41762. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  41763. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  41764. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  41765. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  41766. }
  41767. return out;
  41768. };
  41769. function mat4_invert(out, a) {
  41770. var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
  41771. a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
  41772. a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
  41773. a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
  41774. b00 = a00 * a11 - a01 * a10,
  41775. b01 = a00 * a12 - a02 * a10,
  41776. b02 = a00 * a13 - a03 * a10,
  41777. b03 = a01 * a12 - a02 * a11,
  41778. b04 = a01 * a13 - a03 * a11,
  41779. b05 = a02 * a13 - a03 * a12,
  41780. b06 = a20 * a31 - a21 * a30,
  41781. b07 = a20 * a32 - a22 * a30,
  41782. b08 = a20 * a33 - a23 * a30,
  41783. b09 = a21 * a32 - a22 * a31,
  41784. b10 = a21 * a33 - a23 * a31,
  41785. b11 = a22 * a33 - a23 * a32,
  41786. // Calculate the determinant
  41787. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  41788. if (!det) {
  41789. return null;
  41790. }
  41791. det = 1.0 / det;
  41792. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  41793. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  41794. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  41795. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  41796. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  41797. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  41798. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  41799. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  41800. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  41801. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  41802. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  41803. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  41804. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  41805. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  41806. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  41807. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  41808. return out;
  41809. };
  41810. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  41811. var defaultPosition = new Float32Array([0, 0, 0]);
  41812. function updateEyeMatrices(projection, view, pose, parameters, vrDisplay) {
  41813. mat4_perspectiveFromFieldOfView(projection, parameters ? parameters.fieldOfView : null, vrDisplay.depthNear, vrDisplay.depthFar);
  41814. var orientation = pose.orientation || defaultOrientation;
  41815. var position = pose.position || defaultPosition;
  41816. mat4_fromRotationTranslation(view, orientation, position);
  41817. if (parameters)
  41818. mat4_translate(view, view, parameters.offset);
  41819. mat4_invert(view, view);
  41820. }
  41821. return function(frameData, pose, vrDisplay) {
  41822. if (!frameData || !pose)
  41823. return false;
  41824. frameData.pose = pose;
  41825. frameData.timestamp = pose.timestamp;
  41826. updateEyeMatrices(
  41827. frameData.leftProjectionMatrix, frameData.leftViewMatrix,
  41828. pose, vrDisplay.getEyeParameters("left"), vrDisplay);
  41829. updateEyeMatrices(
  41830. frameData.rightProjectionMatrix, frameData.rightViewMatrix,
  41831. pose, vrDisplay.getEyeParameters("right"), vrDisplay);
  41832. return true;
  41833. };
  41834. })();
  41835. Util.isInsideCrossDomainIFrame = function() {
  41836. var isFramed = (window.self !== window.top);
  41837. var refDomain = Util.getDomainFromUrl(document.referrer);
  41838. var thisDomain = Util.getDomainFromUrl(window.location.href);
  41839. return isFramed && (refDomain !== thisDomain);
  41840. };
  41841. // From http://stackoverflow.com/a/23945027.
  41842. Util.getDomainFromUrl = function(url) {
  41843. var domain;
  41844. // Find & remove protocol (http, ftp, etc.) and get domain.
  41845. if (url.indexOf("://") > -1) {
  41846. domain = url.split('/')[2];
  41847. }
  41848. else {
  41849. domain = url.split('/')[0];
  41850. }
  41851. //find & remove port number
  41852. domain = domain.split(':')[0];
  41853. return domain;
  41854. }
  41855. module.exports = Util;
  41856. },{}],69:[function(_dereq_,module,exports){
  41857. /*
  41858. * Copyright 2015 Google Inc. All Rights Reserved.
  41859. * Licensed under the Apache License, Version 2.0 (the "License");
  41860. * you may not use this file except in compliance with the License.
  41861. * You may obtain a copy of the License at
  41862. *
  41863. * http://www.apache.org/licenses/LICENSE-2.0
  41864. *
  41865. * Unless required by applicable law or agreed to in writing, software
  41866. * distributed under the License is distributed on an "AS IS" BASIS,
  41867. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41868. * See the License for the specific language governing permissions and
  41869. * limitations under the License.
  41870. */
  41871. var DeviceInfo = _dereq_('./device-info.js');
  41872. var Util = _dereq_('./util.js');
  41873. var DEFAULT_VIEWER = 'CardboardV1';
  41874. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  41875. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  41876. /**
  41877. * Creates a viewer selector with the options specified. Supports being shown
  41878. * and hidden. Generates events when viewer parameters change. Also supports
  41879. * saving the currently selected index in localStorage.
  41880. */
  41881. function ViewerSelector() {
  41882. // Try to load the selected key from local storage.
  41883. try {
  41884. this.selectedKey = localStorage.getItem(VIEWER_KEY);
  41885. } catch (error) {
  41886. console.error('Failed to load viewer profile: %s', error);
  41887. }
  41888. //If none exists, or if localstorage is unavailable, use the default key.
  41889. if (!this.selectedKey) {
  41890. this.selectedKey = DEFAULT_VIEWER;
  41891. }
  41892. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  41893. this.root = null;
  41894. this.onChangeCallbacks_ = [];
  41895. }
  41896. ViewerSelector.prototype.show = function(root) {
  41897. this.root = root;
  41898. root.appendChild(this.dialog);
  41899. // Ensure the currently selected item is checked.
  41900. var selected = this.dialog.querySelector('#' + this.selectedKey);
  41901. selected.checked = true;
  41902. // Show the UI.
  41903. this.dialog.style.display = 'block';
  41904. };
  41905. ViewerSelector.prototype.hide = function() {
  41906. if (this.root && this.root.contains(this.dialog)) {
  41907. this.root.removeChild(this.dialog);
  41908. }
  41909. this.dialog.style.display = 'none';
  41910. };
  41911. ViewerSelector.prototype.getCurrentViewer = function() {
  41912. return DeviceInfo.Viewers[this.selectedKey];
  41913. };
  41914. ViewerSelector.prototype.getSelectedKey_ = function() {
  41915. var input = this.dialog.querySelector('input[name=field]:checked');
  41916. if (input) {
  41917. return input.id;
  41918. }
  41919. return null;
  41920. };
  41921. ViewerSelector.prototype.onChange = function(cb) {
  41922. this.onChangeCallbacks_.push(cb);
  41923. };
  41924. ViewerSelector.prototype.fireOnChange_ = function(viewer) {
  41925. for (var i = 0; i < this.onChangeCallbacks_.length; i++) {
  41926. this.onChangeCallbacks_[i](viewer);
  41927. }
  41928. };
  41929. ViewerSelector.prototype.onSave_ = function() {
  41930. this.selectedKey = this.getSelectedKey_();
  41931. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  41932. console.error('ViewerSelector.onSave_: this should never happen!');
  41933. return;
  41934. }
  41935. this.fireOnChange_(DeviceInfo.Viewers[this.selectedKey]);
  41936. // Attempt to save the viewer profile, but fails in private mode.
  41937. try {
  41938. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  41939. } catch(error) {
  41940. console.error('Failed to save viewer profile: %s', error);
  41941. }
  41942. this.hide();
  41943. };
  41944. /**
  41945. * Creates the dialog.
  41946. */
  41947. ViewerSelector.prototype.createDialog_ = function(options) {
  41948. var container = document.createElement('div');
  41949. container.classList.add(CLASS_NAME);
  41950. container.style.display = 'none';
  41951. // Create an overlay that dims the background, and which goes away when you
  41952. // tap it.
  41953. var overlay = document.createElement('div');
  41954. var s = overlay.style;
  41955. s.position = 'fixed';
  41956. s.left = 0;
  41957. s.top = 0;
  41958. s.width = '100%';
  41959. s.height = '100%';
  41960. s.background = 'rgba(0, 0, 0, 0.3)';
  41961. overlay.addEventListener('click', this.hide.bind(this));
  41962. var width = 280;
  41963. var dialog = document.createElement('div');
  41964. var s = dialog.style;
  41965. s.boxSizing = 'border-box';
  41966. s.position = 'fixed';
  41967. s.top = '24px';
  41968. s.left = '50%';
  41969. s.marginLeft = (-width/2) + 'px';
  41970. s.width = width + 'px';
  41971. s.padding = '24px';
  41972. s.overflow = 'hidden';
  41973. s.background = '#fafafa';
  41974. s.fontFamily = "'Roboto', sans-serif";
  41975. s.boxShadow = '0px 5px 20px #666';
  41976. dialog.appendChild(this.createH1_('Select your viewer'));
  41977. for (var id in options) {
  41978. dialog.appendChild(this.createChoice_(id, options[id].label));
  41979. }
  41980. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  41981. container.appendChild(overlay);
  41982. container.appendChild(dialog);
  41983. return container;
  41984. };
  41985. ViewerSelector.prototype.createH1_ = function(name) {
  41986. var h1 = document.createElement('h1');
  41987. var s = h1.style;
  41988. s.color = 'black';
  41989. s.fontSize = '20px';
  41990. s.fontWeight = 'bold';
  41991. s.marginTop = 0;
  41992. s.marginBottom = '24px';
  41993. h1.innerHTML = name;
  41994. return h1;
  41995. };
  41996. ViewerSelector.prototype.createChoice_ = function(id, name) {
  41997. /*
  41998. <div class="choice">
  41999. <input id="v1" type="radio" name="field" value="v1">
  42000. <label for="v1">Cardboard V1</label>
  42001. </div>
  42002. */
  42003. var div = document.createElement('div');
  42004. div.style.marginTop = '8px';
  42005. div.style.color = 'black';
  42006. var input = document.createElement('input');
  42007. input.style.fontSize = '30px';
  42008. input.setAttribute('id', id);
  42009. input.setAttribute('type', 'radio');
  42010. input.setAttribute('value', id);
  42011. input.setAttribute('name', 'field');
  42012. var label = document.createElement('label');
  42013. label.style.marginLeft = '4px';
  42014. label.setAttribute('for', id);
  42015. label.innerHTML = name;
  42016. div.appendChild(input);
  42017. div.appendChild(label);
  42018. return div;
  42019. };
  42020. ViewerSelector.prototype.createButton_ = function(label, onclick) {
  42021. var button = document.createElement('button');
  42022. button.innerHTML = label;
  42023. var s = button.style;
  42024. s.float = 'right';
  42025. s.textTransform = 'uppercase';
  42026. s.color = '#1094f7';
  42027. s.fontSize = '14px';
  42028. s.letterSpacing = 0;
  42029. s.border = 0;
  42030. s.background = 'none';
  42031. s.marginTop = '16px';
  42032. button.addEventListener('click', onclick);
  42033. return button;
  42034. };
  42035. module.exports = ViewerSelector;
  42036. },{"./device-info.js":53,"./util.js":68}],70:[function(_dereq_,module,exports){
  42037. /*
  42038. * Copyright 2015 Google Inc. All Rights Reserved.
  42039. * Licensed under the Apache License, Version 2.0 (the "License");
  42040. * you may not use this file except in compliance with the License.
  42041. * You may obtain a copy of the License at
  42042. *
  42043. * http://www.apache.org/licenses/LICENSE-2.0
  42044. *
  42045. * Unless required by applicable law or agreed to in writing, software
  42046. * distributed under the License is distributed on an "AS IS" BASIS,
  42047. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42048. * See the License for the specific language governing permissions and
  42049. * limitations under the License.
  42050. */
  42051. var Util = _dereq_('./util.js');
  42052. /**
  42053. * Android and iOS compatible wakelock implementation.
  42054. *
  42055. * Refactored thanks to dkovalev@.
  42056. */
  42057. function AndroidWakeLock() {
  42058. var video = document.createElement('video');
  42059. video.setAttribute('loop', '');
  42060. function addSourceToVideo(element, type, dataURI) {
  42061. var source = document.createElement('source');
  42062. source.src = dataURI;
  42063. source.type = 'video/' + type;
  42064. element.appendChild(source);
  42065. }
  42066. addSourceToVideo(video,'webm', Util.base64('video/webm', 'GkXfo0AgQoaBAUL3gQFC8oEEQvOBCEKCQAR3ZWJtQoeBAkKFgQIYU4BnQI0VSalmQCgq17FAAw9CQE2AQAZ3aGFtbXlXQUAGd2hhbW15RIlACECPQAAAAAAAFlSua0AxrkAu14EBY8WBAZyBACK1nEADdW5khkAFVl9WUDglhohAA1ZQOIOBAeBABrCBCLqBCB9DtnVAIueBAKNAHIEAAIAwAQCdASoIAAgAAUAmJaQAA3AA/vz0AAA='));
  42067. addSourceToVideo(video, 'mp4', Util.base64('video/mp4', 'AAAAHGZ0eXBpc29tAAACAGlzb21pc28ybXA0MQAAAAhmcmVlAAAAG21kYXQAAAGzABAHAAABthADAowdbb9/AAAC6W1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAAAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAIVdHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAIAAAACAAAAAABsW1kaWEAAAAgbWRoZAAAAAB8JbCAfCWwgAAAA+gAAAAAVcQAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAAAVxtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAEcc3RibAAAALhzdHNkAAAAAAAAAAEAAACobXA0dgAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAIAAgASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAAFJlc2RzAAAAAANEAAEABDwgEQAAAAADDUAAAAAABS0AAAGwAQAAAbWJEwAAAQAAAAEgAMSNiB9FAEQBFGMAAAGyTGF2YzUyLjg3LjQGAQIAAAAYc3R0cwAAAAAAAAABAAAAAQAAAAAAAAAcc3RzYwAAAAAAAAABAAAAAQAAAAEAAAABAAAAFHN0c3oAAAAAAAAAEwAAAAEAAAAUc3RjbwAAAAAAAAABAAAALAAAAGB1ZHRhAAAAWG1ldGEAAAAAAAAAIWhkbHIAAAAAAAAAAG1kaXJhcHBsAAAAAAAAAAAAAAAAK2lsc3QAAAAjqXRvbwAAABtkYXRhAAAAAQAAAABMYXZmNTIuNzguMw=='));
  42068. this.request = function() {
  42069. if (video.paused) {
  42070. video.play();
  42071. }
  42072. };
  42073. this.release = function() {
  42074. video.pause();
  42075. };
  42076. }
  42077. function iOSWakeLock() {
  42078. var timer = null;
  42079. this.request = function() {
  42080. if (!timer) {
  42081. timer = setInterval(function() {
  42082. window.location = window.location;
  42083. setTimeout(window.stop, 0);
  42084. }, 30000);
  42085. }
  42086. }
  42087. this.release = function() {
  42088. if (timer) {
  42089. clearInterval(timer);
  42090. timer = null;
  42091. }
  42092. }
  42093. }
  42094. function getWakeLock() {
  42095. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  42096. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  42097. return iOSWakeLock;
  42098. } else {
  42099. return AndroidWakeLock;
  42100. }
  42101. }
  42102. module.exports = getWakeLock();
  42103. },{"./util.js":68}],71:[function(_dereq_,module,exports){
  42104. /*
  42105. * Copyright 2015 Google Inc. All Rights Reserved.
  42106. * Licensed under the Apache License, Version 2.0 (the "License");
  42107. * you may not use this file except in compliance with the License.
  42108. * You may obtain a copy of the License at
  42109. *
  42110. * http://www.apache.org/licenses/LICENSE-2.0
  42111. *
  42112. * Unless required by applicable law or agreed to in writing, software
  42113. * distributed under the License is distributed on an "AS IS" BASIS,
  42114. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42115. * See the License for the specific language governing permissions and
  42116. * limitations under the License.
  42117. */
  42118. var Util = _dereq_('./util.js');
  42119. var CardboardVRDisplay = _dereq_('./cardboard-vr-display.js');
  42120. var MouseKeyboardVRDisplay = _dereq_('./mouse-keyboard-vr-display.js');
  42121. // Uncomment to add positional tracking via webcam.
  42122. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  42123. var VRDisplay = _dereq_('./base.js').VRDisplay;
  42124. var VRFrameData = _dereq_('./base.js').VRFrameData;
  42125. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  42126. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  42127. var VRDisplayHMDDevice = _dereq_('./display-wrappers.js').VRDisplayHMDDevice;
  42128. var VRDisplayPositionSensorDevice = _dereq_('./display-wrappers.js').VRDisplayPositionSensorDevice;
  42129. var version = _dereq_('../package.json').version;
  42130. function WebVRPolyfill() {
  42131. this.displays = [];
  42132. this.devices = []; // For deprecated objects
  42133. this.devicesPopulated = false;
  42134. this.nativeWebVRAvailable = this.isWebVRAvailable();
  42135. this.nativeLegacyWebVRAvailable = this.isDeprecatedWebVRAvailable();
  42136. this.nativeGetVRDisplaysFunc = this.nativeWebVRAvailable ?
  42137. navigator.getVRDisplays :
  42138. null;
  42139. if (!this.nativeLegacyWebVRAvailable && !this.nativeWebVRAvailable) {
  42140. this.enablePolyfill();
  42141. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42142. this.enableDeprecatedPolyfill();
  42143. }
  42144. }
  42145. // Put a shim in place to update the API to 1.1 if needed.
  42146. InstallWebVRSpecShim();
  42147. }
  42148. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  42149. return ('getVRDisplays' in navigator);
  42150. };
  42151. WebVRPolyfill.prototype.isDeprecatedWebVRAvailable = function() {
  42152. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  42153. };
  42154. WebVRPolyfill.prototype.connectDisplay = function(vrDisplay) {
  42155. vrDisplay.fireVRDisplayConnect_();
  42156. this.displays.push(vrDisplay);
  42157. };
  42158. WebVRPolyfill.prototype.populateDevices = function() {
  42159. if (this.devicesPopulated) {
  42160. return;
  42161. }
  42162. // Initialize our virtual VR devices.
  42163. var vrDisplay = null;
  42164. // Add a Cardboard VRDisplay on compatible mobile devices
  42165. if (this.isCardboardCompatible()) {
  42166. vrDisplay = new CardboardVRDisplay();
  42167. this.connectDisplay(vrDisplay);
  42168. // For backwards compatibility
  42169. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42170. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42171. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42172. }
  42173. }
  42174. // Add a Mouse and Keyboard driven VRDisplay for desktops/laptops
  42175. if (!this.isMobile() && !window.WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  42176. vrDisplay = new MouseKeyboardVRDisplay();
  42177. this.connectDisplay(vrDisplay);
  42178. // For backwards compatibility
  42179. if (window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42180. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42181. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42182. }
  42183. }
  42184. // Uncomment to add positional tracking via webcam.
  42185. //if (!this.isMobile() && window.WebVRConfig.ENABLE_DEPRECATED_API) {
  42186. // positionDevice = new WebcamPositionSensorVRDevice();
  42187. // this.devices.push(positionDevice);
  42188. //}
  42189. this.devicesPopulated = true;
  42190. };
  42191. WebVRPolyfill.prototype.enablePolyfill = function() {
  42192. // Provide navigator.getVRDisplays.
  42193. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  42194. // Polyfill native VRDisplay.getFrameData
  42195. if (this.nativeWebVRAvailable && window.VRFrameData) {
  42196. var NativeVRFrameData = window.VRFrameData;
  42197. var nativeFrameData = new window.VRFrameData();
  42198. var nativeGetFrameData = window.VRDisplay.prototype.getFrameData;
  42199. window.VRFrameData = VRFrameData;
  42200. window.VRDisplay.prototype.getFrameData = function(frameData) {
  42201. if (frameData instanceof NativeVRFrameData) {
  42202. nativeGetFrameData.call(this, frameData);
  42203. return;
  42204. }
  42205. /*
  42206. Copy frame data from the native object into the polyfilled object.
  42207. */
  42208. nativeGetFrameData.call(this, nativeFrameData);
  42209. frameData.pose = nativeFrameData.pose;
  42210. Util.copyArray(nativeFrameData.leftProjectionMatrix, frameData.leftProjectionMatrix);
  42211. Util.copyArray(nativeFrameData.rightProjectionMatrix, frameData.rightProjectionMatrix);
  42212. Util.copyArray(nativeFrameData.leftViewMatrix, frameData.leftViewMatrix);
  42213. Util.copyArray(nativeFrameData.rightViewMatrix, frameData.rightViewMatrix);
  42214. //todo: copy
  42215. };
  42216. }
  42217. // Provide the `VRDisplay` object.
  42218. window.VRDisplay = VRDisplay;
  42219. // Provide the `navigator.vrEnabled` property.
  42220. if (navigator && typeof navigator.vrEnabled === 'undefined') {
  42221. var self = this;
  42222. Object.defineProperty(navigator, 'vrEnabled', {
  42223. get: function () {
  42224. return self.isCardboardCompatible() &&
  42225. (self.isFullScreenAvailable() || Util.isIOS());
  42226. }
  42227. });
  42228. }
  42229. if (!('VRFrameData' in window)) {
  42230. // Provide the VRFrameData object.
  42231. window.VRFrameData = VRFrameData;
  42232. }
  42233. };
  42234. WebVRPolyfill.prototype.enableDeprecatedPolyfill = function() {
  42235. // Provide navigator.getVRDevices.
  42236. navigator.getVRDevices = this.getVRDevices.bind(this);
  42237. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  42238. window.HMDVRDevice = HMDVRDevice;
  42239. window.PositionSensorVRDevice = PositionSensorVRDevice;
  42240. };
  42241. WebVRPolyfill.prototype.getVRDisplays = function() {
  42242. this.populateDevices();
  42243. var polyfillDisplays = this.displays;
  42244. if (!this.nativeWebVRAvailable) {
  42245. return Promise.resolve(polyfillDisplays);
  42246. }
  42247. // Set up a race condition if this browser has a bug where
  42248. // `navigator.getVRDisplays()` never resolves.
  42249. var timeoutId;
  42250. var vrDisplaysNative = this.nativeGetVRDisplaysFunc.call(navigator);
  42251. var timeoutPromise = new Promise(function(resolve) {
  42252. timeoutId = setTimeout(function() {
  42253. console.warn('Native WebVR implementation detected, but `getVRDisplays()` failed to resolve. Falling back to polyfill.');
  42254. resolve([]);
  42255. }, window.WebVRConfig.GET_VR_DISPLAYS_TIMEOUT);
  42256. });
  42257. return Util.race([
  42258. vrDisplaysNative,
  42259. timeoutPromise
  42260. ]).then(function(nativeDisplays) {
  42261. clearTimeout(timeoutId);
  42262. if (window.WebVRConfig.ALWAYS_APPEND_POLYFILL_DISPLAY) {
  42263. return nativeDisplays.concat(polyfillDisplays);
  42264. } else {
  42265. return nativeDisplays.length > 0 ? nativeDisplays : polyfillDisplays;
  42266. }
  42267. });
  42268. };
  42269. WebVRPolyfill.prototype.getVRDevices = function() {
  42270. console.warn('getVRDevices is deprecated. Please update your code to use getVRDisplays instead.');
  42271. var self = this;
  42272. return new Promise(function(resolve, reject) {
  42273. try {
  42274. if (!self.devicesPopulated) {
  42275. if (self.nativeWebVRAvailable) {
  42276. return navigator.getVRDisplays(function(displays) {
  42277. for (var i = 0; i < displays.length; ++i) {
  42278. self.devices.push(new VRDisplayHMDDevice(displays[i]));
  42279. self.devices.push(new VRDisplayPositionSensorDevice(displays[i]));
  42280. }
  42281. self.devicesPopulated = true;
  42282. resolve(self.devices);
  42283. }, reject);
  42284. }
  42285. if (self.nativeLegacyWebVRAvailable) {
  42286. return (navigator.getVRDDevices || navigator.mozGetVRDevices)(function(devices) {
  42287. for (var i = 0; i < devices.length; ++i) {
  42288. if (devices[i] instanceof HMDVRDevice) {
  42289. self.devices.push(devices[i]);
  42290. }
  42291. if (devices[i] instanceof PositionSensorVRDevice) {
  42292. self.devices.push(devices[i]);
  42293. }
  42294. }
  42295. self.devicesPopulated = true;
  42296. resolve(self.devices);
  42297. }, reject);
  42298. }
  42299. }
  42300. self.populateDevices();
  42301. resolve(self.devices);
  42302. } catch (e) {
  42303. reject(e);
  42304. }
  42305. });
  42306. };
  42307. WebVRPolyfill.prototype.NativeVRFrameData = window.VRFrameData;
  42308. /**
  42309. * Determine if a device is mobile.
  42310. */
  42311. WebVRPolyfill.prototype.isMobile = function() {
  42312. return /Android/i.test(navigator.userAgent) ||
  42313. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  42314. };
  42315. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  42316. // For now, support all iOS and Android devices.
  42317. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  42318. return this.isMobile() || window.WebVRConfig.FORCE_ENABLE_VR;
  42319. };
  42320. WebVRPolyfill.prototype.isFullScreenAvailable = function() {
  42321. return (document.fullscreenEnabled ||
  42322. document.mozFullScreenEnabled ||
  42323. document.webkitFullscreenEnabled ||
  42324. false);
  42325. };
  42326. // Installs a shim that updates a WebVR 1.0 spec implementation to WebVR 1.1
  42327. function InstallWebVRSpecShim() {
  42328. if ('VRDisplay' in window && !('VRFrameData' in window)) {
  42329. // Provide the VRFrameData object.
  42330. window.VRFrameData = VRFrameData;
  42331. // A lot of Chrome builds don't have depthNear and depthFar, even
  42332. // though they're in the WebVR 1.0 spec. Patch them in if they're not present.
  42333. if(!('depthNear' in window.VRDisplay.prototype)) {
  42334. window.VRDisplay.prototype.depthNear = 0.01;
  42335. }
  42336. if(!('depthFar' in window.VRDisplay.prototype)) {
  42337. window.VRDisplay.prototype.depthFar = 10000.0;
  42338. }
  42339. window.VRDisplay.prototype.getFrameData = function(frameData) {
  42340. return Util.frameDataFromPose(frameData, this.getPose(), this);
  42341. }
  42342. }
  42343. };
  42344. WebVRPolyfill.InstallWebVRSpecShim = InstallWebVRSpecShim;
  42345. WebVRPolyfill.version = version;
  42346. module.exports.WebVRPolyfill = WebVRPolyfill;
  42347. },{"../package.json":47,"./base.js":48,"./cardboard-vr-display.js":51,"./display-wrappers.js":54,"./mouse-keyboard-vr-display.js":60,"./util.js":68}],72:[function(_dereq_,module,exports){
  42348. var newline = /\n/
  42349. var newlineChar = '\n'
  42350. var whitespace = /\s/
  42351. module.exports = function(text, opt) {
  42352. var lines = module.exports.lines(text, opt)
  42353. return lines.map(function(line) {
  42354. return text.substring(line.start, line.end)
  42355. }).join('\n')
  42356. }
  42357. module.exports.lines = function wordwrap(text, opt) {
  42358. opt = opt||{}
  42359. //zero width results in nothing visible
  42360. if (opt.width === 0 && opt.mode !== 'nowrap')
  42361. return []
  42362. text = text||''
  42363. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  42364. var start = Math.max(0, opt.start||0)
  42365. var end = typeof opt.end === 'number' ? opt.end : text.length
  42366. var mode = opt.mode
  42367. var measure = opt.measure || monospace
  42368. if (mode === 'pre')
  42369. return pre(measure, text, start, end, width)
  42370. else
  42371. return greedy(measure, text, start, end, width, mode)
  42372. }
  42373. function idxOf(text, chr, start, end) {
  42374. var idx = text.indexOf(chr, start)
  42375. if (idx === -1 || idx > end)
  42376. return end
  42377. return idx
  42378. }
  42379. function isWhitespace(chr) {
  42380. return whitespace.test(chr)
  42381. }
  42382. function pre(measure, text, start, end, width) {
  42383. var lines = []
  42384. var lineStart = start
  42385. for (var i=start; i<end && i<text.length; i++) {
  42386. var chr = text.charAt(i)
  42387. var isNewline = newline.test(chr)
  42388. //If we've reached a newline, then step down a line
  42389. //Or if we've reached the EOF
  42390. if (isNewline || i===end-1) {
  42391. var lineEnd = isNewline ? i : i+1
  42392. var measured = measure(text, lineStart, lineEnd, width)
  42393. lines.push(measured)
  42394. lineStart = i+1
  42395. }
  42396. }
  42397. return lines
  42398. }
  42399. function greedy(measure, text, start, end, width, mode) {
  42400. //A greedy word wrapper based on LibGDX algorithm
  42401. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  42402. var lines = []
  42403. var testWidth = width
  42404. //if 'nowrap' is specified, we only wrap on newline chars
  42405. if (mode === 'nowrap')
  42406. testWidth = Number.MAX_VALUE
  42407. while (start < end && start < text.length) {
  42408. //get next newline position
  42409. var newLine = idxOf(text, newlineChar, start, end)
  42410. //eat whitespace at start of line
  42411. while (start < newLine) {
  42412. if (!isWhitespace( text.charAt(start) ))
  42413. break
  42414. start++
  42415. }
  42416. //determine visible # of glyphs for the available width
  42417. var measured = measure(text, start, newLine, testWidth)
  42418. var lineEnd = start + (measured.end-measured.start)
  42419. var nextStart = lineEnd + newlineChar.length
  42420. //if we had to cut the line before the next newline...
  42421. if (lineEnd < newLine) {
  42422. //find char to break on
  42423. while (lineEnd > start) {
  42424. if (isWhitespace(text.charAt(lineEnd)))
  42425. break
  42426. lineEnd--
  42427. }
  42428. if (lineEnd === start) {
  42429. if (nextStart > start + newlineChar.length) nextStart--
  42430. lineEnd = nextStart // If no characters to break, show all.
  42431. } else {
  42432. nextStart = lineEnd
  42433. //eat whitespace at end of line
  42434. while (lineEnd > start) {
  42435. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  42436. break
  42437. lineEnd--
  42438. }
  42439. }
  42440. }
  42441. if (lineEnd >= start) {
  42442. var result = measure(text, start, lineEnd, testWidth)
  42443. lines.push(result)
  42444. }
  42445. start = nextStart
  42446. }
  42447. return lines
  42448. }
  42449. //determines the visible number of glyphs within a given width
  42450. function monospace(text, start, end, width) {
  42451. var glyphs = Math.min(width, end-start)
  42452. return {
  42453. start: start,
  42454. end: start+glyphs
  42455. }
  42456. }
  42457. },{}],73:[function(_dereq_,module,exports){
  42458. "use strict";
  42459. var window = _dereq_("global/window")
  42460. var isFunction = _dereq_("is-function")
  42461. var parseHeaders = _dereq_("parse-headers")
  42462. var xtend = _dereq_("xtend")
  42463. module.exports = createXHR
  42464. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  42465. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  42466. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  42467. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  42468. options = initParams(uri, options, callback)
  42469. options.method = method.toUpperCase()
  42470. return _createXHR(options)
  42471. }
  42472. })
  42473. function forEachArray(array, iterator) {
  42474. for (var i = 0; i < array.length; i++) {
  42475. iterator(array[i])
  42476. }
  42477. }
  42478. function isEmpty(obj){
  42479. for(var i in obj){
  42480. if(obj.hasOwnProperty(i)) return false
  42481. }
  42482. return true
  42483. }
  42484. function initParams(uri, options, callback) {
  42485. var params = uri
  42486. if (isFunction(options)) {
  42487. callback = options
  42488. if (typeof uri === "string") {
  42489. params = {uri:uri}
  42490. }
  42491. } else {
  42492. params = xtend(options, {uri: uri})
  42493. }
  42494. params.callback = callback
  42495. return params
  42496. }
  42497. function createXHR(uri, options, callback) {
  42498. options = initParams(uri, options, callback)
  42499. return _createXHR(options)
  42500. }
  42501. function _createXHR(options) {
  42502. if(typeof options.callback === "undefined"){
  42503. throw new Error("callback argument missing")
  42504. }
  42505. var called = false
  42506. var callback = function cbOnce(err, response, body){
  42507. if(!called){
  42508. called = true
  42509. options.callback(err, response, body)
  42510. }
  42511. }
  42512. function readystatechange() {
  42513. if (xhr.readyState === 4) {
  42514. loadFunc()
  42515. }
  42516. }
  42517. function getBody() {
  42518. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  42519. var body = undefined
  42520. if (xhr.response) {
  42521. body = xhr.response
  42522. } else {
  42523. body = xhr.responseText || getXml(xhr)
  42524. }
  42525. if (isJson) {
  42526. try {
  42527. body = JSON.parse(body)
  42528. } catch (e) {}
  42529. }
  42530. return body
  42531. }
  42532. function errorFunc(evt) {
  42533. clearTimeout(timeoutTimer)
  42534. if(!(evt instanceof Error)){
  42535. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  42536. }
  42537. evt.statusCode = 0
  42538. return callback(evt, failureResponse)
  42539. }
  42540. // will load the data & process the response in a special response object
  42541. function loadFunc() {
  42542. if (aborted) return
  42543. var status
  42544. clearTimeout(timeoutTimer)
  42545. if(options.useXDR && xhr.status===undefined) {
  42546. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  42547. status = 200
  42548. } else {
  42549. status = (xhr.status === 1223 ? 204 : xhr.status)
  42550. }
  42551. var response = failureResponse
  42552. var err = null
  42553. if (status !== 0){
  42554. response = {
  42555. body: getBody(),
  42556. statusCode: status,
  42557. method: method,
  42558. headers: {},
  42559. url: uri,
  42560. rawRequest: xhr
  42561. }
  42562. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  42563. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  42564. }
  42565. } else {
  42566. err = new Error("Internal XMLHttpRequest Error")
  42567. }
  42568. return callback(err, response, response.body)
  42569. }
  42570. var xhr = options.xhr || null
  42571. if (!xhr) {
  42572. if (options.cors || options.useXDR) {
  42573. xhr = new createXHR.XDomainRequest()
  42574. }else{
  42575. xhr = new createXHR.XMLHttpRequest()
  42576. }
  42577. }
  42578. var key
  42579. var aborted
  42580. var uri = xhr.url = options.uri || options.url
  42581. var method = xhr.method = options.method || "GET"
  42582. var body = options.body || options.data
  42583. var headers = xhr.headers = options.headers || {}
  42584. var sync = !!options.sync
  42585. var isJson = false
  42586. var timeoutTimer
  42587. var failureResponse = {
  42588. body: undefined,
  42589. headers: {},
  42590. statusCode: 0,
  42591. method: method,
  42592. url: uri,
  42593. rawRequest: xhr
  42594. }
  42595. if ("json" in options && options.json !== false) {
  42596. isJson = true
  42597. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  42598. if (method !== "GET" && method !== "HEAD") {
  42599. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  42600. body = JSON.stringify(options.json === true ? body : options.json)
  42601. }
  42602. }
  42603. xhr.onreadystatechange = readystatechange
  42604. xhr.onload = loadFunc
  42605. xhr.onerror = errorFunc
  42606. // IE9 must have onprogress be set to a unique function.
  42607. xhr.onprogress = function () {
  42608. // IE must die
  42609. }
  42610. xhr.onabort = function(){
  42611. aborted = true;
  42612. }
  42613. xhr.ontimeout = errorFunc
  42614. xhr.open(method, uri, !sync, options.username, options.password)
  42615. //has to be after open
  42616. if(!sync) {
  42617. xhr.withCredentials = !!options.withCredentials
  42618. }
  42619. // Cannot set timeout with sync request
  42620. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  42621. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  42622. if (!sync && options.timeout > 0 ) {
  42623. timeoutTimer = setTimeout(function(){
  42624. if (aborted) return
  42625. aborted = true//IE9 may still call readystatechange
  42626. xhr.abort("timeout")
  42627. var e = new Error("XMLHttpRequest timeout")
  42628. e.code = "ETIMEDOUT"
  42629. errorFunc(e)
  42630. }, options.timeout )
  42631. }
  42632. if (xhr.setRequestHeader) {
  42633. for(key in headers){
  42634. if(headers.hasOwnProperty(key)){
  42635. xhr.setRequestHeader(key, headers[key])
  42636. }
  42637. }
  42638. } else if (options.headers && !isEmpty(options.headers)) {
  42639. throw new Error("Headers cannot be set on an XDomainRequest object")
  42640. }
  42641. if ("responseType" in options) {
  42642. xhr.responseType = options.responseType
  42643. }
  42644. if ("beforeSend" in options &&
  42645. typeof options.beforeSend === "function"
  42646. ) {
  42647. options.beforeSend(xhr)
  42648. }
  42649. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  42650. // XMLHttpRequest spec says to pass null as body to indicate no body
  42651. // See https://github.com/naugtur/xhr/issues/100.
  42652. xhr.send(body || null)
  42653. return xhr
  42654. }
  42655. function getXml(xhr) {
  42656. if (xhr.responseType === "document") {
  42657. return xhr.responseXML
  42658. }
  42659. var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  42660. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  42661. return xhr.responseXML
  42662. }
  42663. return null
  42664. }
  42665. function noop() {}
  42666. },{"global/window":15,"is-function":20,"parse-headers":31,"xtend":75}],74:[function(_dereq_,module,exports){
  42667. module.exports = (function xmlparser() {
  42668. //common browsers
  42669. if (typeof window.DOMParser !== 'undefined') {
  42670. return function(str) {
  42671. var parser = new window.DOMParser()
  42672. return parser.parseFromString(str, 'application/xml')
  42673. }
  42674. }
  42675. //IE8 fallback
  42676. if (typeof window.ActiveXObject !== 'undefined'
  42677. && new window.ActiveXObject('Microsoft.XMLDOM')) {
  42678. return function(str) {
  42679. var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM")
  42680. xmlDoc.async = "false"
  42681. xmlDoc.loadXML(str)
  42682. return xmlDoc
  42683. }
  42684. }
  42685. //last resort fallback
  42686. return function(str) {
  42687. var div = document.createElement('div')
  42688. div.innerHTML = str
  42689. return div
  42690. }
  42691. })()
  42692. },{}],75:[function(_dereq_,module,exports){
  42693. module.exports = extend
  42694. var hasOwnProperty = Object.prototype.hasOwnProperty;
  42695. function extend() {
  42696. var target = {}
  42697. for (var i = 0; i < arguments.length; i++) {
  42698. var source = arguments[i]
  42699. for (var key in source) {
  42700. if (hasOwnProperty.call(source, key)) {
  42701. target[key] = source[key]
  42702. }
  42703. }
  42704. }
  42705. return target
  42706. }
  42707. },{}],76:[function(_dereq_,module,exports){
  42708. module.exports={
  42709. "name": "aframe",
  42710. "version": "0.7.0",
  42711. "description": "A web framework for building virtual reality experiences.",
  42712. "homepage": "https://aframe.io/",
  42713. "main": "dist/aframe-master.js",
  42714. "scripts": {
  42715. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  42716. "build": "shx mkdir -p build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  42717. "codecov": "codecov",
  42718. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  42719. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  42720. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  42721. "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",
  42722. "docs": "markserv --dir docs --port 9001",
  42723. "preghpages": "node ./scripts/preghpages.js",
  42724. "ghpages": "ghpages -p gh-pages/",
  42725. "lint": "semistandard -v | snazzy",
  42726. "lint:fix": "semistandard --fix",
  42727. "precommit": "npm run lint",
  42728. "prepush": "node scripts/testOnlyCheck.js",
  42729. "prerelease": "node scripts/release.js 0.6.1 0.7.0",
  42730. "start": "npm run dev",
  42731. "test": "karma start ./tests/karma.conf.js",
  42732. "test:docs": "node scripts/docsLint.js",
  42733. "test:firefox": "npm test -- --browsers Firefox",
  42734. "test:chrome": "npm test -- --browsers Chrome",
  42735. "test:node": "mocha --ui tdd tests/node"
  42736. },
  42737. "repository": "aframevr/aframe",
  42738. "license": "MIT",
  42739. "dependencies": {
  42740. "@tweenjs/tween.js": "^16.8.0",
  42741. "browserify-css": "^0.8.2",
  42742. "debug": "ngokevin/debug#noTimestamp",
  42743. "deep-assign": "^2.0.0",
  42744. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  42745. "envify": "^3.4.1",
  42746. "load-bmfont": "^1.2.3",
  42747. "object-assign": "^4.0.1",
  42748. "present": "0.0.6",
  42749. "promise-polyfill": "^3.1.0",
  42750. "style-attr": "^1.0.2",
  42751. "three": "github:dmarcos/three.js#r89fix",
  42752. "three-bmfont-text": "^2.1.0",
  42753. "webvr-polyfill": "^0.9.40"
  42754. },
  42755. "devDependencies": {
  42756. "browserify": "^13.1.0",
  42757. "browserify-derequire": "^0.9.4",
  42758. "browserify-istanbul": "^2.0.0",
  42759. "budo": "^9.2.0",
  42760. "chai": "^3.5.0",
  42761. "chai-shallow-deep-equal": "^1.4.0",
  42762. "chalk": "^1.1.3",
  42763. "codecov": "^1.0.1",
  42764. "cross-env": "^5.0.1",
  42765. "exorcist": "^0.4.0",
  42766. "ghpages": "0.0.8",
  42767. "git-rev": "^0.2.1",
  42768. "glob": "^7.1.1",
  42769. "husky": "^0.11.7",
  42770. "istanbul": "^0.4.5",
  42771. "jsdom": "^9.11.0",
  42772. "karma": "1.4.1",
  42773. "karma-browserify": "^5.1.0",
  42774. "karma-chai-shallow-deep-equal": "0.0.4",
  42775. "karma-chrome-launcher": "^2.0.0",
  42776. "karma-coverage": "^1.1.1",
  42777. "karma-env-preprocessor": "^0.1.1",
  42778. "karma-firefox-launcher": "^1.0.0",
  42779. "karma-mocha": "^1.1.1",
  42780. "karma-mocha-reporter": "^2.1.0",
  42781. "karma-sinon-chai": "1.2.4",
  42782. "lolex": "^1.5.1",
  42783. "markserv": "github:sukima/markserv#feature/fix-broken-websoketio-link",
  42784. "minifyify": "^7.3.3",
  42785. "mocha": "^3.0.2",
  42786. "mozilla-download": "^1.1.1",
  42787. "replace-in-file": "^2.5.3",
  42788. "semistandard": "^9.0.0",
  42789. "shelljs": "^0.7.7",
  42790. "shx": "^0.2.2",
  42791. "sinon": "^1.17.5",
  42792. "sinon-chai": "2.8.0",
  42793. "snazzy": "^5.0.0",
  42794. "too-wordy": "ngokevin/too-wordy",
  42795. "uglifyjs": "^2.4.10",
  42796. "write-good": "^0.9.1"
  42797. },
  42798. "link": true,
  42799. "browserify": {
  42800. "transform": [
  42801. "browserify-css",
  42802. "envify"
  42803. ]
  42804. },
  42805. "semistandard": {
  42806. "ignore": [
  42807. "build/**",
  42808. "dist/**",
  42809. "examples/**/shaders/*.js",
  42810. "**/vendor/**"
  42811. ]
  42812. },
  42813. "keywords": [
  42814. "3d",
  42815. "aframe",
  42816. "cardboard",
  42817. "components",
  42818. "oculus",
  42819. "three",
  42820. "three.js",
  42821. "rift",
  42822. "vive",
  42823. "vr",
  42824. "web-components",
  42825. "webvr"
  42826. ],
  42827. "browserify-css": {
  42828. "minify": true
  42829. },
  42830. "engines": {
  42831. "node": ">= 4.6.0",
  42832. "npm": "^2.15.9"
  42833. }
  42834. }
  42835. },{}],77:[function(_dereq_,module,exports){
  42836. var registerComponent = _dereq_('../core/component').registerComponent;
  42837. var THREE = _dereq_('../lib/three');
  42838. /**
  42839. * Camera component.
  42840. * Pairs along with camera system to handle tracking the active camera.
  42841. */
  42842. module.exports.Component = registerComponent('camera', {
  42843. schema: {
  42844. active: {default: true},
  42845. far: {default: 10000},
  42846. fov: {default: 80, min: 0},
  42847. near: {default: 0.005, min: 0},
  42848. spectator: {default: false},
  42849. zoom: {default: 1, min: 0}
  42850. },
  42851. /**
  42852. * Initialize three.js camera and add it to the entity.
  42853. * Add reference from scene to this entity as the camera.
  42854. */
  42855. init: function () {
  42856. var camera;
  42857. var el = this.el;
  42858. // Create camera.
  42859. camera = this.camera = new THREE.PerspectiveCamera();
  42860. el.setObject3D('camera', camera);
  42861. },
  42862. /**
  42863. * Update three.js camera.
  42864. */
  42865. update: function (oldData) {
  42866. var data = this.data;
  42867. var camera = this.camera;
  42868. // Update properties.
  42869. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  42870. camera.far = data.far;
  42871. camera.fov = data.fov;
  42872. camera.near = data.near;
  42873. camera.zoom = data.zoom;
  42874. camera.updateProjectionMatrix();
  42875. this.updateActiveCamera(oldData);
  42876. this.updateSpectatorCamera(oldData);
  42877. },
  42878. updateActiveCamera: function (oldData) {
  42879. var data = this.data;
  42880. var el = this.el;
  42881. var system = this.system;
  42882. // Active property did not change.
  42883. if (oldData && oldData.active === data.active || data.spectator) { return; }
  42884. // If `active` property changes, or first update, handle active camera with system.
  42885. if (data.active && system.activeCameraEl !== el) {
  42886. // Camera enabled. Set camera to this camera.
  42887. system.setActiveCamera(el);
  42888. } else if (!data.active && system.activeCameraEl === el) {
  42889. // Camera disabled. Set camera to another camera.
  42890. system.disableActiveCamera();
  42891. }
  42892. },
  42893. updateSpectatorCamera: function (oldData) {
  42894. var data = this.data;
  42895. var el = this.el;
  42896. var system = this.system;
  42897. // spectator property did not change.
  42898. if (oldData && oldData.spectator === data.spectator) { return; }
  42899. // If `spectator` property changes, or first update, handle spectator camera with system.
  42900. if (data.spectator && system.spectatorCameraEl !== el) {
  42901. // Camera enabled. Set camera to this camera.
  42902. system.setSpectatorCamera(el);
  42903. } else if (!data.spectator && system.spectatorCameraEl === el) {
  42904. // Camera disabled. Set camera to another camera.
  42905. system.disableSpectatorCamera();
  42906. }
  42907. },
  42908. /**
  42909. * Remove camera on remove (callback).
  42910. */
  42911. remove: function () {
  42912. this.el.removeObject3D('camera');
  42913. }
  42914. });
  42915. },{"../core/component":126,"../lib/three":174}],78:[function(_dereq_,module,exports){
  42916. var registerComponent = _dereq_('../core/component').registerComponent;
  42917. var THREE = _dereq_('../lib/three');
  42918. module.exports.Component = registerComponent('collada-model', {
  42919. schema: {type: 'asset'},
  42920. init: function () {
  42921. this.model = null;
  42922. this.loader = new THREE.ColladaLoader();
  42923. this.loader.options.convertUpAxis = true;
  42924. },
  42925. update: function () {
  42926. var self = this;
  42927. var el = this.el;
  42928. var src = this.data;
  42929. if (!src) { return; }
  42930. this.remove();
  42931. this.loader.load(src, function (colladaModel) {
  42932. self.model = colladaModel.scene;
  42933. el.setObject3D('mesh', self.model);
  42934. el.emit('model-loaded', {format: 'collada', model: self.model});
  42935. });
  42936. },
  42937. remove: function () {
  42938. if (!this.model) { return; }
  42939. this.el.removeObject3D('mesh');
  42940. }
  42941. });
  42942. },{"../core/component":126,"../lib/three":174}],79:[function(_dereq_,module,exports){
  42943. /* global THREE */
  42944. var registerComponent = _dereq_('../core/component').registerComponent;
  42945. var utils = _dereq_('../utils/');
  42946. var bind = utils.bind;
  42947. var EVENTS = {
  42948. CLICK: 'click',
  42949. FUSING: 'fusing',
  42950. MOUSEENTER: 'mouseenter',
  42951. MOUSEDOWN: 'mousedown',
  42952. MOUSELEAVE: 'mouseleave',
  42953. MOUSEUP: 'mouseup'
  42954. };
  42955. var STATES = {
  42956. FUSING: 'cursor-fusing',
  42957. HOVERING: 'cursor-hovering',
  42958. HOVERED: 'cursor-hovered'
  42959. };
  42960. var CANVAS_EVENTS = {
  42961. DOWN: ['mousedown', 'touchstart'],
  42962. UP: ['mouseup', 'touchend']
  42963. };
  42964. /**
  42965. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  42966. * from the camera and pointing from camera's facing direction, and then only returning the
  42967. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  42968. *
  42969. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  42970. * @member {Element} cursorDownEl - Entity that was last mousedowned during current click.
  42971. * @member {object} intersection - Attributes of the current intersection event, including
  42972. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  42973. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  42974. * emit events when unintersecting.
  42975. */
  42976. module.exports.Component = registerComponent('cursor', {
  42977. dependencies: ['raycaster'],
  42978. schema: {
  42979. downEvents: {default: []},
  42980. fuse: {default: utils.device.isMobile()},
  42981. fuseTimeout: {default: 1500, min: 0},
  42982. upEvents: {default: []},
  42983. rayOrigin: {default: 'entity', oneOf: ['mouse', 'entity']}
  42984. },
  42985. init: function () {
  42986. var self = this;
  42987. this.fuseTimeout = undefined;
  42988. this.cursorDownEl = null;
  42989. this.intersection = null;
  42990. this.intersectedEl = null;
  42991. this.canvasBounds = document.body.getBoundingClientRect();
  42992. // Debounce.
  42993. this.updateCanvasBounds = utils.debounce(function updateCanvasBounds () {
  42994. self.canvasBounds = self.el.sceneEl.canvas.getBoundingClientRect();
  42995. }, 200);
  42996. this.eventDetail = {};
  42997. this.intersectedEventDetail = {cursorEl: this.el};
  42998. // Bind methods.
  42999. this.onCursorDown = bind(this.onCursorDown, this);
  43000. this.onCursorUp = bind(this.onCursorUp, this);
  43001. this.onIntersection = bind(this.onIntersection, this);
  43002. this.onIntersectionCleared = bind(this.onIntersectionCleared, this);
  43003. this.onMouseMove = bind(this.onMouseMove, this);
  43004. },
  43005. update: function (oldData) {
  43006. if (this.data.rayOrigin === oldData.rayOrigin) { return; }
  43007. this.updateMouseEventListeners();
  43008. },
  43009. play: function () {
  43010. this.addEventListeners();
  43011. },
  43012. pause: function () {
  43013. this.removeEventListeners();
  43014. },
  43015. remove: function () {
  43016. var el = this.el;
  43017. el.removeState(STATES.HOVERING);
  43018. el.removeState(STATES.FUSING);
  43019. clearTimeout(this.fuseTimeout);
  43020. if (this.intersectedEl) { this.intersectedEl.removeState(STATES.HOVERED); }
  43021. this.removeEventListeners();
  43022. },
  43023. addEventListeners: function () {
  43024. var canvas;
  43025. var data = this.data;
  43026. var el = this.el;
  43027. var self = this;
  43028. function addCanvasListeners () {
  43029. canvas = el.sceneEl.canvas;
  43030. if (data.downEvents.length || data.upEvents.length) { return; }
  43031. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43032. canvas.addEventListener(downEvent, self.onCursorDown);
  43033. });
  43034. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43035. canvas.addEventListener(upEvent, self.onCursorUp);
  43036. });
  43037. }
  43038. canvas = el.sceneEl.canvas;
  43039. if (canvas) {
  43040. addCanvasListeners();
  43041. } else {
  43042. el.sceneEl.addEventListener('render-target-loaded', addCanvasListeners);
  43043. }
  43044. data.downEvents.forEach(function (downEvent) {
  43045. el.addEventListener(downEvent, self.onCursorDown);
  43046. });
  43047. data.upEvents.forEach(function (upEvent) {
  43048. el.addEventListener(upEvent, self.onCursorUp);
  43049. });
  43050. el.addEventListener('raycaster-intersection', this.onIntersection);
  43051. el.addEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43052. window.addEventListener('resize', this.updateCanvasBounds);
  43053. },
  43054. removeEventListeners: function () {
  43055. var canvas;
  43056. var data = this.data;
  43057. var el = this.el;
  43058. var self = this;
  43059. canvas = el.sceneEl.canvas;
  43060. if (canvas && !data.downEvents.length && !data.upEvents.length) {
  43061. CANVAS_EVENTS.DOWN.forEach(function (downEvent) {
  43062. canvas.removeEventListener(downEvent, self.onCursorDown);
  43063. });
  43064. CANVAS_EVENTS.UP.forEach(function (upEvent) {
  43065. canvas.removeEventListener(upEvent, self.onCursorUp);
  43066. });
  43067. }
  43068. data.downEvents.forEach(function (downEvent) {
  43069. el.removeEventListener(downEvent, self.onCursorDown);
  43070. });
  43071. data.upEvents.forEach(function (upEvent) {
  43072. el.removeEventListener(upEvent, self.onCursorUp);
  43073. });
  43074. el.removeEventListener('raycaster-intersection', this.onIntersection);
  43075. el.removeEventListener('raycaster-intersection-cleared', this.onIntersectionCleared);
  43076. canvas.removeEventListener('mousemove', this.onMouseMove);
  43077. canvas.removeEventListener('touchstart', this.onMouseMove);
  43078. canvas.removeEventListener('touchmove', this.onMouseMove);
  43079. canvas.removeEventListener('resize', this.updateCanvasBounds);
  43080. },
  43081. updateMouseEventListeners: function () {
  43082. var canvas;
  43083. var el = this.el;
  43084. canvas = el.sceneEl.canvas;
  43085. canvas.removeEventListener('mousemove', this.onMouseMove);
  43086. canvas.removeEventListener('touchmove', this.onMouseMove);
  43087. el.setAttribute('raycaster', 'useWorldCoordinates', false);
  43088. if (this.data.rayOrigin !== 'mouse') { return; }
  43089. canvas.addEventListener('mousemove', this.onMouseMove, false);
  43090. canvas.addEventListener('touchmove', this.onMouseMove, false);
  43091. el.setAttribute('raycaster', 'useWorldCoordinates', true);
  43092. this.updateCanvasBounds();
  43093. },
  43094. onMouseMove: (function () {
  43095. var direction = new THREE.Vector3();
  43096. var mouse = new THREE.Vector2();
  43097. var origin = new THREE.Vector3();
  43098. var rayCasterConfig = {origin: origin, direction: direction};
  43099. return function (evt) {
  43100. var bounds = this.canvasBounds;
  43101. var camera = this.el.sceneEl.camera;
  43102. var left;
  43103. var point;
  43104. var top;
  43105. camera.parent.updateMatrixWorld();
  43106. camera.updateMatrixWorld();
  43107. // Calculate mouse position based on the canvas element
  43108. if (evt.type === 'touchmove' || evt.type === 'touchstart') {
  43109. // Track the first touch for simplicity.
  43110. point = evt.touches.item(0);
  43111. } else {
  43112. point = evt;
  43113. }
  43114. left = point.clientX - bounds.left;
  43115. top = point.clientY - bounds.top;
  43116. mouse.x = (left / bounds.width) * 2 - 1;
  43117. mouse.y = -(top / bounds.height) * 2 + 1;
  43118. origin.setFromMatrixPosition(camera.matrixWorld);
  43119. direction.set(mouse.x, mouse.y, 0.5).unproject(camera).sub(origin).normalize();
  43120. this.el.setAttribute('raycaster', rayCasterConfig);
  43121. if (evt.type === 'touchmove') { evt.preventDefault(); }
  43122. };
  43123. })(),
  43124. /**
  43125. * Trigger mousedown and keep track of the mousedowned entity.
  43126. */
  43127. onCursorDown: function (evt) {
  43128. // Raycast again for touch.
  43129. if (this.data.rayOrigin === 'mouse' && evt.type === 'touchstart') {
  43130. this.onMouseMove(evt);
  43131. this.el.components.raycaster.checkIntersections();
  43132. evt.preventDefault();
  43133. }
  43134. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43135. this.cursorDownEl = this.intersectedEl;
  43136. },
  43137. /**
  43138. * Trigger mouseup if:
  43139. * - Not fusing (mobile has no mouse).
  43140. * - Currently intersecting an entity.
  43141. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43142. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43143. */
  43144. onCursorUp: function (evt) {
  43145. this.twoWayEmit(EVENTS.MOUSEUP);
  43146. // If intersected entity has changed since the cursorDown, still emit mouseUp on the
  43147. // previously cursorUp entity.
  43148. if (this.cursorDownEl && this.cursorDownEl !== this.intersectedEl) {
  43149. this.intersectedEventDetail.intersection = null;
  43150. this.cursorDownEl.emit(EVENTS.MOUSEUP, this.intersectedEventDetail);
  43151. }
  43152. if (!this.data.fuse && this.intersectedEl && this.cursorDownEl === this.intersectedEl) {
  43153. this.twoWayEmit(EVENTS.CLICK);
  43154. }
  43155. this.cursorDownEl = null;
  43156. if (evt.type === 'touchend') { evt.preventDefault(); }
  43157. },
  43158. /**
  43159. * Handle intersection.
  43160. */
  43161. onIntersection: function (evt) {
  43162. var cursorEl = this.el;
  43163. var index;
  43164. var intersectedEl;
  43165. var intersection;
  43166. // Select closest object, excluding the cursor.
  43167. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43168. intersection = evt.detail.intersections[index];
  43169. intersectedEl = evt.detail.els[index];
  43170. // If cursor is the only intersected object, ignore the event.
  43171. if (!intersectedEl) { return; }
  43172. // Already intersecting this entity.
  43173. if (this.intersectedEl === intersectedEl) {
  43174. this.intersection = intersection;
  43175. return;
  43176. }
  43177. // Unset current intersection.
  43178. if (this.intersectedEl) { this.clearCurrentIntersection(); }
  43179. this.setIntersection(intersectedEl, intersection);
  43180. },
  43181. /**
  43182. * Handle intersection cleared.
  43183. */
  43184. onIntersectionCleared: function (evt) {
  43185. var clearedEls = evt.detail.clearedEls;
  43186. // Check if the current intersection has ended
  43187. if (clearedEls.indexOf(this.intersectedEl) === -1) { return; }
  43188. this.clearCurrentIntersection();
  43189. },
  43190. setIntersection: function (intersectedEl, intersection) {
  43191. var cursorEl = this.el;
  43192. var data = this.data;
  43193. var self = this;
  43194. // Set new intersection.
  43195. this.intersection = intersection;
  43196. this.intersectedEl = intersectedEl;
  43197. // Hovering.
  43198. cursorEl.addState(STATES.HOVERING);
  43199. intersectedEl.addState(STATES.HOVERED);
  43200. this.twoWayEmit(EVENTS.MOUSEENTER);
  43201. // Begin fuse if necessary.
  43202. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43203. cursorEl.addState(STATES.FUSING);
  43204. this.twoWayEmit(EVENTS.FUSING);
  43205. this.fuseTimeout = setTimeout(function fuse () {
  43206. cursorEl.removeState(STATES.FUSING);
  43207. self.twoWayEmit(EVENTS.CLICK);
  43208. }, data.fuseTimeout);
  43209. },
  43210. clearCurrentIntersection: function () {
  43211. var cursorEl = this.el;
  43212. var index;
  43213. var intersection;
  43214. var intersections;
  43215. // No longer hovering (or fusing).
  43216. this.intersectedEl.removeState(STATES.HOVERED);
  43217. cursorEl.removeState(STATES.HOVERING);
  43218. cursorEl.removeState(STATES.FUSING);
  43219. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43220. // Unset intersected entity (after emitting the event).
  43221. this.intersection = null;
  43222. this.intersectedEl = null;
  43223. // Clear fuseTimeout.
  43224. clearTimeout(this.fuseTimeout);
  43225. // Set intersection to another raycasted element if any.
  43226. intersections = this.el.components.raycaster.intersections;
  43227. if (intersections.length === 0) { return; }
  43228. // exclude the cursor.
  43229. index = intersections[0].object.el === cursorEl ? 1 : 0;
  43230. intersection = intersections[index];
  43231. if (!intersection) { return; }
  43232. this.setIntersection(intersection.object.el, intersection);
  43233. },
  43234. /**
  43235. * Helper to emit on both the cursor and the intersected entity (if exists).
  43236. */
  43237. twoWayEmit: function (evtName) {
  43238. var el = this.el;
  43239. var intersectedEl = this.intersectedEl;
  43240. var intersection = this.intersection;
  43241. this.eventDetail.intersectedEl = intersectedEl;
  43242. this.eventDetail.intersection = intersection;
  43243. el.emit(evtName, this.eventDetail);
  43244. if (!intersectedEl) { return; }
  43245. this.intersectedEventDetail.intersection = intersection;
  43246. intersectedEl.emit(evtName, this.intersectedEventDetail);
  43247. }
  43248. });
  43249. },{"../core/component":126,"../utils/":196}],80:[function(_dereq_,module,exports){
  43250. var registerComponent = _dereq_('../core/component').registerComponent;
  43251. var bind = _dereq_('../utils/bind');
  43252. var checkControllerPresentAndSetup = _dereq_('../utils/tracked-controls').checkControllerPresentAndSetup;
  43253. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43254. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43255. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43256. var DAYDREAM_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/google/';
  43257. var DAYDREAM_CONTROLLER_MODEL_OBJ_URL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.obj';
  43258. var DAYDREAM_CONTROLLER_MODEL_OBJ_MTL = DAYDREAM_CONTROLLER_MODEL_BASE_URL + 'vr_controller_daydream.mtl';
  43259. var GAMEPAD_ID_PREFIX = 'Daydream Controller';
  43260. /**
  43261. * Daydream controls.
  43262. * Interface with Daydream controller and map Gamepad events to
  43263. * controller buttons: trackpad, menu, system
  43264. * Load a controller model and highlight the pressed buttons.
  43265. */
  43266. module.exports.Component = registerComponent('daydream-controls', {
  43267. schema: {
  43268. hand: {default: ''}, // This informs the degenerate arm model.
  43269. buttonColor: {type: 'color', default: '#000000'},
  43270. buttonTouchedColor: {type: 'color', default: '#777777'},
  43271. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43272. model: {default: true},
  43273. rotationOffset: {default: 0},
  43274. armModel: {default: true}
  43275. },
  43276. /**
  43277. * Button IDs:
  43278. * 0 - trackpad
  43279. * 1 - menu (never dispatched on this layer)
  43280. * 2 - system (never dispatched on this layer)
  43281. */
  43282. mapping: {
  43283. axes: {trackpad: [0, 1]},
  43284. buttons: ['trackpad', 'menu', 'system']
  43285. },
  43286. bindMethods: function () {
  43287. this.onModelLoaded = bind(this.onModelLoaded, this);
  43288. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43289. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43290. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43291. this.onAxisMoved = bind(this.onAxisMoved, this);
  43292. },
  43293. init: function () {
  43294. var self = this;
  43295. this.animationActive = 'pointing';
  43296. this.onButtonChanged = bind(this.onButtonChanged, this);
  43297. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43298. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43299. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43300. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43301. this.onAxisMoved = bind(this.onAxisMoved, this);
  43302. this.controllerPresent = false;
  43303. this.lastControllerCheck = 0;
  43304. this.bindMethods();
  43305. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43306. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43307. },
  43308. addEventListeners: function () {
  43309. var el = this.el;
  43310. el.addEventListener('buttonchanged', this.onButtonChanged);
  43311. el.addEventListener('buttondown', this.onButtonDown);
  43312. el.addEventListener('buttonup', this.onButtonUp);
  43313. el.addEventListener('touchstart', this.onButtonTouchStart);
  43314. el.addEventListener('touchend', this.onButtonTouchEnd);
  43315. el.addEventListener('model-loaded', this.onModelLoaded);
  43316. el.addEventListener('axismove', this.onAxisMoved);
  43317. this.controllerEventsActive = true;
  43318. },
  43319. removeEventListeners: function () {
  43320. var el = this.el;
  43321. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43322. el.removeEventListener('buttondown', this.onButtonDown);
  43323. el.removeEventListener('buttonup', this.onButtonUp);
  43324. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43325. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43326. el.removeEventListener('model-loaded', this.onModelLoaded);
  43327. el.removeEventListener('axismove', this.onAxisMoved);
  43328. this.controllerEventsActive = false;
  43329. },
  43330. checkIfControllerPresent: function () {
  43331. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {hand: this.data.hand});
  43332. },
  43333. play: function () {
  43334. this.checkIfControllerPresent();
  43335. this.addControllersUpdateListener();
  43336. },
  43337. pause: function () {
  43338. this.removeEventListeners();
  43339. this.removeControllersUpdateListener();
  43340. },
  43341. injectTrackedControls: function () {
  43342. var el = this.el;
  43343. var data = this.data;
  43344. el.setAttribute('tracked-controls', {
  43345. armModel: data.armModel,
  43346. hand: data.hand,
  43347. idPrefix: GAMEPAD_ID_PREFIX,
  43348. rotationOffset: data.rotationOffset
  43349. });
  43350. if (!this.data.model) { return; }
  43351. this.el.setAttribute('obj-model', {
  43352. obj: DAYDREAM_CONTROLLER_MODEL_OBJ_URL,
  43353. mtl: DAYDREAM_CONTROLLER_MODEL_OBJ_MTL
  43354. });
  43355. },
  43356. addControllersUpdateListener: function () {
  43357. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43358. },
  43359. removeControllersUpdateListener: function () {
  43360. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43361. },
  43362. onControllersUpdate: function () {
  43363. this.checkIfControllerPresent();
  43364. },
  43365. onModelLoaded: function (evt) {
  43366. var controllerObject3D = evt.detail.model;
  43367. var buttonMeshes;
  43368. if (!this.data.model) { return; }
  43369. buttonMeshes = this.buttonMeshes = {};
  43370. buttonMeshes.menu = controllerObject3D.getObjectByName('AppButton_AppButton_Cylinder.004');
  43371. buttonMeshes.system = controllerObject3D.getObjectByName('HomeButton_HomeButton_Cylinder.005');
  43372. buttonMeshes.trackpad = controllerObject3D.getObjectByName('TouchPad_TouchPad_Cylinder.003');
  43373. // Offset pivot point.
  43374. controllerObject3D.position.set(0, 0, -0.04);
  43375. },
  43376. onAxisMoved: function (evt) {
  43377. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43378. },
  43379. onButtonChanged: function (evt) {
  43380. var button = this.mapping.buttons[evt.detail.id];
  43381. if (!button) return;
  43382. // Pass along changed event with button state, using button mapping for convenience.
  43383. this.el.emit(button + 'changed', evt.detail.state);
  43384. },
  43385. updateModel: function (buttonName, evtName) {
  43386. if (!this.data.model) { return; }
  43387. this.updateButtonModel(buttonName, evtName);
  43388. },
  43389. updateButtonModel: function (buttonName, state) {
  43390. var buttonMeshes = this.buttonMeshes;
  43391. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43392. var color;
  43393. switch (state) {
  43394. case 'down':
  43395. color = this.data.buttonHighlightColor;
  43396. break;
  43397. case 'touchstart':
  43398. color = this.data.buttonTouchedColor;
  43399. break;
  43400. default:
  43401. color = this.data.buttonColor;
  43402. }
  43403. buttonMeshes[buttonName].material.color.set(color);
  43404. }
  43405. });
  43406. },{"../core/component":126,"../utils/bind":190,"../utils/tracked-controls":201}],81:[function(_dereq_,module,exports){
  43407. var registerComponent = _dereq_('../core/component').registerComponent;
  43408. var bind = _dereq_('../utils/bind');
  43409. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  43410. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  43411. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  43412. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  43413. var GEARVR_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/samsung/';
  43414. var GEARVR_CONTROLLER_MODEL_OBJ_URL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.obj';
  43415. var GEARVR_CONTROLLER_MODEL_OBJ_MTL = GEARVR_CONTROLLER_MODEL_BASE_URL + 'gear_vr_controller.mtl';
  43416. var GAMEPAD_ID_PREFIX = 'Gear VR';
  43417. /**
  43418. * Gear VR controls.
  43419. * Interface with Gear VR controller and map Gamepad events to
  43420. * controller buttons: trackpad, trigger
  43421. * Load a controller model and highlight the pressed buttons.
  43422. */
  43423. module.exports.Component = registerComponent('gearvr-controls', {
  43424. schema: {
  43425. hand: {default: ''}, // This informs the degenerate arm model.
  43426. buttonColor: {type: 'color', default: '#000000'},
  43427. buttonTouchedColor: {type: 'color', default: '#777777'},
  43428. buttonHighlightColor: {type: 'color', default: '#FFFFFF'},
  43429. model: {default: true},
  43430. rotationOffset: {default: 0},
  43431. armModel: {default: true}
  43432. },
  43433. /**
  43434. * Button IDs:
  43435. * 0 - trackpad
  43436. * 1 - trigger
  43437. */
  43438. mapping: {
  43439. axes: {trackpad: [0, 1]},
  43440. buttons: ['trackpad', 'trigger']
  43441. },
  43442. bindMethods: function () {
  43443. this.onModelLoaded = bind(this.onModelLoaded, this);
  43444. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  43445. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  43446. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  43447. this.onAxisMoved = bind(this.onAxisMoved, this);
  43448. },
  43449. init: function () {
  43450. var self = this;
  43451. this.animationActive = 'pointing';
  43452. this.onButtonChanged = bind(this.onButtonChanged, this);
  43453. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  43454. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  43455. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  43456. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  43457. this.onAxisMoved = bind(this.onAxisMoved, this);
  43458. this.controllerPresent = false;
  43459. this.lastControllerCheck = 0;
  43460. this.bindMethods();
  43461. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  43462. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  43463. },
  43464. addEventListeners: function () {
  43465. var el = this.el;
  43466. el.addEventListener('buttonchanged', this.onButtonChanged);
  43467. el.addEventListener('buttondown', this.onButtonDown);
  43468. el.addEventListener('buttonup', this.onButtonUp);
  43469. el.addEventListener('touchstart', this.onButtonTouchStart);
  43470. el.addEventListener('touchend', this.onButtonTouchEnd);
  43471. el.addEventListener('model-loaded', this.onModelLoaded);
  43472. el.addEventListener('axismove', this.onAxisMoved);
  43473. this.controllerEventsActive = true;
  43474. this.addControllersUpdateListener();
  43475. },
  43476. removeEventListeners: function () {
  43477. var el = this.el;
  43478. el.removeEventListener('buttonchanged', this.onButtonChanged);
  43479. el.removeEventListener('buttondown', this.onButtonDown);
  43480. el.removeEventListener('buttonup', this.onButtonUp);
  43481. el.removeEventListener('touchstart', this.onButtonTouchStart);
  43482. el.removeEventListener('touchend', this.onButtonTouchEnd);
  43483. el.removeEventListener('model-loaded', this.onModelLoaded);
  43484. el.removeEventListener('axismove', this.onAxisMoved);
  43485. this.controllerEventsActive = false;
  43486. this.removeControllersUpdateListener();
  43487. },
  43488. checkIfControllerPresent: function () {
  43489. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX,
  43490. this.data.hand ? {hand: this.data.hand} : {});
  43491. },
  43492. play: function () {
  43493. this.checkIfControllerPresent();
  43494. this.addControllersUpdateListener();
  43495. },
  43496. pause: function () {
  43497. this.removeEventListeners();
  43498. this.removeControllersUpdateListener();
  43499. },
  43500. injectTrackedControls: function () {
  43501. var el = this.el;
  43502. var data = this.data;
  43503. el.setAttribute('tracked-controls', {
  43504. armModel: data.armModel,
  43505. idPrefix: GAMEPAD_ID_PREFIX,
  43506. rotationOffset: data.rotationOffset
  43507. });
  43508. if (!this.data.model) { return; }
  43509. this.el.setAttribute('obj-model', {
  43510. obj: GEARVR_CONTROLLER_MODEL_OBJ_URL,
  43511. mtl: GEARVR_CONTROLLER_MODEL_OBJ_MTL
  43512. });
  43513. },
  43514. addControllersUpdateListener: function () {
  43515. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  43516. },
  43517. removeControllersUpdateListener: function () {
  43518. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  43519. },
  43520. onControllersUpdate: function () {
  43521. this.checkIfControllerPresent();
  43522. },
  43523. // No need for onButtonChanged, since Gear VR controller has no analog buttons.
  43524. onModelLoaded: function (evt) {
  43525. var controllerObject3D = evt.detail.model;
  43526. var buttonMeshes;
  43527. if (!this.data.model) { return; }
  43528. buttonMeshes = this.buttonMeshes = {};
  43529. buttonMeshes.trigger = controllerObject3D.children[2];
  43530. buttonMeshes.trackpad = controllerObject3D.children[1];
  43531. },
  43532. onButtonChanged: function (evt) {
  43533. var button = this.mapping.buttons[evt.detail.id];
  43534. if (!button) return;
  43535. // Pass along changed event with button state, using button mapping for convenience.
  43536. this.el.emit(button + 'changed', evt.detail.state);
  43537. },
  43538. onAxisMoved: function (evt) {
  43539. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  43540. },
  43541. updateModel: function (buttonName, evtName) {
  43542. if (!this.data.model) { return; }
  43543. this.updateButtonModel(buttonName, evtName);
  43544. },
  43545. updateButtonModel: function (buttonName, state) {
  43546. var buttonMeshes = this.buttonMeshes;
  43547. if (!buttonMeshes || !buttonMeshes[buttonName]) { return; }
  43548. var color;
  43549. switch (state) {
  43550. case 'down':
  43551. color = this.data.buttonHighlightColor;
  43552. break;
  43553. case 'touchstart':
  43554. color = this.data.buttonTouchedColor;
  43555. break;
  43556. default:
  43557. color = this.data.buttonColor;
  43558. }
  43559. buttonMeshes[buttonName].material.color.set(color);
  43560. }
  43561. });
  43562. },{"../core/component":126,"../utils/bind":190,"../utils/tracked-controls":201}],82:[function(_dereq_,module,exports){
  43563. var geometries = _dereq_('../core/geometry').geometries;
  43564. var geometryNames = _dereq_('../core/geometry').geometryNames;
  43565. var registerComponent = _dereq_('../core/component').registerComponent;
  43566. var THREE = _dereq_('../lib/three');
  43567. var dummyGeometry = new THREE.Geometry();
  43568. /**
  43569. * Geometry component. Combined with material component to make a mesh in 3D object.
  43570. * Extended with registered geometries.
  43571. */
  43572. module.exports.Component = registerComponent('geometry', {
  43573. schema: {
  43574. buffer: {default: true},
  43575. primitive: {default: 'box', oneOf: geometryNames},
  43576. skipCache: {default: false}
  43577. },
  43578. init: function () {
  43579. this.geometry = null;
  43580. },
  43581. /**
  43582. * Talk to geometry system to get or create geometry.
  43583. */
  43584. update: function (previousData) {
  43585. var data = this.data;
  43586. var el = this.el;
  43587. var mesh;
  43588. var system = this.system;
  43589. // Dispose old geometry if we created one.
  43590. if (this.geometry) {
  43591. system.unuseGeometry(previousData);
  43592. this.geometry = null;
  43593. }
  43594. // Create new geometry.
  43595. this.geometry = system.getOrCreateGeometry(data);
  43596. // Set on mesh. If mesh does not exist, create it.
  43597. mesh = el.getObject3D('mesh');
  43598. if (mesh) {
  43599. mesh.geometry = this.geometry;
  43600. } else {
  43601. mesh = new THREE.Mesh();
  43602. mesh.geometry = this.geometry;
  43603. el.setObject3D('mesh', mesh);
  43604. }
  43605. },
  43606. /**
  43607. * Tell geometry system that entity is no longer using the geometry.
  43608. * Unset the geometry on the mesh
  43609. */
  43610. remove: function () {
  43611. this.system.unuseGeometry(this.data);
  43612. this.el.getObject3D('mesh').geometry = dummyGeometry;
  43613. this.geometry = null;
  43614. },
  43615. /**
  43616. * Update geometry component schema based on geometry type.
  43617. *
  43618. * @param {object} data - New data passed by Component.
  43619. */
  43620. updateSchema: function (data) {
  43621. var newGeometryType = data.primitive;
  43622. var currentGeometryType = this.data && this.data.primitive;
  43623. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  43624. // Geometry has no schema.
  43625. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  43626. // Nothing has changed.
  43627. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  43628. this.extendSchema(schema);
  43629. }
  43630. });
  43631. },{"../core/component":126,"../core/geometry":127,"../lib/three":174}],83:[function(_dereq_,module,exports){
  43632. var registerComponent = _dereq_('../core/component').registerComponent;
  43633. var THREE = _dereq_('../lib/three');
  43634. var utils = _dereq_('../utils/');
  43635. var warn = utils.debug('components:gltf-model:warn');
  43636. /**
  43637. * glTF model loader.
  43638. */
  43639. module.exports.Component = registerComponent('gltf-model', {
  43640. schema: {type: 'model'},
  43641. init: function () {
  43642. this.model = null;
  43643. this.loader = new THREE.GLTFLoader();
  43644. },
  43645. update: function () {
  43646. var self = this;
  43647. var el = this.el;
  43648. var src = this.data;
  43649. if (!src) { return; }
  43650. this.remove();
  43651. this.loader.load(src, function gltfLoaded (gltfModel) {
  43652. self.model = gltfModel.scene || gltfModel.scenes[0];
  43653. self.model.animations = gltfModel.animations;
  43654. el.setObject3D('mesh', self.model);
  43655. el.emit('model-loaded', {format: 'gltf', model: self.model});
  43656. }, undefined /* onProgress */, function gltfFailed (error) {
  43657. var message = (error && error.message) ? error.message : 'Failed to load glTF model';
  43658. warn(message);
  43659. el.emit('model-error', {format: 'gltf', src: src});
  43660. });
  43661. },
  43662. remove: function () {
  43663. if (!this.model) { return; }
  43664. this.el.removeObject3D('mesh');
  43665. }
  43666. });
  43667. },{"../core/component":126,"../lib/three":174,"../utils/":196}],84:[function(_dereq_,module,exports){
  43668. /* global THREE */
  43669. var registerComponent = _dereq_('../core/component').registerComponent;
  43670. // Found at https://github.com/aframevr/assets.
  43671. var MODEL_URLS = {
  43672. left: 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json',
  43673. right: 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json'
  43674. };
  43675. // Poses.
  43676. var ANIMATIONS = {
  43677. open: 'Open',
  43678. // point: grip active, trackpad surface active, trigger inactive.
  43679. point: 'Point',
  43680. // pointThumb: grip active, trigger inactive, trackpad surface inactive.
  43681. pointThumb: 'Point + Thumb',
  43682. // fist: grip active, trigger active, trackpad surface active.
  43683. fist: 'Fist',
  43684. // hold: trigger active, grip inactive.
  43685. hold: 'Hold',
  43686. // thumbUp: grip active, trigger active, trackpad surface inactive.
  43687. thumbUp: 'Thumb Up'
  43688. };
  43689. // Map animation to public events for the API.
  43690. var EVENTS = {};
  43691. EVENTS[ANIMATIONS.fist] = 'grip';
  43692. EVENTS[ANIMATIONS.thumbUp] = 'pistol';
  43693. EVENTS[ANIMATIONS.point] = 'pointing';
  43694. EVENTS[ANIMATIONS.thumb] = 'thumb';
  43695. /**
  43696. * Hand controls component that abstracts 6DoF controls:
  43697. * oculus-touch-controls, vive-controls, windows-motion-controls.
  43698. *
  43699. * Originally meant to be a sample implementation of applications-specific controls that
  43700. * abstracts multiple types of controllers.
  43701. *
  43702. * Auto-detect appropriate controller.
  43703. * Handle common events coming from the detected vendor-specific controls.
  43704. * Translate button events to semantic hand-related event names:
  43705. * (gripclose, gripopen, thumbup, thumbdown, pointup, pointdown)
  43706. * Load hand model with gestures that are applied based on the button pressed.
  43707. *
  43708. * @property {string} Hand mapping (`left`, `right`).
  43709. */
  43710. module.exports.Component = registerComponent('hand-controls', {
  43711. schema: {default: 'left'},
  43712. init: function () {
  43713. var self = this;
  43714. var el = this.el;
  43715. // Current pose.
  43716. this.gesture = ANIMATIONS.open;
  43717. // Active buttons populated by events provided by the attached controls.
  43718. this.pressedButtons = {};
  43719. this.touchedButtons = {};
  43720. this.loader = new THREE.ObjectLoader();
  43721. this.loader.setCrossOrigin('anonymous');
  43722. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  43723. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  43724. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  43725. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  43726. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  43727. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  43728. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  43729. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  43730. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  43731. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  43732. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  43733. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  43734. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  43735. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  43736. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  43737. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  43738. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  43739. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  43740. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  43741. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  43742. this.onControllerConnected = function () { self.setModelVisibility(true); };
  43743. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  43744. el.addEventListener('controllerconnected', this.onControllerConnected);
  43745. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  43746. },
  43747. play: function () {
  43748. this.addEventListeners();
  43749. },
  43750. pause: function () {
  43751. this.removeEventListeners();
  43752. },
  43753. tick: function (time, delta) {
  43754. var mesh = this.el.getObject3D('mesh');
  43755. if (!mesh || !mesh.mixer) { return; }
  43756. mesh.mixer.update(delta / 1000);
  43757. },
  43758. addEventListeners: function () {
  43759. var el = this.el;
  43760. el.addEventListener('gripdown', this.onGripDown);
  43761. el.addEventListener('gripup', this.onGripUp);
  43762. el.addEventListener('trackpaddown', this.onTrackpadDown);
  43763. el.addEventListener('trackpadup', this.onTrackpadUp);
  43764. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  43765. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  43766. el.addEventListener('triggerdown', this.onTriggerDown);
  43767. el.addEventListener('triggerup', this.onTriggerUp);
  43768. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  43769. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  43770. el.addEventListener('griptouchstart', this.onGripTouchStart);
  43771. el.addEventListener('griptouchend', this.onGripTouchEnd);
  43772. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  43773. el.addEventListener('thumbstickup', this.onThumbstickUp);
  43774. el.addEventListener('abuttontouchstart', this.onAorXTouchStart);
  43775. el.addEventListener('abuttontouchend', this.onAorXTouchEnd);
  43776. el.addEventListener('bbuttontouchstart', this.onBorYTouchStart);
  43777. el.addEventListener('bbuttontouchend', this.onBorYTouchEnd);
  43778. el.addEventListener('xbuttontouchstart', this.onAorXTouchStart);
  43779. el.addEventListener('xbuttontouchend', this.onAorXTouchEnd);
  43780. el.addEventListener('ybuttontouchstart', this.onBorYTouchStart);
  43781. el.addEventListener('ybuttontouchend', this.onBorYTouchEnd);
  43782. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  43783. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  43784. },
  43785. removeEventListeners: function () {
  43786. var el = this.el;
  43787. el.removeEventListener('gripdown', this.onGripDown);
  43788. el.removeEventListener('gripup', this.onGripUp);
  43789. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  43790. el.removeEventListener('trackpadup', this.onTrackpadUp);
  43791. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  43792. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  43793. el.removeEventListener('triggerdown', this.onTriggerDown);
  43794. el.removeEventListener('triggerup', this.onTriggerUp);
  43795. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  43796. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  43797. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  43798. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  43799. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  43800. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  43801. el.removeEventListener('abuttontouchstart', this.onAorXTouchStart);
  43802. el.removeEventListener('abuttontouchend', this.onAorXTouchEnd);
  43803. el.removeEventListener('bbuttontouchstart', this.onBorYTouchStart);
  43804. el.removeEventListener('bbuttontouchend', this.onBorYTouchEnd);
  43805. el.removeEventListener('xbuttontouchstart', this.onAorXTouchStart);
  43806. el.removeEventListener('xbuttontouchend', this.onAorXTouchEnd);
  43807. el.removeEventListener('ybuttontouchstart', this.onBorYTouchStart);
  43808. el.removeEventListener('ybuttontouchend', this.onBorYTouchEnd);
  43809. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  43810. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  43811. },
  43812. /**
  43813. * Update handler. More like the `init` handler since the only property is the hand, and
  43814. * that won't be changing much.
  43815. */
  43816. update: function (previousHand) {
  43817. var controlConfiguration;
  43818. var el = this.el;
  43819. var hand = this.data;
  43820. // Get common configuration to abstract different vendor controls.
  43821. controlConfiguration = {
  43822. hand: hand,
  43823. model: false,
  43824. rotationOffset: hand === 'left' ? 90 : -90
  43825. };
  43826. // Set model.
  43827. if (hand !== previousHand) {
  43828. this.loader.load(MODEL_URLS[hand], function (scene) {
  43829. var mesh = scene.getObjectByName('Hand');
  43830. mesh.material.skinning = true;
  43831. mesh.mixer = new THREE.AnimationMixer(mesh);
  43832. el.setObject3D('mesh', mesh);
  43833. mesh.position.set(0, 0, 0);
  43834. mesh.rotation.set(0, 0, 0);
  43835. // hidden by default
  43836. mesh.visible = false;
  43837. el.setAttribute('vive-controls', controlConfiguration);
  43838. el.setAttribute('oculus-touch-controls', controlConfiguration);
  43839. el.setAttribute('windows-motion-controls', controlConfiguration);
  43840. });
  43841. }
  43842. },
  43843. remove: function () {
  43844. this.el.removeObject3D('mesh');
  43845. },
  43846. /**
  43847. * Play model animation, based on which button was pressed and which kind of event.
  43848. *
  43849. * 1. Process buttons.
  43850. * 2. Determine gesture (this.determineGesture()).
  43851. * 3. Animation gesture (this.animationGesture()).
  43852. * 4. Emit gesture events (this.emitGestureEvents()).
  43853. *
  43854. * @param {string} button - Name of the button.
  43855. * @param {string} evt - Type of event for the button (i.e., down/up/touchstart/touchend).
  43856. */
  43857. handleButton: function (button, evt) {
  43858. var lastGesture;
  43859. var isPressed = evt === 'down';
  43860. var isTouched = evt === 'touchstart';
  43861. // Update objects.
  43862. if (evt.indexOf('touch') === 0) {
  43863. // Update touch object.
  43864. if (isTouched === this.touchedButtons[button]) { return; }
  43865. this.touchedButtons[button] = isTouched;
  43866. } else {
  43867. // Update button object.
  43868. if (isPressed === this.pressedButtons[button]) { return; }
  43869. this.pressedButtons[button] = isPressed;
  43870. }
  43871. // Determine the gesture.
  43872. lastGesture = this.gesture;
  43873. this.gesture = this.determineGesture();
  43874. // Same gesture.
  43875. if (this.gesture === lastGesture) { return; }
  43876. // Animate gesture.
  43877. this.animateGesture(this.gesture, lastGesture);
  43878. // Emit events.
  43879. this.emitGestureEvents(this.gesture, lastGesture);
  43880. },
  43881. /**
  43882. * Determine which pose hand should be in considering active and touched buttons.
  43883. */
  43884. determineGesture: function () {
  43885. var gesture;
  43886. var isGripActive = this.pressedButtons['grip'];
  43887. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  43888. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  43889. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  43890. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  43891. var isVive = isViveController(this.el.components['tracked-controls']);
  43892. // Works well with Oculus Touch and Windows Motion Controls, but Vive needs tweaks.
  43893. if (isGripActive) {
  43894. if (isVive) {
  43895. gesture = ANIMATIONS.fist;
  43896. } else
  43897. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  43898. gesture = isTriggerActive ? ANIMATIONS.fist : ANIMATIONS.point;
  43899. } else {
  43900. gesture = isTriggerActive ? ANIMATIONS.thumbUp : ANIMATIONS.pointThumb;
  43901. }
  43902. } else {
  43903. if (isTriggerActive) {
  43904. gesture = !isVive ? ANIMATIONS.hold : ANIMATIONS.fist;
  43905. } else if (isVive && isTrackpadActive) {
  43906. gesture = ANIMATIONS.point;
  43907. }
  43908. }
  43909. return gesture;
  43910. },
  43911. /**
  43912. * Play gesture animation.
  43913. *
  43914. * @param {string} gesture - Which pose to animate to. If absent, then animate to open.
  43915. * @param {string} lastGesture - Previous gesture, to reverse back to open if needed.
  43916. */
  43917. animateGesture: function (gesture, lastGesture) {
  43918. if (gesture) {
  43919. this.playAnimation(gesture || ANIMATIONS.open, lastGesture, false);
  43920. return;
  43921. }
  43922. // If no gesture, then reverse the current gesture back to open pose.
  43923. this.playAnimation(lastGesture, lastGesture, true);
  43924. },
  43925. /**
  43926. * Emit `hand-controls`-specific events.
  43927. */
  43928. emitGestureEvents: function (gesture, lastGesture) {
  43929. var el = this.el;
  43930. var eventName;
  43931. if (lastGesture === gesture) { return; }
  43932. // Emit event for lastGesture not inactive.
  43933. eventName = getGestureEventName(lastGesture, false);
  43934. if (eventName) { el.emit(eventName); }
  43935. // Emit event for current gesture now active.
  43936. eventName = getGestureEventName(gesture, true);
  43937. if (eventName) { el.emit(eventName); }
  43938. },
  43939. /**
  43940. * Play hand animation based on button state.
  43941. *
  43942. * @param {string} gesture - Name of the animation as specified by the model.
  43943. * @param {string} lastGesture - Previous pose.
  43944. * @param {boolean} reverse - Whether animation should play in reverse.
  43945. */
  43946. playAnimation: function (gesture, lastGesture, reverse) {
  43947. var fromAction;
  43948. var mesh = this.el.getObject3D('mesh');
  43949. var toAction;
  43950. if (!mesh) { return; }
  43951. // Grab clip action.
  43952. toAction = mesh.mixer.clipAction(gesture);
  43953. toAction.clampWhenFinished = true;
  43954. toAction.loop = THREE.PingPong;
  43955. toAction.repetitions = 0;
  43956. toAction.timeScale = reverse ? -1 : 1;
  43957. toAction.weight = 1;
  43958. // No gesture to gesture or gesture to no gesture.
  43959. if (!lastGesture || gesture === lastGesture) {
  43960. // Stop all current animations.
  43961. mesh.mixer.stopAllAction();
  43962. // Play animation.
  43963. toAction.play();
  43964. return;
  43965. }
  43966. // Animate or crossfade from gesture to gesture.
  43967. fromAction = mesh.mixer.clipAction(lastGesture);
  43968. mesh.mixer.stopAllAction();
  43969. fromAction.weight = 0.15;
  43970. fromAction.play();
  43971. toAction.play();
  43972. fromAction.crossFadeTo(toAction, 0.15, true);
  43973. },
  43974. setModelVisibility: function (visible) {
  43975. var model = this.el.getObject3D('mesh');
  43976. if (!model) { return; }
  43977. model.visible = visible;
  43978. }
  43979. });
  43980. /**
  43981. * Suffix gestures based on toggle state (e.g., open/close, up/down, start/end).
  43982. *
  43983. * @param {string} gesture
  43984. * @param {boolean} active
  43985. */
  43986. function getGestureEventName (gesture, active) {
  43987. var eventName;
  43988. if (!gesture) { return; }
  43989. eventName = EVENTS[gesture];
  43990. if (eventName === 'grip') {
  43991. return eventName + (active ? 'close' : 'open');
  43992. }
  43993. if (eventName === 'point' || eventName === 'thumb') {
  43994. return eventName + (active ? 'up' : 'down');
  43995. }
  43996. if (eventName === 'pointing' || eventName === 'pistol') {
  43997. return eventName + (active ? 'start' : 'end');
  43998. }
  43999. return;
  44000. }
  44001. function isViveController (trackedControls) {
  44002. var controllerId = trackedControls && trackedControls.controller &&
  44003. trackedControls.controller.id;
  44004. return controllerId && controllerId.indexOf('OpenVR ') === 0;
  44005. }
  44006. },{"../core/component":126}],85:[function(_dereq_,module,exports){
  44007. _dereq_('./camera');
  44008. _dereq_('./collada-model');
  44009. _dereq_('./cursor');
  44010. _dereq_('./daydream-controls');
  44011. _dereq_('./gearvr-controls');
  44012. _dereq_('./geometry');
  44013. _dereq_('./gltf-model');
  44014. _dereq_('./hand-controls');
  44015. _dereq_('./laser-controls');
  44016. _dereq_('./light');
  44017. _dereq_('./line');
  44018. _dereq_('./link');
  44019. _dereq_('./look-controls');
  44020. _dereq_('./material');
  44021. _dereq_('./obj-model');
  44022. _dereq_('./oculus-touch-controls');
  44023. _dereq_('./position');
  44024. _dereq_('./raycaster');
  44025. _dereq_('./rotation');
  44026. _dereq_('./scale');
  44027. _dereq_('./shadow');
  44028. _dereq_('./sound');
  44029. _dereq_('./text');
  44030. _dereq_('./tracked-controls');
  44031. _dereq_('./visible');
  44032. _dereq_('./vive-controls');
  44033. _dereq_('./wasd-controls');
  44034. _dereq_('./windows-motion-controls');
  44035. _dereq_('./scene/background');
  44036. _dereq_('./scene/debug');
  44037. _dereq_('./scene/embedded');
  44038. _dereq_('./scene/inspector');
  44039. _dereq_('./scene/fog');
  44040. _dereq_('./scene/keyboard-shortcuts');
  44041. _dereq_('./scene/pool');
  44042. _dereq_('./scene/screenshot');
  44043. _dereq_('./scene/stats');
  44044. _dereq_('./scene/vr-mode-ui');
  44045. },{"./camera":77,"./collada-model":78,"./cursor":79,"./daydream-controls":80,"./gearvr-controls":81,"./geometry":82,"./gltf-model":83,"./hand-controls":84,"./laser-controls":86,"./light":87,"./line":88,"./link":89,"./look-controls":90,"./material":91,"./obj-model":92,"./oculus-touch-controls":93,"./position":94,"./raycaster":95,"./rotation":96,"./scale":97,"./scene/background":98,"./scene/debug":99,"./scene/embedded":100,"./scene/fog":101,"./scene/inspector":102,"./scene/keyboard-shortcuts":103,"./scene/pool":104,"./scene/screenshot":105,"./scene/stats":106,"./scene/vr-mode-ui":107,"./shadow":108,"./sound":109,"./text":110,"./tracked-controls":111,"./visible":112,"./vive-controls":113,"./wasd-controls":114,"./windows-motion-controls":115}],86:[function(_dereq_,module,exports){
  44046. var registerComponent = _dereq_('../core/component').registerComponent;
  44047. var utils = _dereq_('../utils/');
  44048. registerComponent('laser-controls', {
  44049. schema: {
  44050. hand: {default: 'right'}
  44051. },
  44052. init: function () {
  44053. var config = this.config;
  44054. var data = this.data;
  44055. var el = this.el;
  44056. var self = this;
  44057. // Set all controller models.
  44058. el.setAttribute('daydream-controls', {hand: data.hand});
  44059. el.setAttribute('gearvr-controls', {hand: data.hand});
  44060. el.setAttribute('oculus-touch-controls', {hand: data.hand});
  44061. el.setAttribute('vive-controls', {hand: data.hand});
  44062. el.setAttribute('windows-motion-controls', {hand: data.hand});
  44063. // Wait for controller to connect, or have a valid pointing pose, before creating ray
  44064. el.addEventListener('controllerconnected', createRay);
  44065. el.addEventListener('controllerdisconnected', hideRay);
  44066. el.addEventListener('controllermodelready', function (evt) {
  44067. createRay(evt);
  44068. self.modelReady = true;
  44069. });
  44070. function createRay (evt) {
  44071. var controllerConfig = config[evt.detail.name];
  44072. if (!controllerConfig) { return; }
  44073. // Show the line unless a particular config opts to hide it, until a controllermodelready
  44074. // event comes through.
  44075. var raycasterConfig = utils.extend({
  44076. showLine: true
  44077. }, controllerConfig.raycaster || {});
  44078. // The controllermodelready event contains a rayOrigin that takes into account
  44079. // offsets specific to the loaded model.
  44080. if (evt.detail.rayOrigin) {
  44081. raycasterConfig.origin = evt.detail.rayOrigin.origin;
  44082. raycasterConfig.direction = evt.detail.rayOrigin.direction;
  44083. raycasterConfig.showLine = true;
  44084. }
  44085. // Only apply a default raycaster if it does not yet exist. This prevents it overwriting
  44086. // config applied from a controllermodelready event.
  44087. if (evt.detail.rayOrigin || !self.modelReady) {
  44088. el.setAttribute('raycaster', raycasterConfig);
  44089. } else {
  44090. el.setAttribute('raycaster', 'showLine', true);
  44091. }
  44092. el.setAttribute('cursor', utils.extend({
  44093. fuse: false
  44094. }, controllerConfig.cursor));
  44095. }
  44096. function hideRay () {
  44097. el.setAttribute('raycaster', 'showLine', false);
  44098. }
  44099. },
  44100. config: {
  44101. 'daydream-controls': {
  44102. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']}
  44103. },
  44104. 'gearvr-controls': {
  44105. cursor: {downEvents: ['trackpaddown'], upEvents: ['trackpadup']},
  44106. raycaster: {origin: {x: 0, y: 0.0005, z: 0}}
  44107. },
  44108. 'oculus-touch-controls': {
  44109. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44110. raycaster: {origin: {x: 0.001, y: 0, z: 0.065}, direction: {x: 0, y: -0.8, z: -1}}
  44111. },
  44112. 'vive-controls': {
  44113. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']}
  44114. },
  44115. 'windows-motion-controls': {
  44116. cursor: {downEvents: ['triggerdown'], upEvents: ['triggerup']},
  44117. raycaster: {showLine: false}
  44118. }
  44119. }
  44120. });
  44121. },{"../core/component":126,"../utils/":196}],87:[function(_dereq_,module,exports){
  44122. var bind = _dereq_('../utils/bind');
  44123. var diff = _dereq_('../utils').diff;
  44124. var debug = _dereq_('../utils/debug');
  44125. var registerComponent = _dereq_('../core/component').registerComponent;
  44126. var THREE = _dereq_('../lib/three');
  44127. var degToRad = THREE.Math.degToRad;
  44128. var warn = debug('components:light:warn');
  44129. /**
  44130. * Light component.
  44131. */
  44132. module.exports.Component = registerComponent('light', {
  44133. schema: {
  44134. angle: {default: 60, if: {type: ['spot']}},
  44135. color: {type: 'color'},
  44136. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44137. decay: {default: 1, if: {type: ['point', 'spot']}},
  44138. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44139. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44140. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44141. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  44142. target: {type: 'selector', if: {type: ['spot', 'directional']}},
  44143. // Shadows.
  44144. castShadow: {default: false, if: {type: ['point', 'spot', 'directional']}},
  44145. shadowBias: {default: 0, if: {castShadow: true}},
  44146. shadowCameraFar: {default: 500, if: {castShadow: true}},
  44147. shadowCameraFov: {default: 90, if: {castShadow: true}},
  44148. shadowCameraNear: {default: 0.5, if: {castShadow: true}},
  44149. shadowCameraTop: {default: 5, if: {castShadow: true}},
  44150. shadowCameraRight: {default: 5, if: {castShadow: true}},
  44151. shadowCameraBottom: {default: -5, if: {castShadow: true}},
  44152. shadowCameraLeft: {default: -5, if: {castShadow: true}},
  44153. shadowCameraVisible: {default: false, if: {castShadow: true}},
  44154. shadowMapHeight: {default: 512, if: {castShadow: true}},
  44155. shadowMapWidth: {default: 512, if: {castShadow: true}}
  44156. },
  44157. /**
  44158. * Notifies scene a light has been added to remove default lighting.
  44159. */
  44160. init: function () {
  44161. var el = this.el;
  44162. this.light = null;
  44163. this.defaultTarget = null;
  44164. this.system.registerLight(el);
  44165. },
  44166. /**
  44167. * (Re)create or update light.
  44168. */
  44169. update: function (oldData) {
  44170. var data = this.data;
  44171. var diffData = diff(data, oldData);
  44172. var light = this.light;
  44173. var self = this;
  44174. // Existing light.
  44175. if (light && !('type' in diffData)) {
  44176. var shadowsLoaded = false;
  44177. // Light type has not changed. Update light.
  44178. Object.keys(diffData).forEach(function (key) {
  44179. var value = data[key];
  44180. switch (key) {
  44181. case 'color': {
  44182. light.color.set(value);
  44183. break;
  44184. }
  44185. case 'groundColor': {
  44186. light.groundColor.set(value);
  44187. break;
  44188. }
  44189. case 'angle': {
  44190. light.angle = degToRad(value);
  44191. break;
  44192. }
  44193. case 'target': {
  44194. // Reset target if selector is null.
  44195. if (value === null) {
  44196. if (data.type === 'spot' || data.type === 'directional') {
  44197. light.target = self.defaultTarget;
  44198. }
  44199. } else {
  44200. // Target specified, set target to entity's `object3D` when it is loaded.
  44201. if (value.hasLoaded) {
  44202. self.onSetTarget(value, light);
  44203. } else {
  44204. value.addEventListener('loaded', bind(self.onSetTarget, self, value, light));
  44205. }
  44206. }
  44207. break;
  44208. }
  44209. case 'castShadow':
  44210. case 'shadowBias':
  44211. case 'shadowCameraFar':
  44212. case 'shadowCameraFov':
  44213. case 'shadowCameraNear':
  44214. case 'shadowCameraTop':
  44215. case 'shadowCameraRight':
  44216. case 'shadowCameraBottom':
  44217. case 'shadowCameraLeft':
  44218. case 'shadowCameraVisible':
  44219. case 'shadowMapHeight':
  44220. case 'shadowMapWidth':
  44221. if (!shadowsLoaded) {
  44222. self.updateShadow();
  44223. shadowsLoaded = true;
  44224. }
  44225. break;
  44226. default: {
  44227. light[key] = value;
  44228. }
  44229. }
  44230. });
  44231. return;
  44232. }
  44233. // No light yet or light type has changed. Create and add light.
  44234. this.setLight(this.data);
  44235. this.updateShadow();
  44236. },
  44237. setLight: function (data) {
  44238. var el = this.el;
  44239. var newLight = this.getLight(data);
  44240. if (newLight) {
  44241. if (this.light) {
  44242. el.removeObject3D('light');
  44243. }
  44244. this.light = newLight;
  44245. this.light.el = el;
  44246. el.setObject3D('light', this.light);
  44247. // HACK solution for issue #1624
  44248. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44249. el.getObject3D('light').translateY(-1);
  44250. }
  44251. // set and position default lighttarget as a child to enable spotlight orientation
  44252. if (data.type === 'spot') {
  44253. el.setObject3D('light-target', this.defaultTarget);
  44254. el.getObject3D('light-target').position.set(0, 0, -1);
  44255. }
  44256. }
  44257. },
  44258. /**
  44259. * Updates shadow-related properties on the current light.
  44260. */
  44261. updateShadow: function () {
  44262. var el = this.el;
  44263. var data = this.data;
  44264. var light = this.light;
  44265. light.castShadow = data.castShadow;
  44266. // Shadow camera helper.
  44267. var cameraHelper = el.getObject3D('cameraHelper');
  44268. if (data.shadowCameraVisible && !cameraHelper) {
  44269. el.setObject3D('cameraHelper', new THREE.CameraHelper(light.shadow.camera));
  44270. } else if (!data.shadowCameraVisible && cameraHelper) {
  44271. el.removeObject3D('cameraHelper');
  44272. }
  44273. if (!data.castShadow) { return light; }
  44274. // Shadow appearance.
  44275. light.shadow.bias = data.shadowBias;
  44276. light.shadow.mapSize.height = data.shadowMapHeight;
  44277. light.shadow.mapSize.width = data.shadowMapWidth;
  44278. // Shadow camera.
  44279. light.shadow.camera.near = data.shadowCameraNear;
  44280. light.shadow.camera.far = data.shadowCameraFar;
  44281. if (light.shadow.camera instanceof THREE.OrthographicCamera) {
  44282. light.shadow.camera.top = data.shadowCameraTop;
  44283. light.shadow.camera.right = data.shadowCameraRight;
  44284. light.shadow.camera.bottom = data.shadowCameraBottom;
  44285. light.shadow.camera.left = data.shadowCameraLeft;
  44286. } else {
  44287. light.shadow.camera.fov = data.shadowCameraFov;
  44288. }
  44289. light.shadow.camera.updateProjectionMatrix();
  44290. if (cameraHelper) { cameraHelper.update(); }
  44291. },
  44292. /**
  44293. * Creates a new three.js light object given data object defining the light.
  44294. *
  44295. * @param {object} data
  44296. */
  44297. getLight: function (data) {
  44298. var angle = data.angle;
  44299. var color = new THREE.Color(data.color).getHex();
  44300. var decay = data.decay;
  44301. var distance = data.distance;
  44302. var groundColor = new THREE.Color(data.groundColor).getHex();
  44303. var intensity = data.intensity;
  44304. var type = data.type;
  44305. var target = data.target;
  44306. var light = null;
  44307. switch (type.toLowerCase()) {
  44308. case 'ambient': {
  44309. return new THREE.AmbientLight(color, intensity);
  44310. }
  44311. case 'directional': {
  44312. light = new THREE.DirectionalLight(color, intensity);
  44313. this.defaultTarget = light.target;
  44314. if (target) {
  44315. if (target.hasLoaded) {
  44316. this.onSetTarget(target, light);
  44317. } else {
  44318. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44319. }
  44320. }
  44321. return light;
  44322. }
  44323. case 'hemisphere': {
  44324. return new THREE.HemisphereLight(color, groundColor, intensity);
  44325. }
  44326. case 'point': {
  44327. return new THREE.PointLight(color, intensity, distance, decay);
  44328. }
  44329. case 'spot': {
  44330. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44331. this.defaultTarget = light.target;
  44332. if (target) {
  44333. if (target.hasLoaded) {
  44334. this.onSetTarget(target, light);
  44335. } else {
  44336. target.addEventListener('loaded', bind(this.onSetTarget, this, target, light));
  44337. }
  44338. }
  44339. return light;
  44340. }
  44341. default: {
  44342. warn('%s is not a valid light type. ' +
  44343. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44344. }
  44345. }
  44346. },
  44347. onSetTarget: function (targetEl, light) {
  44348. light.target = targetEl.object3D;
  44349. },
  44350. /**
  44351. * Remove light on remove (callback).
  44352. */
  44353. remove: function () {
  44354. var el = this.el;
  44355. el.removeObject3D('light');
  44356. if (el.getObject3D('cameraHelper')) {
  44357. el.removeObject3D('cameraHelper');
  44358. }
  44359. }
  44360. });
  44361. },{"../core/component":126,"../lib/three":174,"../utils":196,"../utils/bind":190,"../utils/debug":192}],88:[function(_dereq_,module,exports){
  44362. /* global THREE */
  44363. var registerComponent = _dereq_('../core/component').registerComponent;
  44364. module.exports.Component = registerComponent('line', {
  44365. schema: {
  44366. start: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44367. end: {type: 'vec3', default: {x: 0, y: 0, z: 0}},
  44368. color: {type: 'color', default: '#74BEC1'},
  44369. opacity: {type: 'number', default: 1},
  44370. visible: {default: true}
  44371. },
  44372. multiple: true,
  44373. init: function () {
  44374. var data = this.data;
  44375. var geometry;
  44376. var material;
  44377. material = this.material = new THREE.LineBasicMaterial({
  44378. color: data.color,
  44379. opacity: data.opacity,
  44380. transparent: data.opacity < 1,
  44381. visible: data.visible
  44382. });
  44383. geometry = this.geometry = new THREE.BufferGeometry();
  44384. geometry.addAttribute('position', new THREE.BufferAttribute(new Float32Array(2 * 3), 3));
  44385. this.line = new THREE.Line(geometry, material);
  44386. this.el.setObject3D(this.attrName, this.line);
  44387. },
  44388. update: function (oldData) {
  44389. var data = this.data;
  44390. var geometry = this.geometry;
  44391. var geoNeedsUpdate = false;
  44392. var material = this.material;
  44393. var positionArray = geometry.attributes.position.array;
  44394. // Update geometry.
  44395. if (!isEqualVec3(data.start, oldData.start)) {
  44396. positionArray[0] = data.start.x;
  44397. positionArray[1] = data.start.y;
  44398. positionArray[2] = data.start.z;
  44399. geoNeedsUpdate = true;
  44400. }
  44401. if (!isEqualVec3(data.end, oldData.end)) {
  44402. positionArray[3] = data.end.x;
  44403. positionArray[4] = data.end.y;
  44404. positionArray[5] = data.end.z;
  44405. geoNeedsUpdate = true;
  44406. }
  44407. if (geoNeedsUpdate) {
  44408. geometry.attributes.position.needsUpdate = true;
  44409. geometry.computeBoundingSphere();
  44410. }
  44411. material.color.setStyle(data.color);
  44412. material.opacity = data.opacity;
  44413. material.transparent = data.opacity < 1;
  44414. material.visible = data.visible;
  44415. },
  44416. remove: function () {
  44417. this.el.removeObject3D('line', this.line);
  44418. }
  44419. });
  44420. function isEqualVec3 (a, b) {
  44421. if (!a || !b) { return false; }
  44422. return (a.x === b.x && a.y === b.y && a.z === b.z);
  44423. }
  44424. },{"../core/component":126}],89:[function(_dereq_,module,exports){
  44425. var registerComponent = _dereq_('../core/component').registerComponent;
  44426. var registerShader = _dereq_('../core/shader').registerShader;
  44427. var THREE = _dereq_('../lib/three');
  44428. /**
  44429. * Link component. Connect experiences and traverse between them in VR
  44430. *
  44431. * @member {object} hiddenEls - Store the hidden elements during peek mode.
  44432. */
  44433. module.exports.Component = registerComponent('link', {
  44434. schema: {
  44435. backgroundColor: {default: 'red', type: 'color'},
  44436. borderColor: {default: 'white', type: 'color'},
  44437. highlighted: {default: false},
  44438. highlightedColor: {default: '#24CAFF', type: 'color'},
  44439. href: {default: ''},
  44440. image: {type: 'asset'},
  44441. on: {default: 'click'},
  44442. peekMode: {default: false},
  44443. title: {default: ''},
  44444. titleColor: {default: 'white', type: 'color'},
  44445. visualAspectEnabled: {default: true}
  44446. },
  44447. init: function () {
  44448. this.navigate = this.navigate.bind(this);
  44449. this.previousQuaternion = undefined;
  44450. this.quaternionClone = new THREE.Quaternion();
  44451. // Store hidden elements during peek mode so we can show them again later.
  44452. this.hiddenEls = [];
  44453. this.initVisualAspect();
  44454. },
  44455. update: function (oldData) {
  44456. var data = this.data;
  44457. var el = this.el;
  44458. var backgroundColor;
  44459. var strokeColor;
  44460. backgroundColor = data.highlighted ? data.highlightedColor : data.backgroundColor;
  44461. strokeColor = data.highlighted ? data.highlightedColor : data.borderColor;
  44462. el.setAttribute('material', 'backgroundColor', backgroundColor);
  44463. el.setAttribute('material', 'strokeColor', strokeColor);
  44464. if (data.on !== oldData.on) { this.updateEventListener(); }
  44465. if (data.visualAspectEnabled && oldData.peekMode !== undefined &&
  44466. data.peekMode !== oldData.peekMode) { this.updatePeekMode(); }
  44467. if (!data.image || oldData.image === data.image) { return; }
  44468. el.setAttribute('material', 'pano',
  44469. typeof data.image === 'string' ? data.image : data.image.src);
  44470. },
  44471. /*
  44472. * Toggle all elements and full 360 preview of the linked page.
  44473. */
  44474. updatePeekMode: function () {
  44475. var el = this.el;
  44476. var sphereEl = this.sphereEl;
  44477. if (this.data.peekMode) {
  44478. this.hideAll();
  44479. el.getObject3D('mesh').visible = false;
  44480. sphereEl.setAttribute('visible', true);
  44481. } else {
  44482. this.showAll();
  44483. el.getObject3D('mesh').visible = true;
  44484. sphereEl.setAttribute('visible', false);
  44485. }
  44486. },
  44487. play: function () {
  44488. this.updateEventListener();
  44489. },
  44490. pause: function () {
  44491. this.removeEventListener();
  44492. },
  44493. updateEventListener: function () {
  44494. var el = this.el;
  44495. if (!el.isPlaying) { return; }
  44496. this.removeEventListener();
  44497. el.addEventListener(this.data.on, this.navigate);
  44498. },
  44499. removeEventListener: function () {
  44500. var on = this.data.on;
  44501. if (!on) { return; }
  44502. this.el.removeEventListener(on, this.navigate);
  44503. },
  44504. initVisualAspect: function () {
  44505. var el = this.el;
  44506. var semiSphereEl;
  44507. var sphereEl;
  44508. var textEl;
  44509. if (!this.data.visualAspectEnabled) { return; }
  44510. textEl = this.textEl = this.textEl || document.createElement('a-entity');
  44511. sphereEl = this.sphereEl = this.sphereEl || document.createElement('a-entity');
  44512. semiSphereEl = this.semiSphereEl = this.semiSphereEl || document.createElement('a-entity');
  44513. // Set portal.
  44514. el.setAttribute('geometry', {primitive: 'circle', radius: 1.0, segments: 64});
  44515. el.setAttribute('material', {shader: 'portal', pano: this.data.image, side: 'double'});
  44516. // Set text that displays the link title and URL.
  44517. textEl.setAttribute('text', {
  44518. color: this.data.titleColor,
  44519. align: 'center',
  44520. font: 'kelsonsans',
  44521. value: this.data.title || this.data.href,
  44522. width: 4
  44523. });
  44524. textEl.setAttribute('position', '0 1.5 0');
  44525. el.appendChild(textEl);
  44526. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44527. semiSphereEl.setAttribute('geometry', {
  44528. primitive: 'sphere',
  44529. radius: 1.0,
  44530. phiStart: 0,
  44531. segmentsWidth: 64,
  44532. segmentsHeight: 64,
  44533. phiLength: 180,
  44534. thetaStart: 0,
  44535. thetaLength: 360
  44536. });
  44537. semiSphereEl.setAttribute('material', {
  44538. shader: 'portal',
  44539. borderEnabled: 0.0,
  44540. pano: this.data.image,
  44541. side: 'back'
  44542. });
  44543. semiSphereEl.setAttribute('rotation', '0 180 0');
  44544. semiSphereEl.setAttribute('position', '0 0 0');
  44545. semiSphereEl.setAttribute('visible', false);
  44546. el.appendChild(semiSphereEl);
  44547. // Set sphere rendered when camera is close to portal to allow user to peek inside.
  44548. sphereEl.setAttribute('geometry', {
  44549. primitive: 'sphere',
  44550. radius: 10,
  44551. segmentsWidth: 64,
  44552. segmentsHeight: 64
  44553. });
  44554. sphereEl.setAttribute('material', {
  44555. shader: 'portal',
  44556. borderEnabled: 0.0,
  44557. pano: this.data.image,
  44558. side: 'back'
  44559. });
  44560. sphereEl.setAttribute('visible', false);
  44561. el.appendChild(sphereEl);
  44562. },
  44563. navigate: function () {
  44564. window.location = this.data.href;
  44565. },
  44566. /**
  44567. * 1. Swap plane that represents portal with sphere with a hole when the camera is close
  44568. * so user can peek inside portal. Sphere is rendered on oposite side of portal
  44569. * from where user enters.
  44570. * 2. Place the url/title above or inside portal depending on distance to camera.
  44571. * 3. Face portal to camera when far away from user.
  44572. */
  44573. tick: (function () {
  44574. var cameraWorldPosition = new THREE.Vector3();
  44575. var elWorldPosition = new THREE.Vector3();
  44576. var quaternion = new THREE.Quaternion();
  44577. var scale = new THREE.Vector3();
  44578. return function () {
  44579. var el = this.el;
  44580. var object3D = el.object3D;
  44581. var camera = el.sceneEl.camera;
  44582. var cameraPortalOrientation;
  44583. var distance;
  44584. var textEl = this.textEl;
  44585. if (!this.data.visualAspectEnabled) { return; }
  44586. // Update matrices
  44587. object3D.updateMatrixWorld();
  44588. camera.parent.updateMatrixWorld();
  44589. camera.updateMatrixWorld();
  44590. object3D.matrix.decompose(elWorldPosition, quaternion, scale);
  44591. elWorldPosition.setFromMatrixPosition(object3D.matrixWorld);
  44592. cameraWorldPosition.setFromMatrixPosition(camera.matrixWorld);
  44593. distance = elWorldPosition.distanceTo(cameraWorldPosition);
  44594. if (distance > 20) {
  44595. // Store original orientation to be restored when the portal stops facing the camera.
  44596. if (!this.previousQuaternion) {
  44597. this.quaternionClone.copy(quaternion);
  44598. this.previousQuaternion = this.quaternionClone;
  44599. }
  44600. // If the portal is far away from the user, face portal to camera.
  44601. object3D.lookAt(cameraWorldPosition);
  44602. } else {
  44603. // When portal is close to the user/camera.
  44604. cameraPortalOrientation = this.calculateCameraPortalOrientation();
  44605. // If user gets very close to portal, replace with holed sphere they can peek in.
  44606. if (distance < 0.5) {
  44607. // Configure text size and sphere orientation depending side user approaches portal.
  44608. if (this.semiSphereEl.getAttribute('visible') === true) { return; }
  44609. textEl.setAttribute('text', 'width', 1.5);
  44610. if (cameraPortalOrientation <= 0.0) {
  44611. textEl.setAttribute('position', '0 0 0.75');
  44612. textEl.setAttribute('rotation', '0 180 0');
  44613. this.semiSphereEl.setAttribute('rotation', '0 0 0');
  44614. } else {
  44615. textEl.setAttribute('position', '0 0 -0.75');
  44616. textEl.setAttribute('rotation', '0 0 0');
  44617. this.semiSphereEl.setAttribute('rotation', '0 180 0');
  44618. }
  44619. el.getObject3D('mesh').visible = false;
  44620. this.semiSphereEl.setAttribute('visible', true);
  44621. this.peekCameraPortalOrientation = cameraPortalOrientation;
  44622. } else {
  44623. // Calculate wich side the camera is approaching the camera (back / front).
  44624. // Adjust text orientation based on camera position.
  44625. if (cameraPortalOrientation <= 0.0) {
  44626. textEl.setAttribute('rotation', '0 180 0');
  44627. } else {
  44628. textEl.setAttribute('rotation', '0 0 0');
  44629. }
  44630. textEl.setAttribute('text', 'width', 5);
  44631. textEl.setAttribute('position', '0 1.5 0');
  44632. el.getObject3D('mesh').visible = true;
  44633. this.semiSphereEl.setAttribute('visible', false);
  44634. this.peekCameraPortalOrientation = undefined;
  44635. }
  44636. if (this.previousQuaternion) {
  44637. object3D.quaternion.copy(this.previousQuaternion);
  44638. this.previousQuaternion = undefined;
  44639. }
  44640. }
  44641. };
  44642. })(),
  44643. hideAll: function () {
  44644. var el = this.el;
  44645. var hiddenEls = this.hiddenEls;
  44646. var self = this;
  44647. if (hiddenEls.length > 0) { return; }
  44648. el.sceneEl.object3D.traverse(function (object) {
  44649. if (object && object.el && object.el.hasAttribute('link-controls')) { return; }
  44650. if (!object.el || object === el.sceneEl.object3D || object.el === el ||
  44651. object.el === self.sphereEl || object.el === el.sceneEl.cameraEl ||
  44652. object.el.getAttribute('visible') === false || object.el === self.textEl ||
  44653. object.el === self.semiSphereEl) {
  44654. return;
  44655. }
  44656. object.el.setAttribute('visible', false);
  44657. hiddenEls.push(object.el);
  44658. });
  44659. },
  44660. showAll: function () {
  44661. this.hiddenEls.forEach(function (el) { el.setAttribute('visible', true); });
  44662. this.hiddenEls = [];
  44663. },
  44664. /**
  44665. * Calculate whether the camera faces the front or back face of the portal.
  44666. * @returns {number} > 0 if camera faces front of portal, < 0 if it faces back of portal.
  44667. */
  44668. calculateCameraPortalOrientation: (function () {
  44669. var mat4 = new THREE.Matrix4();
  44670. var cameraPosition = new THREE.Vector3();
  44671. var portalNormal = new THREE.Vector3(0, 0, 1);
  44672. var portalPosition = new THREE.Vector3(0, 0, 0);
  44673. return function () {
  44674. var el = this.el;
  44675. var camera = el.sceneEl.camera;
  44676. // Reset tmp variables.
  44677. cameraPosition.set(0, 0, 0);
  44678. portalNormal.set(0, 0, 1);
  44679. portalPosition.set(0, 0, 0);
  44680. // Apply portal orientation to the normal.
  44681. el.object3D.matrixWorld.extractRotation(mat4);
  44682. portalNormal.applyMatrix4(mat4);
  44683. // Calculate portal world position.
  44684. el.object3D.updateMatrixWorld();
  44685. el.object3D.localToWorld(portalPosition);
  44686. // Calculate camera world position.
  44687. camera.parent.parent.updateMatrixWorld();
  44688. camera.parent.updateMatrixWorld();
  44689. camera.updateMatrixWorld();
  44690. camera.localToWorld(cameraPosition);
  44691. // Calculate vector from portal to camera.
  44692. // (portal) -------> (camera)
  44693. cameraPosition.sub(portalPosition).normalize();
  44694. portalNormal.normalize();
  44695. // Side where camera approaches portal is given by sign of dot product of portal normal
  44696. // and portal to camera vectors.
  44697. return Math.sign(portalNormal.dot(cameraPosition));
  44698. };
  44699. })(),
  44700. remove: function () {
  44701. this.removeEventListener();
  44702. }
  44703. });
  44704. /* eslint-disable */
  44705. registerShader('portal', {
  44706. schema: {
  44707. borderEnabled: {default: 1.0, type: 'int', is: 'uniform'},
  44708. backgroundColor: {default: 'red', type: 'color', is: 'uniform'},
  44709. pano: {type: 'map', is: 'uniform'},
  44710. strokeColor: {default: 'white', type: 'color', is: 'uniform'}
  44711. },
  44712. vertexShader: [
  44713. 'vec3 portalPosition;',
  44714. 'varying vec3 vWorldPosition;',
  44715. 'varying float vDistanceToCenter;',
  44716. 'varying float vDistance;',
  44717. 'void main() {',
  44718. 'vDistanceToCenter = clamp(length(position - vec3(0.0, 0.0, 0.0)), 0.0, 1.0);',
  44719. 'portalPosition = (modelMatrix * vec4(0.0, 0.0, 0.0, 1.0)).xyz;',
  44720. 'vDistance = length(portalPosition - cameraPosition);',
  44721. 'vWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;',
  44722. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  44723. '}'
  44724. ].join('\n'),
  44725. fragmentShader: [
  44726. '#define RECIPROCAL_PI2 0.15915494',
  44727. 'uniform sampler2D pano;',
  44728. 'uniform vec3 strokeColor;',
  44729. 'uniform vec3 backgroundColor;',
  44730. 'uniform float borderEnabled;',
  44731. 'varying float vDistanceToCenter;',
  44732. 'varying float vDistance;',
  44733. 'varying vec3 vWorldPosition;',
  44734. 'void main() {',
  44735. 'vec3 direction = normalize(vWorldPosition - cameraPosition);',
  44736. 'vec2 sampleUV;',
  44737. 'float borderThickness = clamp(exp(-vDistance / 50.0), 0.6, 0.95);',
  44738. 'sampleUV.y = saturate(direction.y * 0.5 + 0.5);',
  44739. 'sampleUV.x = atan(direction.z, -direction.x) * -RECIPROCAL_PI2 + 0.5;',
  44740. 'if (vDistanceToCenter > borderThickness && borderEnabled == 1.0) {',
  44741. 'gl_FragColor = vec4(strokeColor, 1.0);',
  44742. '} else {',
  44743. 'gl_FragColor = mix(texture2D(pano, sampleUV), vec4(backgroundColor, 1.0), clamp(pow((vDistance / 15.0), 2.0), 0.0, 1.0));',
  44744. '}',
  44745. '}'
  44746. ].join('\n')
  44747. });
  44748. /* eslint-enable */
  44749. },{"../core/component":126,"../core/shader":135,"../lib/three":174}],90:[function(_dereq_,module,exports){
  44750. var registerComponent = _dereq_('../core/component').registerComponent;
  44751. var THREE = _dereq_('../lib/three');
  44752. var utils = _dereq_('../utils/');
  44753. var bind = utils.bind;
  44754. var PolyfillControls = _dereq_('../utils').device.PolyfillControls;
  44755. // To avoid recalculation at every mouse movement tick
  44756. var GRABBING_CLASS = 'a-grabbing';
  44757. var PI_2 = Math.PI / 2;
  44758. var radToDeg = THREE.Math.radToDeg;
  44759. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  44760. /**
  44761. * look-controls. Update entity pose, factoring mouse, touch, and WebVR API data.
  44762. */
  44763. module.exports.Component = registerComponent('look-controls', {
  44764. dependencies: ['position', 'rotation'],
  44765. schema: {
  44766. enabled: {default: true},
  44767. touchEnabled: {default: true},
  44768. hmdEnabled: {default: true},
  44769. pointerLockEnabled: {default: true},
  44770. reverseMouseDrag: {default: false}
  44771. },
  44772. init: function () {
  44773. this.previousHMDPosition = new THREE.Vector3();
  44774. this.hmdQuaternion = new THREE.Quaternion();
  44775. this.hmdEuler = new THREE.Euler();
  44776. this.position = new THREE.Vector3();
  44777. // To save / restore camera pose
  44778. this.savedRotation = new THREE.Vector3();
  44779. this.savedPosition = new THREE.Vector3();
  44780. this.polyfillObject = new THREE.Object3D();
  44781. this.polyfillControls = new PolyfillControls(this.polyfillObject);
  44782. this.rotation = {};
  44783. this.deltaRotation = {};
  44784. this.savedPose = null;
  44785. this.pointerLocked = false;
  44786. this.setupMouseControls();
  44787. this.bindMethods();
  44788. // Call enter VR handler if the scene has entered VR before the event listeners attached.
  44789. if (this.el.sceneEl.is('vr-mode')) { this.onEnterVR(); }
  44790. },
  44791. update: function (oldData) {
  44792. var data = this.data;
  44793. // Disable grab cursor classes if no longer enabled.
  44794. if (data.enabled !== oldData.enabled) {
  44795. this.updateGrabCursor(data.enabled);
  44796. }
  44797. // Reset pitch and yaw if disabling HMD.
  44798. if (oldData && !data.hmdEnabled && !oldData.hmdEnabled) {
  44799. this.pitchObject.rotation.set(0, 0, 0);
  44800. this.yawObject.rotation.set(0, 0, 0);
  44801. }
  44802. if (oldData && !data.pointerLockEnabled !== oldData.pointerLockEnabled) {
  44803. this.removeEventListeners();
  44804. this.addEventListeners();
  44805. if (this.pointerLocked) { document.exitPointerLock(); }
  44806. }
  44807. },
  44808. tick: function (t) {
  44809. var data = this.data;
  44810. if (!data.enabled) { return; }
  44811. this.updateOrientation();
  44812. },
  44813. play: function () {
  44814. this.addEventListeners();
  44815. },
  44816. pause: function () {
  44817. this.removeEventListeners();
  44818. },
  44819. remove: function () {
  44820. this.removeEventListeners();
  44821. },
  44822. bindMethods: function () {
  44823. this.onMouseDown = bind(this.onMouseDown, this);
  44824. this.onMouseMove = bind(this.onMouseMove, this);
  44825. this.onMouseUp = bind(this.onMouseUp, this);
  44826. this.onTouchStart = bind(this.onTouchStart, this);
  44827. this.onTouchMove = bind(this.onTouchMove, this);
  44828. this.onTouchEnd = bind(this.onTouchEnd, this);
  44829. this.onEnterVR = bind(this.onEnterVR, this);
  44830. this.onExitVR = bind(this.onExitVR, this);
  44831. this.onPointerLockChange = bind(this.onPointerLockChange, this);
  44832. this.onPointerLockError = bind(this.onPointerLockError, this);
  44833. },
  44834. /**
  44835. * Set up states and Object3Ds needed to store rotation data.
  44836. */
  44837. setupMouseControls: function () {
  44838. this.mouseDown = false;
  44839. this.pitchObject = new THREE.Object3D();
  44840. this.yawObject = new THREE.Object3D();
  44841. this.yawObject.position.y = 10;
  44842. this.yawObject.add(this.pitchObject);
  44843. },
  44844. /**
  44845. * Add mouse and touch event listeners to canvas.
  44846. */
  44847. addEventListeners: function () {
  44848. var sceneEl = this.el.sceneEl;
  44849. var canvasEl = sceneEl.canvas;
  44850. // Wait for canvas to load.
  44851. if (!canvasEl) {
  44852. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  44853. return;
  44854. }
  44855. // Mouse events.
  44856. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  44857. window.addEventListener('mousemove', this.onMouseMove, false);
  44858. window.addEventListener('mouseup', this.onMouseUp, false);
  44859. // Touch events.
  44860. canvasEl.addEventListener('touchstart', this.onTouchStart);
  44861. window.addEventListener('touchmove', this.onTouchMove);
  44862. window.addEventListener('touchend', this.onTouchEnd);
  44863. // sceneEl events.
  44864. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  44865. sceneEl.addEventListener('exit-vr', this.onExitVR);
  44866. // Pointer Lock events.
  44867. if (this.data.pointerLockEnabled) {
  44868. document.addEventListener('pointerlockchange', this.onPointerLockChange, false);
  44869. document.addEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44870. document.addEventListener('pointerlockerror', this.onPointerLockError, false);
  44871. }
  44872. },
  44873. /**
  44874. * Remove mouse and touch event listeners from canvas.
  44875. */
  44876. removeEventListeners: function () {
  44877. var sceneEl = this.el.sceneEl;
  44878. var canvasEl = sceneEl && sceneEl.canvas;
  44879. if (!canvasEl) { return; }
  44880. // Mouse events.
  44881. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  44882. window.removeEventListener('mousemove', this.onMouseMove);
  44883. window.removeEventListener('mouseup', this.onMouseUp);
  44884. // Touch events.
  44885. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  44886. window.removeEventListener('touchmove', this.onTouchMove);
  44887. window.removeEventListener('touchend', this.onTouchEnd);
  44888. // sceneEl events.
  44889. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  44890. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  44891. // Pointer Lock events.
  44892. document.removeEventListener('pointerlockchange', this.onPointerLockChange, false);
  44893. document.removeEventListener('mozpointerlockchange', this.onPointerLockChange, false);
  44894. document.removeEventListener('pointerlockerror', this.onPointerLockError, false);
  44895. },
  44896. /**
  44897. * Update orientation for mobile, mouse drag, and headset.
  44898. * Mouse-drag only enabled if HMD is not active.
  44899. */
  44900. updateOrientation: function () {
  44901. var hmdEuler = this.hmdEuler;
  44902. var pitchObject = this.pitchObject;
  44903. var yawObject = this.yawObject;
  44904. var sceneEl = this.el.sceneEl;
  44905. var rotation = this.rotation;
  44906. // In VR mode, THREE is in charge of updating the camera rotation.
  44907. if (sceneEl.is('vr-mode') && sceneEl.checkHeadsetConnected()) { return; }
  44908. // Calculate polyfilled HMD quaternion.
  44909. this.polyfillControls.update();
  44910. hmdEuler.setFromQuaternion(this.polyfillObject.quaternion, 'YXZ');
  44911. // On mobile, do camera rotation with touch events and sensors.
  44912. rotation.x = radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x);
  44913. rotation.y = radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y);
  44914. rotation.z = 0;
  44915. this.el.setAttribute('rotation', rotation);
  44916. },
  44917. /**
  44918. * Translate mouse drag into rotation.
  44919. *
  44920. * Dragging up and down rotates the camera around the X-axis (yaw).
  44921. * Dragging left and right rotates the camera around the Y-axis (pitch).
  44922. */
  44923. onMouseMove: function (event) {
  44924. var pitchObject = this.pitchObject;
  44925. var yawObject = this.yawObject;
  44926. var previousMouseEvent = this.previousMouseEvent;
  44927. var movementX;
  44928. var movementY;
  44929. // Not dragging or not enabled.
  44930. if (!this.data.enabled || (!this.mouseDown && !this.pointerLocked)) { return; }
  44931. // Calculate delta.
  44932. movementX = event.movementX || event.mozMovementX;
  44933. movementY = event.movementY || event.mozMovementY;
  44934. if (movementX === undefined || movementY === undefined) {
  44935. movementX = event.screenX - previousMouseEvent.screenX;
  44936. movementY = event.screenY - previousMouseEvent.screenY;
  44937. }
  44938. this.previousMouseEvent = event;
  44939. // Calculate rotation.
  44940. yawObject.rotation.y -= movementX * 0.002;
  44941. pitchObject.rotation.x -= movementY * 0.002;
  44942. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44943. },
  44944. /**
  44945. * Register mouse down to detect mouse drag.
  44946. */
  44947. onMouseDown: function (evt) {
  44948. if (!this.data.enabled) { return; }
  44949. // Handle only primary button.
  44950. if (evt.button !== 0) { return; }
  44951. var sceneEl = this.el.sceneEl;
  44952. var canvasEl = sceneEl && sceneEl.canvas;
  44953. this.mouseDown = true;
  44954. this.previousMouseEvent = evt;
  44955. document.body.classList.add(GRABBING_CLASS);
  44956. if (this.data.pointerLockEnabled && !this.pointerLocked) {
  44957. if (canvasEl.requestPointerLock) {
  44958. canvasEl.requestPointerLock();
  44959. } else if (canvasEl.mozRequestPointerLock) {
  44960. canvasEl.mozRequestPointerLock();
  44961. }
  44962. }
  44963. },
  44964. /**
  44965. * Register mouse up to detect release of mouse drag.
  44966. */
  44967. onMouseUp: function () {
  44968. this.mouseDown = false;
  44969. document.body.classList.remove(GRABBING_CLASS);
  44970. },
  44971. /**
  44972. * Register touch down to detect touch drag.
  44973. */
  44974. onTouchStart: function (evt) {
  44975. if (evt.touches.length !== 1 || !this.data.touchEnabled) { return; }
  44976. this.touchStart = {
  44977. x: evt.touches[0].pageX,
  44978. y: evt.touches[0].pageY
  44979. };
  44980. this.touchStarted = true;
  44981. },
  44982. /**
  44983. * Translate touch move to Y-axis rotation.
  44984. */
  44985. onTouchMove: function (evt) {
  44986. var canvas = this.el.sceneEl.canvas;
  44987. var deltaY;
  44988. var yawObject = this.yawObject;
  44989. if (!this.touchStarted || !this.data.touchEnabled) { return; }
  44990. deltaY = 2 * Math.PI * (evt.touches[0].pageX - this.touchStart.x) / canvas.clientWidth;
  44991. // Limit touch orientaion to to yaw (y axis).
  44992. yawObject.rotation.y -= deltaY * 0.5;
  44993. this.touchStart = {
  44994. x: evt.touches[0].pageX,
  44995. y: evt.touches[0].pageY
  44996. };
  44997. },
  44998. /**
  44999. * Register touch end to detect release of touch drag.
  45000. */
  45001. onTouchEnd: function () {
  45002. this.touchStarted = false;
  45003. },
  45004. /**
  45005. * Save pose.
  45006. */
  45007. onEnterVR: function () {
  45008. this.saveCameraPose();
  45009. },
  45010. /**
  45011. * Restore the pose.
  45012. */
  45013. onExitVR: function () {
  45014. this.restoreCameraPose();
  45015. this.previousHMDPosition.set(0, 0, 0);
  45016. },
  45017. /**
  45018. * Update Pointer Lock state.
  45019. */
  45020. onPointerLockChange: function () {
  45021. this.pointerLocked = !!(document.pointerLockElement || document.mozPointerLockElement);
  45022. },
  45023. /**
  45024. * Recover from Pointer Lock error.
  45025. */
  45026. onPointerLockError: function () {
  45027. this.pointerLocked = false;
  45028. },
  45029. /**
  45030. * Toggle the feature of showing/hiding the grab cursor.
  45031. */
  45032. updateGrabCursor: function (enabled) {
  45033. var sceneEl = this.el.sceneEl;
  45034. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  45035. function disableGrabCursor () { sceneEl.canvas.classList.remove('a-grab-cursor'); }
  45036. if (!sceneEl.canvas) {
  45037. if (enabled) {
  45038. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  45039. } else {
  45040. sceneEl.addEventListener('render-target-loaded', disableGrabCursor);
  45041. }
  45042. return;
  45043. }
  45044. if (enabled) {
  45045. enableGrabCursor();
  45046. return;
  45047. }
  45048. disableGrabCursor();
  45049. },
  45050. /**
  45051. * Save camera pose before entering VR to restore later if exiting.
  45052. */
  45053. saveCameraPose: function () {
  45054. var el = this.el;
  45055. var position = el.getAttribute('position');
  45056. var rotation = el.getAttribute('rotation');
  45057. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  45058. if (this.savedPose || !hasPositionalTracking) { return; }
  45059. this.savedPose = {
  45060. position: this.savedPosition.copy(position),
  45061. rotation: this.savedRotation.copy(rotation)
  45062. };
  45063. },
  45064. /**
  45065. * Reset camera pose to before entering VR.
  45066. */
  45067. restoreCameraPose: function () {
  45068. var el = this.el;
  45069. var savedPose = this.savedPose;
  45070. var hasPositionalTracking = this.hasPositionalTracking !== undefined ? this.hasPositionalTracking : checkHasPositionalTracking();
  45071. if (!savedPose || !hasPositionalTracking) { return; }
  45072. // Reset camera orientation.
  45073. el.setAttribute('position', savedPose.position);
  45074. el.setAttribute('rotation', savedPose.rotation);
  45075. this.savedPose = null;
  45076. }
  45077. });
  45078. },{"../core/component":126,"../lib/three":174,"../utils":196,"../utils/":196}],91:[function(_dereq_,module,exports){
  45079. /* global Promise */
  45080. var utils = _dereq_('../utils/');
  45081. var component = _dereq_('../core/component');
  45082. var THREE = _dereq_('../lib/three');
  45083. var shader = _dereq_('../core/shader');
  45084. var error = utils.debug('components:material:error');
  45085. var registerComponent = component.registerComponent;
  45086. var shaders = shader.shaders;
  45087. var shaderNames = shader.shaderNames;
  45088. /**
  45089. * Material component.
  45090. *
  45091. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  45092. * three.js's implementation of PBR. Another standard shading model is `flat` which
  45093. * uses MeshBasicMaterial.
  45094. */
  45095. module.exports.Component = registerComponent('material', {
  45096. schema: {
  45097. alphaTest: {default: 0.0, min: 0.0, max: 1.0},
  45098. depthTest: {default: true},
  45099. depthWrite: {default: true},
  45100. flatShading: {default: false},
  45101. npot: {default: false},
  45102. offset: {type: 'vec2', default: {x: 0, y: 0}},
  45103. opacity: {default: 1.0, min: 0.0, max: 1.0},
  45104. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  45105. shader: {default: 'standard', oneOf: shaderNames},
  45106. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  45107. transparent: {default: false},
  45108. vertexColors: {type: 'string', default: 'none', oneOf: ['face', 'vertex']},
  45109. visible: {default: true}
  45110. },
  45111. init: function () {
  45112. this.material = null;
  45113. },
  45114. /**
  45115. * Update or create material.
  45116. *
  45117. * @param {object|null} oldData
  45118. */
  45119. update: function (oldData) {
  45120. var data = this.data;
  45121. if (!this.shader || data.shader !== oldData.shader) {
  45122. this.updateShader(data.shader);
  45123. }
  45124. this.shader.update(this.data);
  45125. this.updateMaterial(oldData);
  45126. },
  45127. updateSchema: function (data) {
  45128. var newShader = data.shader;
  45129. var currentShader = this.data && this.data.shader;
  45130. var shader = newShader || currentShader;
  45131. var schema = shaders[shader] && shaders[shader].schema;
  45132. if (!schema) { error('Unknown shader schema ' + shader); }
  45133. if (currentShader && newShader === currentShader) { return; }
  45134. this.extendSchema(schema);
  45135. this.updateBehavior();
  45136. },
  45137. updateBehavior: function () {
  45138. var schema = this.schema;
  45139. var self = this;
  45140. var sceneEl = this.el.sceneEl;
  45141. var tickProperties = {};
  45142. var tick = function (time, delta) {
  45143. Object.keys(tickProperties).forEach(function update (key) {
  45144. tickProperties[key] = time;
  45145. });
  45146. self.shader.update(tickProperties);
  45147. };
  45148. this.tick = undefined;
  45149. Object.keys(schema).forEach(function (key) {
  45150. if (schema[key].type === 'time') {
  45151. self.tick = tick;
  45152. tickProperties[key] = true;
  45153. }
  45154. });
  45155. if (!sceneEl) { return; }
  45156. if (!this.tick) {
  45157. sceneEl.removeBehavior(this);
  45158. } else {
  45159. sceneEl.addBehavior(this);
  45160. }
  45161. },
  45162. updateShader: function (shaderName) {
  45163. var data = this.data;
  45164. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  45165. var shaderInstance;
  45166. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  45167. // Get material from A-Frame shader.
  45168. shaderInstance = this.shader = new Shader();
  45169. shaderInstance.el = this.el;
  45170. shaderInstance.init(data);
  45171. this.setMaterial(shaderInstance.material);
  45172. this.updateSchema(data);
  45173. },
  45174. /**
  45175. * Set and update base material properties.
  45176. * Set `needsUpdate` when needed.
  45177. */
  45178. updateMaterial: function (oldData) {
  45179. var data = this.data;
  45180. var material = this.material;
  45181. // Base material properties.
  45182. material.alphaTest = data.alphaTest;
  45183. material.depthTest = data.depthTest !== false;
  45184. material.depthWrite = data.depthWrite !== false;
  45185. material.opacity = data.opacity;
  45186. material.flatShading = data.flatShading;
  45187. material.side = parseSide(data.side);
  45188. material.transparent = data.transparent !== false || data.opacity < 1.0;
  45189. material.vertexColors = parseVertexColors(data.vertexColors);
  45190. material.visible = data.visible;
  45191. // Check if material needs update.
  45192. if (Object.keys(oldData).length &&
  45193. (oldData.alphaTest !== data.alphaTest ||
  45194. oldData.side !== data.side ||
  45195. oldData.vertexColors !== data.vertexColors)) {
  45196. material.needsUpdate = true;
  45197. }
  45198. },
  45199. /**
  45200. * Remove material on remove (callback).
  45201. * Dispose of it from memory and unsubscribe from scene updates.
  45202. */
  45203. remove: function () {
  45204. var defaultMaterial = new THREE.MeshBasicMaterial();
  45205. var material = this.material;
  45206. var object3D = this.el.getObject3D('mesh');
  45207. if (object3D) { object3D.material = defaultMaterial; }
  45208. disposeMaterial(material, this.system);
  45209. },
  45210. /**
  45211. * (Re)create new material. Has side-effects of setting `this.material` and updating
  45212. * material registration in scene.
  45213. *
  45214. * @param {object} data - Material component data.
  45215. * @param {object} type - Material type to create.
  45216. * @returns {object} Material.
  45217. */
  45218. setMaterial: function (material) {
  45219. var el = this.el;
  45220. var mesh;
  45221. var system = this.system;
  45222. if (this.material) { disposeMaterial(this.material, system); }
  45223. this.material = material;
  45224. system.registerMaterial(material);
  45225. // Set on mesh. If mesh does not exist, wait for it.
  45226. mesh = el.getObject3D('mesh');
  45227. if (mesh) {
  45228. mesh.material = material;
  45229. } else {
  45230. el.addEventListener('object3dset', function waitForMesh (evt) {
  45231. if (evt.detail.type !== 'mesh' || evt.target !== el) { return; }
  45232. el.getObject3D('mesh').material = material;
  45233. el.removeEventListener('object3dset', waitForMesh);
  45234. });
  45235. }
  45236. }
  45237. });
  45238. /**
  45239. * Return a three.js constant determining which material face sides to render
  45240. * based on the side parameter (passed as a component property).
  45241. *
  45242. * @param {string} [side=front] - `front`, `back`, or `double`.
  45243. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  45244. */
  45245. function parseSide (side) {
  45246. switch (side) {
  45247. case 'back': {
  45248. return THREE.BackSide;
  45249. }
  45250. case 'double': {
  45251. return THREE.DoubleSide;
  45252. }
  45253. default: {
  45254. // Including case `front`.
  45255. return THREE.FrontSide;
  45256. }
  45257. }
  45258. }
  45259. /**
  45260. * Return a three.js constant determining vertex coloring.
  45261. */
  45262. function parseVertexColors (coloring) {
  45263. switch (coloring) {
  45264. case 'face': {
  45265. return THREE.FaceColors;
  45266. }
  45267. case 'vertex': {
  45268. return THREE.VertexColors;
  45269. }
  45270. default: {
  45271. return THREE.NoColors;
  45272. }
  45273. }
  45274. }
  45275. /**
  45276. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  45277. */
  45278. function disposeMaterial (material, system) {
  45279. material.dispose();
  45280. system.unregisterMaterial(material);
  45281. }
  45282. },{"../core/component":126,"../core/shader":135,"../lib/three":174,"../utils/":196}],92:[function(_dereq_,module,exports){
  45283. var debug = _dereq_('../utils/debug');
  45284. var registerComponent = _dereq_('../core/component').registerComponent;
  45285. var THREE = _dereq_('../lib/three');
  45286. var warn = debug('components:obj-model:warn');
  45287. module.exports.Component = registerComponent('obj-model', {
  45288. schema: {
  45289. mtl: {type: 'model'},
  45290. obj: {type: 'model'}
  45291. },
  45292. init: function () {
  45293. this.model = null;
  45294. this.objLoader = new THREE.OBJLoader();
  45295. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  45296. // Allow cross-origin images to be loaded.
  45297. this.mtlLoader.crossOrigin = '';
  45298. },
  45299. update: function () {
  45300. var data = this.data;
  45301. if (!data.obj) { return; }
  45302. this.remove();
  45303. this.loadObj(data.obj, data.mtl);
  45304. },
  45305. remove: function () {
  45306. if (!this.model) { return; }
  45307. this.el.removeObject3D('mesh');
  45308. },
  45309. loadObj: function (objUrl, mtlUrl) {
  45310. var self = this;
  45311. var el = this.el;
  45312. var mtlLoader = this.mtlLoader;
  45313. var objLoader = this.objLoader;
  45314. if (mtlUrl) {
  45315. // .OBJ with an .MTL.
  45316. if (el.hasAttribute('material')) {
  45317. warn('Material component properties are ignored when a .MTL is provided');
  45318. }
  45319. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  45320. mtlLoader.load(mtlUrl, function (materials) {
  45321. materials.preload();
  45322. objLoader.setMaterials(materials);
  45323. objLoader.load(objUrl, function (objModel) {
  45324. self.model = objModel;
  45325. el.setObject3D('mesh', objModel);
  45326. el.emit('model-loaded', {format: 'obj', model: objModel});
  45327. });
  45328. });
  45329. return;
  45330. }
  45331. // .OBJ only.
  45332. objLoader.load(objUrl, function loadObjOnly (objModel) {
  45333. // Apply material.
  45334. var material = el.components.material;
  45335. if (material) {
  45336. objModel.traverse(function (child) {
  45337. if (child instanceof THREE.Mesh) {
  45338. child.material = material.material;
  45339. }
  45340. });
  45341. }
  45342. self.model = objModel;
  45343. el.setObject3D('mesh', objModel);
  45344. el.emit('model-loaded', {format: 'obj', model: objModel});
  45345. });
  45346. }
  45347. });
  45348. },{"../core/component":126,"../lib/three":174,"../utils/debug":192}],93:[function(_dereq_,module,exports){
  45349. var bind = _dereq_('../utils/bind');
  45350. var registerComponent = _dereq_('../core/component').registerComponent;
  45351. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  45352. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  45353. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  45354. var TOUCH_CONTROLLER_MODEL_OBJ_URL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.obj';
  45355. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.mtl';
  45356. var TOUCH_CONTROLLER_MODEL_OBJ_URL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.obj';
  45357. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.mtl';
  45358. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  45359. var PIVOT_OFFSET = {x: 0, y: -0.015, z: 0.04};
  45360. /**
  45361. * Oculus Touch controls.
  45362. * Interface with Oculus Touch controllers and map Gamepad events to
  45363. * controller buttons: thumbstick, trigger, grip, xbutton, ybutton, surface
  45364. * Load a controller model and highlight the pressed buttons.
  45365. */
  45366. module.exports.Component = registerComponent('oculus-touch-controls', {
  45367. schema: {
  45368. hand: {default: 'left'},
  45369. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  45370. buttonTouchColor: {type: 'color', default: '#8AB'},
  45371. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  45372. model: {default: true},
  45373. rotationOffset: {default: 0}
  45374. },
  45375. /**
  45376. * Button IDs:
  45377. * 0 - thumbstick (which has separate axismove / thumbstickmoved events)
  45378. * 1 - trigger (with analog value, which goes up to 1)
  45379. * 2 - grip (with analog value, which goes up to 1)
  45380. * 3 - X (left) or A (right)
  45381. * 4 - Y (left) or B (right)
  45382. * 5 - surface (touch only)
  45383. */
  45384. mapping: {
  45385. left: {
  45386. axes: {thumbstick: [0, 1]},
  45387. buttons: ['thumbstick', 'trigger', 'grip', 'xbutton', 'ybutton', 'surface']
  45388. },
  45389. right: {
  45390. axes: {thumbstick: [0, 1]},
  45391. buttons: ['thumbstick', 'trigger', 'grip', 'abutton', 'bbutton', 'surface']
  45392. }
  45393. },
  45394. bindMethods: function () {
  45395. this.onModelLoaded = bind(this.onModelLoaded, this);
  45396. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45397. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45398. this.onAxisMoved = bind(this.onAxisMoved, this);
  45399. },
  45400. init: function () {
  45401. var self = this;
  45402. this.onButtonChanged = bind(this.onButtonChanged, this);
  45403. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self, self.data.hand); };
  45404. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self, self.data.hand); };
  45405. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self, self.data.hand); };
  45406. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self, self.data.hand); };
  45407. this.controllerPresent = false;
  45408. this.lastControllerCheck = 0;
  45409. this.previousButtonValues = {};
  45410. this.bindMethods();
  45411. // Allow mock.
  45412. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  45413. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  45414. },
  45415. addEventListeners: function () {
  45416. var el = this.el;
  45417. el.addEventListener('buttonchanged', this.onButtonChanged);
  45418. el.addEventListener('buttondown', this.onButtonDown);
  45419. el.addEventListener('buttonup', this.onButtonUp);
  45420. el.addEventListener('touchstart', this.onButtonTouchStart);
  45421. el.addEventListener('touchend', this.onButtonTouchEnd);
  45422. el.addEventListener('axismove', this.onAxisMoved);
  45423. el.addEventListener('model-loaded', this.onModelLoaded);
  45424. this.controllerEventsActive = true;
  45425. },
  45426. removeEventListeners: function () {
  45427. var el = this.el;
  45428. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45429. el.removeEventListener('buttondown', this.onButtonDown);
  45430. el.removeEventListener('buttonup', this.onButtonUp);
  45431. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45432. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45433. el.removeEventListener('axismove', this.onAxisMoved);
  45434. el.removeEventListener('model-loaded', this.onModelLoaded);
  45435. this.controllerEventsActive = false;
  45436. },
  45437. checkIfControllerPresent: function () {
  45438. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  45439. hand: this.data.hand
  45440. });
  45441. },
  45442. play: function () {
  45443. this.checkIfControllerPresent();
  45444. this.addControllersUpdateListener();
  45445. },
  45446. pause: function () {
  45447. this.removeEventListeners();
  45448. this.removeControllersUpdateListener();
  45449. },
  45450. updateControllerModel: function () {
  45451. var objUrl, mtlUrl;
  45452. if (!this.data.model) { return; }
  45453. if (this.data.hand === 'right') {
  45454. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_R + ')';
  45455. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_R + ')';
  45456. } else {
  45457. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_L + ')';
  45458. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_L + ')';
  45459. }
  45460. this.el.setAttribute('obj-model', {obj: objUrl, mtl: mtlUrl});
  45461. },
  45462. injectTrackedControls: function () {
  45463. var data = this.data;
  45464. var offset = data.hand === 'right' ? -90 : 90;
  45465. this.el.setAttribute('tracked-controls', {
  45466. id: data.hand === 'right' ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45467. controller: 0,
  45468. rotationOffset: data.rotationOffset !== -999 ? data.rotationOffset : offset
  45469. });
  45470. this.updateControllerModel();
  45471. },
  45472. addControllersUpdateListener: function () {
  45473. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45474. },
  45475. removeControllersUpdateListener: function () {
  45476. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45477. },
  45478. onControllersUpdate: function () {
  45479. // Note that due to gamepadconnected event propagation issues, we don't rely on events.
  45480. this.checkIfControllerPresent();
  45481. },
  45482. onButtonChanged: function (evt) {
  45483. var button = this.mapping[this.data.hand].buttons[evt.detail.id];
  45484. var buttonMeshes = this.buttonMeshes;
  45485. var analogValue;
  45486. if (!button) { return; }
  45487. if (button === 'trigger' || button === 'grip') { analogValue = evt.detail.state.value; }
  45488. // Update trigger and/or grip meshes, if any.
  45489. if (buttonMeshes) {
  45490. if (button === 'trigger' && buttonMeshes.trigger) {
  45491. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45492. }
  45493. if (button === 'grip' && buttonMeshes.grip) {
  45494. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45495. }
  45496. }
  45497. // Pass along changed event with button state, using the buttom mapping for convenience.
  45498. this.el.emit(button + 'changed', evt.detail.state);
  45499. },
  45500. onModelLoaded: function (evt) {
  45501. var controllerObject3D = evt.detail.model;
  45502. var buttonMeshes;
  45503. if (!this.data.model) { return; }
  45504. var leftHand = this.data.hand === 'left';
  45505. buttonMeshes = this.buttonMeshes = {};
  45506. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45507. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45508. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45509. buttonMeshes.xbutton = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45510. buttonMeshes.abutton = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45511. buttonMeshes.ybutton = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45512. buttonMeshes.bbutton = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45513. // Offset pivot point
  45514. controllerObject3D.position = PIVOT_OFFSET;
  45515. },
  45516. onAxisMoved: function (evt) {
  45517. this.emitIfAxesChanged(this, this.mapping[this.data.hand].axes, evt);
  45518. },
  45519. updateModel: function (buttonName, evtName) {
  45520. if (!this.data.model) { return; }
  45521. this.updateButtonModel(buttonName, evtName);
  45522. },
  45523. updateButtonModel: function (buttonName, state) {
  45524. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  45525. var buttonMeshes = this.buttonMeshes;
  45526. if (!this.data.model) { return; }
  45527. if (buttonMeshes && buttonMeshes[buttonName]) {
  45528. buttonMeshes[buttonName].material.color.set(color);
  45529. }
  45530. }
  45531. });
  45532. },{"../core/component":126,"../utils/bind":190,"../utils/tracked-controls":201}],94:[function(_dereq_,module,exports){
  45533. var registerComponent = _dereq_('../core/component').registerComponent;
  45534. module.exports.Component = registerComponent('position', {
  45535. schema: {type: 'vec3'},
  45536. update: function () {
  45537. var object3D = this.el.object3D;
  45538. var data = this.data;
  45539. object3D.position.set(data.x, data.y, data.z);
  45540. }
  45541. });
  45542. },{"../core/component":126}],95:[function(_dereq_,module,exports){
  45543. /* global MutationObserver */
  45544. var registerComponent = _dereq_('../core/component').registerComponent;
  45545. var THREE = _dereq_('../lib/three');
  45546. var utils = _dereq_('../utils/');
  45547. var warn = utils.debug('components:raycaster:warn');
  45548. // Defines selectors that should be 'safe' for the MutationObserver used to
  45549. // refresh the whitelist. Matches classnames, IDs, and presence of attributes.
  45550. // Selectors for the value of an attribute, like [position=0 2 0], cannot be
  45551. // reliably detected and are therefore disallowed.
  45552. var OBSERVER_SELECTOR_RE = /^[\w\s-.,[\]#]*$/;
  45553. // Configuration for the MutationObserver used to refresh the whitelist.
  45554. // Listens for addition/removal of elements and attributes within the scene.
  45555. var OBSERVER_CONFIG = {
  45556. childList: true,
  45557. attributes: true,
  45558. subtree: true
  45559. };
  45560. /**
  45561. * Raycaster component.
  45562. *
  45563. * Pass options to three.js Raycaster including which objects to test.
  45564. * Poll for intersections.
  45565. * Emit event on origin entity and on target entity on intersect.
  45566. *
  45567. * @member {array} intersectedEls - List of currently intersected entities.
  45568. * @member {array} objects - Cached list of meshes to intersect.
  45569. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45570. * @member {object} raycaster - three.js Raycaster.
  45571. */
  45572. module.exports.Component = registerComponent('raycaster', {
  45573. schema: {
  45574. autoRefresh: {default: true},
  45575. direction: {type: 'vec3', default: {x: 0, y: 0, z: -1}},
  45576. enabled: {default: true},
  45577. far: {default: 1000},
  45578. interval: {default: 0},
  45579. near: {default: 0},
  45580. objects: {default: ''},
  45581. origin: {type: 'vec3'},
  45582. recursive: {default: true},
  45583. showLine: {default: false},
  45584. useWorldCoordinates: {default: false}
  45585. },
  45586. init: function () {
  45587. this.clearedIntersectedEls = [];
  45588. this.unitLineEndVec3 = new THREE.Vector3();
  45589. this.intersectedEls = [];
  45590. this.intersections = [];
  45591. this.newIntersectedEls = [];
  45592. this.newIntersections = [];
  45593. this.objects = [];
  45594. this.prevCheckTime = undefined;
  45595. this.prevIntersectedEls = [];
  45596. this.raycaster = new THREE.Raycaster();
  45597. this.updateOriginDirection();
  45598. this.setDirty = this.setDirty.bind(this);
  45599. this.observer = new MutationObserver(this.setDirty);
  45600. this.dirty = true;
  45601. this.lineEndVec3 = new THREE.Vector3();
  45602. this.otherLineEndVec3 = new THREE.Vector3();
  45603. this.lineData = {end: this.lineEndVec3};
  45604. this.intersectedClearedDetail = {el: this.el};
  45605. this.intersectionClearedDetail = {clearedEls: this.clearedIntersectedEls};
  45606. },
  45607. /**
  45608. * Create or update raycaster object.
  45609. */
  45610. update: function (oldData) {
  45611. var data = this.data;
  45612. var el = this.el;
  45613. var raycaster = this.raycaster;
  45614. // Set raycaster properties.
  45615. raycaster.far = data.far;
  45616. raycaster.near = data.near;
  45617. // Draw line.
  45618. if (data.showLine &&
  45619. (data.far !== oldData.far || data.origin !== oldData.origin ||
  45620. data.direction !== oldData.direction || !oldData.showLine)) {
  45621. // Calculate unit vector for line direction. Can be multiplied via scalar to performantly
  45622. // adjust line length.
  45623. this.unitLineEndVec3.copy(data.origin).add(data.direction).normalize();
  45624. this.drawLine();
  45625. }
  45626. if (!data.showLine && oldData.showLine) {
  45627. el.removeAttribute('line');
  45628. }
  45629. if (data.objects !== oldData.objects && !OBSERVER_SELECTOR_RE.test(data.objects)) {
  45630. warn('Selector "' + data.objects + '" may not update automatically with DOM changes.');
  45631. }
  45632. if (data.autoRefresh !== oldData.autoRefresh && el.isPlaying) {
  45633. data.autoRefresh
  45634. ? this.addEventListeners()
  45635. : this.removeEventListeners();
  45636. }
  45637. this.setDirty();
  45638. },
  45639. play: function () {
  45640. this.addEventListeners();
  45641. },
  45642. pause: function () {
  45643. this.removeEventListeners();
  45644. },
  45645. remove: function () {
  45646. if (this.data.showLine) {
  45647. this.el.removeAttribute('line');
  45648. }
  45649. },
  45650. addEventListeners: function () {
  45651. if (!this.data.autoRefresh) { return; }
  45652. this.observer.observe(this.el.sceneEl, OBSERVER_CONFIG);
  45653. this.el.sceneEl.addEventListener('object3dset', this.setDirty);
  45654. this.el.sceneEl.addEventListener('object3dremove', this.setDirty);
  45655. },
  45656. removeEventListeners: function () {
  45657. this.observer.disconnect();
  45658. this.el.sceneEl.removeEventListener('object3dset', this.setDirty);
  45659. this.el.sceneEl.removeEventListener('object3dremove', this.setDirty);
  45660. },
  45661. /**
  45662. * Mark the object list as dirty, to be refreshed before next raycast.
  45663. */
  45664. setDirty: function () {
  45665. this.dirty = true;
  45666. },
  45667. /**
  45668. * Update list of objects to test for intersection.
  45669. */
  45670. refreshObjects: function () {
  45671. var data = this.data;
  45672. var els;
  45673. // If objects not defined, intersect with everything.
  45674. els = data.objects
  45675. ? this.el.sceneEl.querySelectorAll(data.objects)
  45676. : this.el.sceneEl.children;
  45677. this.objects = this.flattenChildrenShallow(els);
  45678. this.dirty = false;
  45679. },
  45680. /**
  45681. * Check for intersections and cleared intersections on an interval.
  45682. */
  45683. tick: function (time) {
  45684. var data = this.data;
  45685. var prevCheckTime = this.prevCheckTime;
  45686. // Only check for intersection if interval time has passed.
  45687. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45688. // Update check time.
  45689. this.prevCheckTime = time;
  45690. this.checkIntersections();
  45691. },
  45692. /**
  45693. * Raycast for intersections and emit events for current and cleared inersections.
  45694. */
  45695. checkIntersections: function () {
  45696. var clearedIntersectedEls = this.clearedIntersectedEls;
  45697. var el = this.el;
  45698. var data = this.data;
  45699. var i;
  45700. var intersectedEls = this.intersectedEls;
  45701. var intersection;
  45702. var intersections = this.intersections;
  45703. var lineLength;
  45704. var newIntersectedEls = this.newIntersectedEls;
  45705. var newIntersections = this.newIntersections;
  45706. var prevIntersectedEls = this.prevIntersectedEls;
  45707. var rawIntersections;
  45708. var self = this;
  45709. if (!this.data.enabled) { return; }
  45710. // Refresh the object whitelist if needed.
  45711. if (this.dirty) { this.refreshObjects(); }
  45712. // Store old previously intersected entities.
  45713. copyArray(this.prevIntersectedEls, this.intersectedEls);
  45714. // Raycast.
  45715. this.updateOriginDirection();
  45716. rawIntersections = this.raycaster.intersectObjects(this.objects, data.recursive);
  45717. // Only keep intersections against objects that have a reference to an entity.
  45718. intersections.length = 0;
  45719. intersectedEls.length = 0;
  45720. for (i = 0; i < rawIntersections.length; i++) {
  45721. intersection = rawIntersections[i];
  45722. // Don't intersect with own line.
  45723. if (data.showLine && intersection.object === el.getObject3D('line')) {
  45724. continue;
  45725. }
  45726. if (intersection.object.el) {
  45727. intersections.push(intersection);
  45728. intersectedEls.push(intersection.object.el);
  45729. }
  45730. }
  45731. // Get newly intersected entities.
  45732. newIntersections.length = 0;
  45733. newIntersectedEls.length = 0;
  45734. for (i = 0; i < intersections.length; i++) {
  45735. if (prevIntersectedEls.indexOf(intersections[i].object.el) === -1) {
  45736. newIntersections.push(intersections[i]);
  45737. newIntersectedEls.push(intersections[i].object.el);
  45738. }
  45739. }
  45740. // Emit intersection cleared on both entities per formerly intersected entity.
  45741. clearedIntersectedEls.length = 0;
  45742. for (i = 0; i < prevIntersectedEls.length; i++) {
  45743. if (intersectedEls.indexOf(prevIntersectedEls[i]) !== -1) { continue; }
  45744. prevIntersectedEls[i].emit('raycaster-intersected-cleared',
  45745. this.intersectedClearedDetail);
  45746. clearedIntersectedEls.push(prevIntersectedEls[i]);
  45747. }
  45748. if (clearedIntersectedEls.length) {
  45749. el.emit('raycaster-intersection-cleared', this.intersectionClearedDetail);
  45750. }
  45751. // Emit intersected on intersected entity per intersected entity.
  45752. for (i = 0; i < newIntersectedEls.length; i++) {
  45753. newIntersectedEls[i].emit('raycaster-intersected', {
  45754. el: el,
  45755. intersection: newIntersections[i]
  45756. });
  45757. }
  45758. // Emit all intersections at once on raycasting entity.
  45759. if (newIntersections.length) {
  45760. el.emit('raycaster-intersection', {
  45761. els: newIntersectedEls,
  45762. intersections: newIntersections
  45763. });
  45764. }
  45765. // Update line length.
  45766. setTimeout(function () {
  45767. if (self.data.showLine) {
  45768. if (intersections.length) {
  45769. if (intersections[0].object.el === el && intersections[1]) {
  45770. lineLength = intersections[1].distance;
  45771. } else {
  45772. lineLength = intersections[0].distance;
  45773. }
  45774. }
  45775. self.drawLine(lineLength);
  45776. }
  45777. });
  45778. },
  45779. /**
  45780. * Update origin and direction of raycaster using entity transforms and supplied origin or
  45781. * direction offsets.
  45782. */
  45783. updateOriginDirection: (function () {
  45784. var direction = new THREE.Vector3();
  45785. var originVec3 = new THREE.Vector3();
  45786. // Closure to make quaternion/vector3 objects private.
  45787. return function updateOriginDirection () {
  45788. var el = this.el;
  45789. var data = this.data;
  45790. if (data.useWorldCoordinates) {
  45791. this.raycaster.set(data.origin, data.direction);
  45792. return;
  45793. }
  45794. // Grab the position and rotation.
  45795. el.object3D.updateMatrixWorld();
  45796. el.object3D.getWorldPosition(originVec3);
  45797. // If non-zero origin, translate the origin into world space.
  45798. if (data.origin.x !== 0 || data.origin.y !== 0 || data.origin.z !== 0) {
  45799. originVec3 = el.object3D.localToWorld(originVec3.copy(data.origin));
  45800. }
  45801. // three.js raycaster direction is relative to 0, 0, 0 NOT the origin / offset we
  45802. // provide. Apply the offset to the direction, then rotation from the object,
  45803. // and normalize.
  45804. direction.copy(data.direction).transformDirection(el.object3D.matrixWorld).normalize();
  45805. // Apply offset and direction, in world coordinates.
  45806. this.raycaster.set(originVec3, direction);
  45807. };
  45808. })(),
  45809. /**
  45810. * Create or update line to give raycaster visual representation.
  45811. * Customize the line through through line component.
  45812. * We draw the line in the raycaster component to customize the line to the
  45813. * raycaster's origin, direction, and far.
  45814. *
  45815. * Unlike the raycaster, we create the line as a child of the object. The line will
  45816. * be affected by the transforms of the objects, so we don't have to calculate transforms
  45817. * like we do with the raycaster.
  45818. *
  45819. * @param {number} length - Length of line. Pass in to shorten the line to the intersection
  45820. * point. If not provided, length will default to the max length, `raycaster.far`.
  45821. */
  45822. drawLine: function (length) {
  45823. var data = this.data;
  45824. var el = this.el;
  45825. var endVec3;
  45826. // Switch each time vector so line update triggered and to avoid unnecessary vector clone.
  45827. endVec3 = this.lineData.end === this.lineEndVec3
  45828. ? this.otherLineEndVec3
  45829. : this.lineEndVec3;
  45830. // Treat Infinity as 1000m for the line.
  45831. if (length === undefined) {
  45832. length = data.far === Infinity ? 1000 : data.far;
  45833. }
  45834. // Update the length of the line if given. `unitLineEndVec3` is the direction
  45835. // given by data.direction, then we apply a scalar to give it a length.
  45836. this.lineData.start = data.origin;
  45837. this.lineData.end = endVec3.copy(this.unitLineEndVec3).multiplyScalar(length);
  45838. el.setAttribute('line', this.lineData);
  45839. },
  45840. /**
  45841. * Return children of each element's object3D group. Children are flattened
  45842. * by one level, removing the THREE.Group wrapper, so that non-recursive
  45843. * raycasting remains useful.
  45844. *
  45845. * @param {Array<Element>} els
  45846. * @return {Array<THREE.Object3D>}
  45847. */
  45848. flattenChildrenShallow: (function () {
  45849. var groups = [];
  45850. return function (els) {
  45851. var children;
  45852. var i;
  45853. var objects = this.objects;
  45854. // Push meshes onto list of objects to intersect.
  45855. groups.length = 0;
  45856. for (i = 0; i < els.length; i++) {
  45857. if (els[i].object3D) {
  45858. groups.push(els[i].object3D);
  45859. }
  45860. }
  45861. // Each entity's root is a THREE.Group. Return the group's chilrden.
  45862. objects.length = 0;
  45863. for (i = 0; i < groups.length; i++) {
  45864. children = groups[i].children;
  45865. if (children && children.length) {
  45866. objects.push.apply(objects, children);
  45867. }
  45868. }
  45869. return objects;
  45870. };
  45871. })()
  45872. });
  45873. /**
  45874. * Copy contents of one array to another without allocating new array.
  45875. */
  45876. function copyArray (a, b) {
  45877. var i;
  45878. a.length = b.length;
  45879. for (i = 0; i < b.length; i++) {
  45880. a[i] = b[i];
  45881. }
  45882. }
  45883. },{"../core/component":126,"../lib/three":174,"../utils/":196}],96:[function(_dereq_,module,exports){
  45884. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45885. var registerComponent = _dereq_('../core/component').registerComponent;
  45886. module.exports.Component = registerComponent('rotation', {
  45887. schema: {type: 'vec3'},
  45888. /**
  45889. * Updates object3D rotation.
  45890. */
  45891. update: function () {
  45892. var data = this.data;
  45893. var object3D = this.el.object3D;
  45894. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45895. object3D.rotation.order = 'YXZ';
  45896. }
  45897. });
  45898. },{"../core/component":126,"../lib/three":174}],97:[function(_dereq_,module,exports){
  45899. var registerComponent = _dereq_('../core/component').registerComponent;
  45900. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45901. var zeroScale = 0.00001;
  45902. module.exports.Component = registerComponent('scale', {
  45903. schema: {
  45904. type: 'vec3',
  45905. default: {x: 1, y: 1, z: 1}
  45906. },
  45907. update: function () {
  45908. var data = this.data;
  45909. var object3D = this.el.object3D;
  45910. var x = data.x === 0 ? zeroScale : data.x;
  45911. var y = data.y === 0 ? zeroScale : data.y;
  45912. var z = data.z === 0 ? zeroScale : data.z;
  45913. object3D.scale.set(x, y, z);
  45914. }
  45915. });
  45916. },{"../core/component":126}],98:[function(_dereq_,module,exports){
  45917. /* global THREE */
  45918. var register = _dereq_('../../core/component').registerComponent;
  45919. module.exports.Component = register('background', {
  45920. schema: {
  45921. color: {type: 'color', default: 'black'},
  45922. transparent: {default: false}
  45923. },
  45924. update: function () {
  45925. var data = this.data;
  45926. var object3D = this.el.object3D;
  45927. if (data.transparent) {
  45928. object3D.background = null;
  45929. return;
  45930. }
  45931. object3D.background = new THREE.Color(data.color);
  45932. }
  45933. });
  45934. },{"../../core/component":126}],99:[function(_dereq_,module,exports){
  45935. var register = _dereq_('../../core/component').registerComponent;
  45936. module.exports.Component = register('debug', {
  45937. schema: {default: true}
  45938. });
  45939. },{"../../core/component":126}],100:[function(_dereq_,module,exports){
  45940. var registerComponent = _dereq_('../../core/component').registerComponent;
  45941. /**
  45942. * Component to embed an a-frame scene within the layout of a 2D page.
  45943. */
  45944. module.exports.Component = registerComponent('embedded', {
  45945. dependencies: ['vr-mode-ui'],
  45946. schema: {default: true},
  45947. update: function () {
  45948. var sceneEl = this.el;
  45949. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45950. if (this.data === true) {
  45951. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45952. sceneEl.removeFullScreenStyles();
  45953. } else {
  45954. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45955. sceneEl.addFullScreenStyles();
  45956. }
  45957. }
  45958. });
  45959. },{"../../core/component":126}],101:[function(_dereq_,module,exports){
  45960. var register = _dereq_('../../core/component').registerComponent;
  45961. var THREE = _dereq_('../../lib/three');
  45962. var debug = _dereq_('../../utils/debug');
  45963. var warn = debug('components:fog:warn');
  45964. /**
  45965. * Fog component.
  45966. * Applies only to the scene entity.
  45967. */
  45968. module.exports.Component = register('fog', {
  45969. schema: {
  45970. color: {type: 'color', default: '#000'},
  45971. density: {default: 0.00025},
  45972. far: {default: 1000, min: 0},
  45973. near: {default: 1, min: 0},
  45974. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45975. },
  45976. update: function () {
  45977. var data = this.data;
  45978. var el = this.el;
  45979. var fog = this.el.object3D.fog;
  45980. if (!el.isScene) {
  45981. warn('Fog component can only be applied to <a-scene>');
  45982. return;
  45983. }
  45984. // (Re)create fog if fog doesn't exist or fog type changed.
  45985. if (!fog || data.type !== fog.name) {
  45986. el.object3D.fog = getFog(data);
  45987. el.systems.material.updateMaterials();
  45988. return;
  45989. }
  45990. // Fog data changed. Update fog.
  45991. Object.keys(this.schema).forEach(function (key) {
  45992. var value = data[key];
  45993. if (key === 'color') { value = new THREE.Color(value); }
  45994. fog[key] = value;
  45995. });
  45996. },
  45997. /**
  45998. * Remove fog on remove (callback).
  45999. */
  46000. remove: function () {
  46001. var fog = this.el.object3D.fog;
  46002. if (!fog) { return; }
  46003. fog.far = 0;
  46004. fog.near = 0.1;
  46005. }
  46006. });
  46007. /**
  46008. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  46009. *
  46010. * @param {object} data - Fog data.
  46011. * @returns {object} fog
  46012. */
  46013. function getFog (data) {
  46014. var fog;
  46015. if (data.type === 'exponential') {
  46016. fog = new THREE.FogExp2(data.color, data.density);
  46017. } else {
  46018. fog = new THREE.Fog(data.color, data.near, data.far);
  46019. }
  46020. fog.name = data.type;
  46021. return fog;
  46022. }
  46023. },{"../../core/component":126,"../../lib/three":174,"../../utils/debug":192}],102:[function(_dereq_,module,exports){
  46024. (function (process){
  46025. /* global AFRAME */
  46026. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  46027. var bind = _dereq_('../../utils/bind');
  46028. var pkg = _dereq_('../../../package');
  46029. var registerComponent = _dereq_('../../core/component').registerComponent;
  46030. /**
  46031. * 0.4.2 to 0.4.x
  46032. * Will need to update this when A-Frame goes to 1.x.x.
  46033. */
  46034. function getFuzzyPatchVersion (version) {
  46035. var split = version.split('.');
  46036. split[2] = 'x';
  46037. return split.join('.');
  46038. }
  46039. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  46040. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  46041. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  46042. var LOADING_MESSAGE = 'Loading Inspector';
  46043. var LOADING_ERROR_MESSAGE = 'Error loading Inspector';
  46044. module.exports.Component = registerComponent('inspector', {
  46045. schema: {
  46046. url: {default: INSPECTOR_URL}
  46047. },
  46048. init: function () {
  46049. this.onKeydown = bind(this.onKeydown, this);
  46050. this.onMessage = bind(this.onMessage, this);
  46051. this.initOverlay();
  46052. window.addEventListener('keydown', this.onKeydown);
  46053. window.addEventListener('message', this.onMessage);
  46054. },
  46055. initOverlay: function () {
  46056. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  46057. this.loadingMessageEl = document.createElement('div');
  46058. this.loadingMessageEl.classList.add('a-inspector-loader');
  46059. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  46060. },
  46061. remove: function () {
  46062. this.removeEventListeners();
  46063. },
  46064. /**
  46065. * <ctrl> + <alt> + i keyboard shortcut.
  46066. */
  46067. onKeydown: function (evt) {
  46068. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  46069. if (!this.data || !shortcutPressed) { return; }
  46070. this.injectInspector();
  46071. },
  46072. showLoader: function () {
  46073. document.body.appendChild(this.loadingMessageEl);
  46074. },
  46075. hideLoader: function () {
  46076. document.body.removeChild(this.loadingMessageEl);
  46077. },
  46078. /**
  46079. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  46080. */
  46081. onMessage: function (evt) {
  46082. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  46083. },
  46084. injectInspector: function () {
  46085. var self = this;
  46086. var script;
  46087. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  46088. this.showLoader();
  46089. // Inject.
  46090. script = document.createElement('script');
  46091. script.src = this.data.url;
  46092. script.setAttribute('data-name', 'aframe-inspector');
  46093. script.setAttribute(AFRAME_INJECTED, '');
  46094. script.onload = function () {
  46095. AFRAME.INSPECTOR.open();
  46096. self.hideLoader();
  46097. self.removeEventListeners();
  46098. };
  46099. script.onerror = function () {
  46100. self.loadingMessageEl.innerHTML = LOADING_ERROR_MESSAGE;
  46101. };
  46102. document.head.appendChild(script);
  46103. AFRAME.inspectorInjected = true;
  46104. },
  46105. removeEventListeners: function () {
  46106. window.removeEventListener('keydown', this.onKeydown);
  46107. window.removeEventListener('message', this.onMessage);
  46108. }
  46109. });
  46110. }).call(this,_dereq_('_process'))
  46111. },{"../../../package":76,"../../constants":117,"../../core/component":126,"../../utils/bind":190,"_process":33}],103:[function(_dereq_,module,exports){
  46112. var registerComponent = _dereq_('../../core/component').registerComponent;
  46113. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  46114. module.exports.Component = registerComponent('keyboard-shortcuts', {
  46115. schema: {
  46116. enterVR: {default: true},
  46117. exitVR: {default: true}
  46118. },
  46119. init: function () {
  46120. var self = this;
  46121. var scene = this.el;
  46122. this.listener = window.addEventListener('keyup', function (event) {
  46123. if (!shouldCaptureKeyEvent(event)) { return; }
  46124. if (self.enterVREnabled && event.keyCode === 70) { // f.
  46125. scene.enterVR();
  46126. }
  46127. if (self.enterVREnabled && event.keyCode === 27) { // escape.
  46128. scene.exitVR();
  46129. }
  46130. }, false);
  46131. },
  46132. update: function (oldData) {
  46133. var data = this.data;
  46134. this.enterVREnabled = data.enterVR;
  46135. },
  46136. remove: function () {
  46137. window.removeEventListener('keyup', this.listener);
  46138. }
  46139. });
  46140. },{"../../core/component":126,"../../utils/":196}],104:[function(_dereq_,module,exports){
  46141. var debug = _dereq_('../../utils/debug');
  46142. var registerComponent = _dereq_('../../core/component').registerComponent;
  46143. var warn = debug('components:pool:warn');
  46144. /**
  46145. * Pool component.
  46146. * A pool of entities that will be reused.
  46147. * It avoids creating and destroying the same kind of entities
  46148. * in dynamic scenes. It will help reduce GC pauses. Useful for example
  46149. * in a game where you want to reuse enemies entities.
  46150. *
  46151. * @member {array} availableEls - Available entities in the pool.
  46152. * @member {array} usedEls - Entities of the pool in use.
  46153. *
  46154. */
  46155. module.exports.Component = registerComponent('pool', {
  46156. schema: {
  46157. mixin: {default: ''},
  46158. size: {default: 0},
  46159. dynamic: {default: false}
  46160. },
  46161. multiple: true,
  46162. initPool: function () {
  46163. var i;
  46164. var mixin = this.data.mixin;
  46165. if (!mixin) { return; }
  46166. this.availableEls = [];
  46167. this.usedEls = [];
  46168. for (i = 0; i < this.data.size; ++i) {
  46169. this.createEntity();
  46170. }
  46171. },
  46172. update: function (oldData) {
  46173. var data = this.data;
  46174. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  46175. this.initPool();
  46176. }
  46177. },
  46178. /**
  46179. * Add a new entity to the list of available entities.
  46180. */
  46181. createEntity: function () {
  46182. var el = document.createElement('a-entity');
  46183. el.play = this.wrapPlay(el.play);
  46184. el.setAttribute('mixin', this.data.mixin);
  46185. el.setAttribute('visible', false);
  46186. this.el.appendChild(el);
  46187. this.availableEls.push(el);
  46188. },
  46189. /**
  46190. * Play wrapper for pooled entities. When pausing and playing
  46191. * a scene we don't want to play the entities that are not in use
  46192. */
  46193. wrapPlay: function (playMethod) {
  46194. var usedEls = this.usedEls;
  46195. return function () {
  46196. if (usedEls.indexOf(this) === -1) { return; }
  46197. playMethod.call(this);
  46198. };
  46199. },
  46200. /**
  46201. * Used to request one of the available entities of the pool
  46202. */
  46203. requestEntity: function () {
  46204. var el;
  46205. if (this.availableEls.length === 0) {
  46206. if (this.data.dynamic === false) {
  46207. warn('Requested entity from empty pool ' + this.name);
  46208. return;
  46209. } else {
  46210. warn('Requested entity from empty pool. This pool is dynamic' +
  46211. 'and will resize automatically. You might want to increase its initial size' + this.name);
  46212. }
  46213. this.createEntity();
  46214. }
  46215. el = this.availableEls.shift();
  46216. this.usedEls.push(el);
  46217. el.setAttribute('visible', true);
  46218. return el;
  46219. },
  46220. /**
  46221. * Used to return a used entity to the pool
  46222. */
  46223. returnEntity: function (el) {
  46224. var index = this.usedEls.indexOf(el);
  46225. if (index === -1) {
  46226. warn('The returned entity was not previously pooled from ' + this.name);
  46227. return;
  46228. }
  46229. this.usedEls.splice(index, 1);
  46230. this.availableEls.push(el);
  46231. el.setAttribute('visible', false);
  46232. el.pause();
  46233. }
  46234. });
  46235. },{"../../core/component":126,"../../utils/debug":192}],105:[function(_dereq_,module,exports){
  46236. /* global ImageData, URL */
  46237. var registerComponent = _dereq_('../../core/component').registerComponent;
  46238. var THREE = _dereq_('../../lib/three');
  46239. var VERTEX_SHADER = [
  46240. 'attribute vec3 position;',
  46241. 'attribute vec2 uv;',
  46242. 'uniform mat4 projectionMatrix;',
  46243. 'uniform mat4 modelViewMatrix;',
  46244. 'varying vec2 vUv;',
  46245. 'void main() {',
  46246. ' vUv = vec2( 1.- uv.x, uv.y );',
  46247. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  46248. '}'
  46249. ].join('\n');
  46250. var FRAGMENT_SHADER = [
  46251. 'precision mediump float;',
  46252. 'uniform samplerCube map;',
  46253. 'varying vec2 vUv;',
  46254. '#define M_PI 3.141592653589793238462643383279',
  46255. 'void main() {',
  46256. ' vec2 uv = vUv;',
  46257. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  46258. ' float latitude = uv.y * M_PI;',
  46259. ' vec3 dir = vec3(',
  46260. ' - sin( longitude ) * sin( latitude ),',
  46261. ' cos( latitude ),',
  46262. ' - cos( longitude ) * sin( latitude )',
  46263. ' );',
  46264. ' normalize( dir );',
  46265. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  46266. '}'
  46267. ].join('\n');
  46268. /**
  46269. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  46270. * It can be configured to either take 360&deg; captures (`equirectangular`)
  46271. * or regular screenshots (`projection`)
  46272. *
  46273. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  46274. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  46275. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  46276. * WebGLRenderTarget with an ortographic camera.
  46277. */
  46278. module.exports.Component = registerComponent('screenshot', {
  46279. schema: {
  46280. width: {default: 4096},
  46281. height: {default: 2048},
  46282. camera: {type: 'selector'}
  46283. },
  46284. init: function () {
  46285. var el = this.el;
  46286. var self = this;
  46287. if (el.renderer) {
  46288. setup();
  46289. } else {
  46290. el.addEventListener('render-target-loaded', setup);
  46291. }
  46292. function setup () {
  46293. var gl = el.renderer.getContext();
  46294. if (!gl) { return; }
  46295. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  46296. self.material = new THREE.RawShaderMaterial({
  46297. uniforms: {map: {type: 't', value: null}},
  46298. vertexShader: VERTEX_SHADER,
  46299. fragmentShader: FRAGMENT_SHADER,
  46300. side: THREE.DoubleSide
  46301. });
  46302. self.quad = new THREE.Mesh(
  46303. new THREE.PlaneBufferGeometry(1, 1),
  46304. self.material
  46305. );
  46306. self.quad.visible = false;
  46307. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  46308. self.canvas = document.createElement('canvas');
  46309. self.ctx = self.canvas.getContext('2d');
  46310. if (el.camera) { el.camera.add(self.quad); }
  46311. self.onKeyDown = self.onKeyDown.bind(self);
  46312. self.onCameraActive = self.onCameraActive.bind(self);
  46313. el.addEventListener('camera-set-active', self.onCameraActive);
  46314. }
  46315. },
  46316. getRenderTarget: function (width, height) {
  46317. return new THREE.WebGLRenderTarget(width, height, {
  46318. minFilter: THREE.LinearFilter,
  46319. magFilter: THREE.LinearFilter,
  46320. wrapS: THREE.ClampToEdgeWrapping,
  46321. wrapT: THREE.ClampToEdgeWrapping,
  46322. format: THREE.RGBAFormat,
  46323. type: THREE.UnsignedByteType
  46324. });
  46325. },
  46326. resize: function (width, height) {
  46327. // Resize quad.
  46328. this.quad.scale.set(width, height, 1);
  46329. // Resize camera.
  46330. this.camera.left = -1 * width / 2;
  46331. this.camera.right = width / 2;
  46332. this.camera.top = height / 2;
  46333. this.camera.bottom = -1 * height / 2;
  46334. this.camera.updateProjectionMatrix();
  46335. // Resize canvas.
  46336. this.canvas.width = width;
  46337. this.canvas.height = height;
  46338. },
  46339. play: function () {
  46340. window.addEventListener('keydown', this.onKeyDown);
  46341. },
  46342. onCameraActive: function (evt) {
  46343. var cameraParent = this.quad.parent;
  46344. if (cameraParent) { cameraParent.remove(this.quad); }
  46345. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  46346. },
  46347. /**
  46348. * <ctrl> + <alt> + s = Regular screenshot.
  46349. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  46350. */
  46351. onKeyDown: function (evt) {
  46352. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  46353. if (!this.data || !shortcutPressed) { return; }
  46354. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  46355. this.capture(projection);
  46356. },
  46357. /**
  46358. * Capture a screenshot of the scene.
  46359. *
  46360. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  46361. */
  46362. setCapture: function (projection) {
  46363. var el = this.el;
  46364. var size;
  46365. var camera;
  46366. var cubeCamera;
  46367. // Configure camera.
  46368. if (projection === 'perspective') {
  46369. // Quad is only used in equirectangular mode. Hide it in this case.
  46370. this.quad.visible = false;
  46371. // Use scene camera.
  46372. camera = (this.data.camera && this.data.camera.components.camera.camera) || el.camera;
  46373. size = {width: this.data.width, height: this.data.height};
  46374. } else {
  46375. // Use ortho camera.
  46376. camera = this.camera;
  46377. // Copy position and rotation of scene camera into the ortho one.
  46378. camera.position.copy(el.camera.getWorldPosition());
  46379. camera.rotation.copy(el.camera.getWorldRotation());
  46380. // Create cube camera and copy position from scene camera.
  46381. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  46382. Math.min(this.cubeMapSize, 2048));
  46383. cubeCamera.position.copy(el.camera.getWorldPosition());
  46384. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  46385. // Render scene with cube camera.
  46386. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  46387. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  46388. size = {width: this.data.width, height: this.data.height};
  46389. // Use quad to project image taken by the cube camera.
  46390. this.quad.visible = true;
  46391. }
  46392. return {
  46393. camera: camera,
  46394. size: size,
  46395. projection: projection
  46396. };
  46397. },
  46398. /**
  46399. * Maintained for backwards compatibility.
  46400. */
  46401. capture: function (projection) {
  46402. var params = this.setCapture(projection);
  46403. this.renderCapture(params.camera, params.size, params.projection);
  46404. // Trigger file download.
  46405. this.saveCapture();
  46406. },
  46407. /**
  46408. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  46409. */
  46410. getCanvas: function (projection) {
  46411. var params = this.setCapture(projection);
  46412. this.renderCapture(params.camera, params.size, params.projection);
  46413. return this.canvas;
  46414. },
  46415. renderCapture: function (camera, size, projection) {
  46416. var autoClear = this.el.renderer.autoClear;
  46417. var el = this.el;
  46418. var imageData;
  46419. var output;
  46420. var pixels;
  46421. var renderer = this.el.renderer;
  46422. // Create rendering target and buffer to store the read pixels.
  46423. output = this.getRenderTarget(size.width, size.height);
  46424. pixels = new Uint8Array(4 * size.width * size.height);
  46425. // Resize quad, camera, and canvas.
  46426. this.resize(size.width, size.height);
  46427. // Render scene to render target.
  46428. renderer.autoClear = true;
  46429. renderer.render(el.object3D, camera, output, true);
  46430. renderer.autoClear = autoClear;
  46431. // Read image pizels back.
  46432. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  46433. if (projection === 'perspective') {
  46434. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  46435. }
  46436. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  46437. // Hide quad after projecting the image.
  46438. this.quad.visible = false;
  46439. // Copy pixels into canvas.
  46440. this.ctx.putImageData(imageData, 0, 0);
  46441. },
  46442. flipPixelsVertically: function (pixels, width, height) {
  46443. var flippedPixels = pixels.slice(0);
  46444. for (var x = 0; x < width; ++x) {
  46445. for (var y = 0; y < height; ++y) {
  46446. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  46447. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  46448. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  46449. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  46450. }
  46451. }
  46452. return flippedPixels;
  46453. },
  46454. /**
  46455. * Download capture to file.
  46456. */
  46457. saveCapture: function () {
  46458. this.canvas.toBlob(function (blob) {
  46459. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  46460. var linkEl = document.createElement('a');
  46461. var url = URL.createObjectURL(blob);
  46462. linkEl.href = url;
  46463. linkEl.setAttribute('download', fileName);
  46464. linkEl.innerHTML = 'downloading...';
  46465. linkEl.style.display = 'none';
  46466. document.body.appendChild(linkEl);
  46467. setTimeout(function () {
  46468. linkEl.click();
  46469. document.body.removeChild(linkEl);
  46470. }, 1);
  46471. }, 'image/png');
  46472. }
  46473. });
  46474. },{"../../core/component":126,"../../lib/three":174}],106:[function(_dereq_,module,exports){
  46475. var registerComponent = _dereq_('../../core/component').registerComponent;
  46476. var RStats = _dereq_('../../../vendor/rStats');
  46477. var utils = _dereq_('../../utils');
  46478. _dereq_('../../../vendor/rStats.extras');
  46479. _dereq_('../../lib/rStatsAframe');
  46480. var AFrameStats = window.aframeStats;
  46481. var bind = utils.bind;
  46482. var HIDDEN_CLASS = 'a-hidden';
  46483. var ThreeStats = window.threeStats;
  46484. /**
  46485. * Stats appended to document.body by RStats.
  46486. */
  46487. module.exports.Component = registerComponent('stats', {
  46488. schema: {default: true},
  46489. init: function () {
  46490. var scene = this.el;
  46491. if (utils.getUrlParameter('stats') === 'false') { return; }
  46492. this.stats = createStats(scene);
  46493. this.statsEl = document.querySelector('.rs-base');
  46494. this.hideBound = bind(this.hide, this);
  46495. this.showBound = bind(this.show, this);
  46496. scene.addEventListener('enter-vr', this.hideBound);
  46497. scene.addEventListener('exit-vr', this.showBound);
  46498. },
  46499. update: function () {
  46500. if (!this.stats) { return; }
  46501. return (!this.data) ? this.hide() : this.show();
  46502. },
  46503. remove: function () {
  46504. this.el.removeEventListener('enter-vr', this.hideBound);
  46505. this.el.removeEventListener('exit-vr', this.showBound);
  46506. if (!this.statsEl) { return; } // Scene detached.
  46507. this.statsEl.parentNode.removeChild(this.statsEl);
  46508. },
  46509. tick: function () {
  46510. var stats = this.stats;
  46511. if (!stats) { return; }
  46512. stats('rAF').tick();
  46513. stats('FPS').frame();
  46514. stats().update();
  46515. },
  46516. hide: function () {
  46517. this.statsEl.classList.add(HIDDEN_CLASS);
  46518. },
  46519. show: function () {
  46520. this.statsEl.classList.remove(HIDDEN_CLASS);
  46521. }
  46522. });
  46523. function createStats (scene) {
  46524. var threeStats = new ThreeStats(scene.renderer);
  46525. var aframeStats = new AFrameStats(scene);
  46526. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46527. return new RStats({
  46528. css: [], // Our stylesheet is injected from `src/index.js`.
  46529. values: {
  46530. fps: {caption: 'fps', below: 30}
  46531. },
  46532. groups: [
  46533. {caption: 'Framerate', values: ['fps', 'raf']}
  46534. ],
  46535. plugins: plugins
  46536. });
  46537. }
  46538. },{"../../../vendor/rStats":203,"../../../vendor/rStats.extras":202,"../../core/component":126,"../../lib/rStatsAframe":173,"../../utils":196}],107:[function(_dereq_,module,exports){
  46539. var registerComponent = _dereq_('../../core/component').registerComponent;
  46540. var constants = _dereq_('../../constants/');
  46541. var utils = _dereq_('../../utils/');
  46542. var bind = utils.bind;
  46543. var ENTER_VR_CLASS = 'a-enter-vr';
  46544. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46545. var HIDDEN_CLASS = 'a-hidden';
  46546. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46547. /**
  46548. * UI for entering VR mode.
  46549. */
  46550. module.exports.Component = registerComponent('vr-mode-ui', {
  46551. dependencies: ['canvas'],
  46552. schema: {
  46553. enabled: {default: true}
  46554. },
  46555. init: function () {
  46556. var self = this;
  46557. var sceneEl = this.el;
  46558. if (utils.getUrlParameter('ui') === 'false') { return; }
  46559. this.insideLoader = false;
  46560. this.enterVREl = null;
  46561. this.orientationModalEl = null;
  46562. this.bindMethods();
  46563. // Hide/show VR UI when entering/exiting VR mode.
  46564. sceneEl.addEventListener('enter-vr', this.updateEnterVRInterface);
  46565. sceneEl.addEventListener('exit-vr', this.updateEnterVRInterface);
  46566. window.addEventListener('message', function (event) {
  46567. if (event.data.type === 'loaderReady') {
  46568. self.insideLoader = true;
  46569. self.remove();
  46570. }
  46571. });
  46572. // Modal that tells the user to change orientation if in portrait.
  46573. window.addEventListener('orientationchange', this.toggleOrientationModalIfNeeded);
  46574. },
  46575. bindMethods: function () {
  46576. this.onEnterVRButtonClick = bind(this.onEnterVRButtonClick, this);
  46577. this.onModalClick = bind(this.onModalClick, this);
  46578. this.toggleOrientationModalIfNeeded = bind(this.toggleOrientationModalIfNeeded, this);
  46579. this.updateEnterVRInterface = bind(this.updateEnterVRInterface, this);
  46580. },
  46581. /**
  46582. * Exit VR when modal clicked.
  46583. */
  46584. onModalClick: function () {
  46585. this.el.exitVR();
  46586. },
  46587. /**
  46588. * Enter VR when modal clicked.
  46589. */
  46590. onEnterVRButtonClick: function () {
  46591. this.el.enterVR();
  46592. },
  46593. update: function () {
  46594. var sceneEl = this.el;
  46595. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46596. return this.remove();
  46597. }
  46598. if (this.enterVREl || this.orientationModalEl) { return; }
  46599. // Add UI if enabled and not already present.
  46600. this.enterVREl = createEnterVRButton(this.onEnterVRButtonClick);
  46601. sceneEl.appendChild(this.enterVREl);
  46602. this.orientationModalEl = createOrientationModal(this.onModalClick);
  46603. sceneEl.appendChild(this.orientationModalEl);
  46604. this.updateEnterVRInterface();
  46605. },
  46606. remove: function () {
  46607. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46608. if (uiElement) {
  46609. uiElement.parentNode.removeChild(uiElement);
  46610. }
  46611. });
  46612. },
  46613. updateEnterVRInterface: function () {
  46614. this.toggleEnterVRButtonIfNeeded();
  46615. this.toggleOrientationModalIfNeeded();
  46616. },
  46617. toggleEnterVRButtonIfNeeded: function () {
  46618. var sceneEl = this.el;
  46619. if (!this.enterVREl) { return; }
  46620. if (sceneEl.is('vr-mode')) {
  46621. this.enterVREl.classList.add(HIDDEN_CLASS);
  46622. } else {
  46623. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46624. }
  46625. },
  46626. toggleOrientationModalIfNeeded: function () {
  46627. var sceneEl = this.el;
  46628. var orientationModalEl = this.orientationModalEl;
  46629. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46630. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46631. // Show if in VR mode on portrait.
  46632. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46633. } else {
  46634. orientationModalEl.classList.add(HIDDEN_CLASS);
  46635. }
  46636. }
  46637. });
  46638. /**
  46639. * Create a button that when clicked will enter into stereo-rendering mode for VR.
  46640. *
  46641. * Structure: <div><button></div>
  46642. *
  46643. * @param {function} onClick - click event handler
  46644. * @returns {Element} Wrapper <div>.
  46645. */
  46646. function createEnterVRButton (onClick) {
  46647. var vrButton;
  46648. var wrapper;
  46649. // Create elements.
  46650. wrapper = document.createElement('div');
  46651. wrapper.classList.add(ENTER_VR_CLASS);
  46652. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46653. vrButton = document.createElement('button');
  46654. vrButton.className = ENTER_VR_BTN_CLASS;
  46655. 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.');
  46656. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46657. // Insert elements.
  46658. wrapper.appendChild(vrButton);
  46659. vrButton.addEventListener('click', function (evt) {
  46660. onClick();
  46661. });
  46662. return wrapper;
  46663. }
  46664. /**
  46665. * Creates a modal dialog to request the user to switch to landscape orientation.
  46666. *
  46667. * @param {function} onClick - click event handler
  46668. * @returns {Element} Wrapper <div>.
  46669. */
  46670. function createOrientationModal (onClick) {
  46671. var modal = document.createElement('div');
  46672. modal.className = ORIENTATION_MODAL_CLASS;
  46673. modal.classList.add(HIDDEN_CLASS);
  46674. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46675. var exit = document.createElement('button');
  46676. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46677. exit.innerHTML = 'Exit VR';
  46678. // Exit VR on close.
  46679. exit.addEventListener('click', onClick);
  46680. modal.appendChild(exit);
  46681. return modal;
  46682. }
  46683. },{"../../constants/":117,"../../core/component":126,"../../utils/":196}],108:[function(_dereq_,module,exports){
  46684. var component = _dereq_('../core/component');
  46685. var THREE = _dereq_('../lib/three');
  46686. var bind = _dereq_('../utils/bind');
  46687. var registerComponent = component.registerComponent;
  46688. /**
  46689. * Shadow component.
  46690. *
  46691. * When applied to an entity, that entity's geometry and any descendants will cast or receive
  46692. * shadows as specified by the `cast` and `receive` properties.
  46693. */
  46694. module.exports.Component = registerComponent('shadow', {
  46695. schema: {
  46696. cast: {default: true},
  46697. receive: {default: true}
  46698. },
  46699. init: function () {
  46700. this.onMeshChanged = bind(this.update, this);
  46701. this.el.addEventListener('object3dset', this.onMeshChanged);
  46702. this.system.setShadowMapEnabled(true);
  46703. },
  46704. update: function () {
  46705. var data = this.data;
  46706. this.updateDescendants(data.cast, data.receive);
  46707. },
  46708. remove: function () {
  46709. var el = this.el;
  46710. el.removeEventListener('object3dset', this.onMeshChanged);
  46711. this.updateDescendants(false, false);
  46712. },
  46713. updateDescendants: function (cast, receive) {
  46714. var sceneEl = this.el.sceneEl;
  46715. this.el.object3D.traverse(function (node) {
  46716. if (!(node instanceof THREE.Mesh)) { return; }
  46717. node.castShadow = cast;
  46718. node.receiveShadow = receive;
  46719. // If scene has already rendered, materials must be updated.
  46720. if (sceneEl.hasLoaded && node.material) {
  46721. var materials = Array.isArray(node.material) ? node.material : [node.material];
  46722. for (var i = 0; i < materials.length; i++) {
  46723. materials[i].needsUpdate = true;
  46724. }
  46725. }
  46726. });
  46727. }
  46728. });
  46729. },{"../core/component":126,"../lib/three":174,"../utils/bind":190}],109:[function(_dereq_,module,exports){
  46730. var registerComponent = _dereq_('../core/component').registerComponent;
  46731. var debug = _dereq_('../utils/debug');
  46732. var bind = _dereq_('../utils/bind');
  46733. var THREE = _dereq_('../lib/three');
  46734. var warn = debug('components:sound:warn');
  46735. /**
  46736. * Sound component.
  46737. */
  46738. module.exports.Component = registerComponent('sound', {
  46739. schema: {
  46740. autoplay: {default: false},
  46741. distanceModel: {default: 'inverse',
  46742. oneOf: ['linear', 'inverse', 'exponential']},
  46743. loop: {default: false},
  46744. maxDistance: {default: 10000},
  46745. on: {default: ''},
  46746. poolSize: {default: 1},
  46747. positional: {default: true},
  46748. refDistance: {default: 1},
  46749. rolloffFactor: {default: 1},
  46750. src: {type: 'audio'},
  46751. volume: {default: 1}
  46752. },
  46753. multiple: true,
  46754. init: function () {
  46755. this.listener = null;
  46756. this.audioLoader = new THREE.AudioLoader();
  46757. this.pool = new THREE.Group();
  46758. this.loaded = false;
  46759. this.mustPlay = false;
  46760. this.playSound = bind(this.playSound, this);
  46761. },
  46762. update: function (oldData) {
  46763. var data = this.data;
  46764. var srcChanged = data.src !== oldData.src;
  46765. // Create new sound if not yet created or changing `src`.
  46766. if (srcChanged) {
  46767. if (!data.src) {
  46768. warn('Audio source was not specified with `src`');
  46769. return;
  46770. }
  46771. this.setupSound();
  46772. }
  46773. this.pool.children.forEach(function (sound) {
  46774. if (data.positional) {
  46775. sound.setDistanceModel(data.distanceModel);
  46776. sound.setMaxDistance(data.maxDistance);
  46777. sound.setRefDistance(data.refDistance);
  46778. sound.setRolloffFactor(data.rolloffFactor);
  46779. }
  46780. sound.setLoop(data.loop);
  46781. sound.setVolume(data.volume);
  46782. sound.isPaused = false;
  46783. });
  46784. if (data.on !== oldData.on) {
  46785. this.updateEventListener(oldData.on);
  46786. }
  46787. // All sound values set. Load in `src`.
  46788. if (srcChanged) {
  46789. var self = this;
  46790. this.loaded = false;
  46791. this.audioLoader.load(data.src, function (buffer) {
  46792. self.pool.children.forEach(function (sound) {
  46793. sound.setBuffer(buffer);
  46794. });
  46795. self.loaded = true;
  46796. // Remove this key from cache, otherwise we can't play it again
  46797. THREE.Cache.remove(data.src);
  46798. if (self.data.autoplay || self.mustPlay) { self.playSound(); }
  46799. self.el.emit('sound-loaded');
  46800. });
  46801. }
  46802. },
  46803. pause: function () {
  46804. this.stopSound();
  46805. this.removeEventListener();
  46806. },
  46807. play: function () {
  46808. if (this.data.autoplay) { this.playSound(); }
  46809. this.updateEventListener();
  46810. },
  46811. remove: function () {
  46812. this.removeEventListener();
  46813. this.el.removeObject3D(this.attrName);
  46814. try {
  46815. this.pool.children.forEach(function (sound) {
  46816. sound.disconnect();
  46817. });
  46818. } catch (e) {
  46819. // disconnect() will throw if it was never connected initially.
  46820. warn('Audio source not properly disconnected');
  46821. }
  46822. },
  46823. /**
  46824. * Update listener attached to the user defined on event.
  46825. */
  46826. updateEventListener: function (oldEvt) {
  46827. var el = this.el;
  46828. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46829. el.addEventListener(this.data.on, this.playSound);
  46830. },
  46831. removeEventListener: function () {
  46832. this.el.removeEventListener(this.data.on, this.playSound);
  46833. },
  46834. /**
  46835. * Removes current sound object, creates new sound object, adds to entity.
  46836. *
  46837. * @returns {object} sound
  46838. */
  46839. setupSound: function () {
  46840. var el = this.el;
  46841. var sceneEl = el.sceneEl;
  46842. if (this.pool.children.length > 0) {
  46843. this.stopSound();
  46844. el.removeObject3D('sound');
  46845. }
  46846. // Only want one AudioListener. Cache it on the scene.
  46847. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46848. sceneEl.audioListener = listener;
  46849. if (sceneEl.camera) {
  46850. sceneEl.camera.add(listener);
  46851. }
  46852. // Wait for camera if necessary.
  46853. sceneEl.addEventListener('camera-set-active', function (evt) {
  46854. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46855. });
  46856. // Create [poolSize] audio instances and attach them to pool
  46857. this.pool = new THREE.Group();
  46858. for (var i = 0; i < this.data.poolSize; i++) {
  46859. var sound = this.data.positional ? new THREE.PositionalAudio(listener) : new THREE.Audio(listener);
  46860. this.pool.add(sound);
  46861. }
  46862. el.setObject3D(this.attrName, this.pool);
  46863. this.pool.children.forEach(function (sound) {
  46864. sound.onEnded = function () {
  46865. sound.isPlaying = false;
  46866. el.emit('sound-ended', {index: i});
  46867. };
  46868. });
  46869. },
  46870. /**
  46871. * Pause all the sounds in the pool.
  46872. */
  46873. pauseSound: function () {
  46874. this.isPlaying = false;
  46875. this.pool.children.forEach(function (sound) {
  46876. if (!sound.source || !sound.source.buffer || !sound.isPlaying || sound.isPaused) { return; }
  46877. sound.isPaused = true;
  46878. sound.pause();
  46879. });
  46880. },
  46881. /**
  46882. * Look for an unused sound in the pool and play it if found.
  46883. */
  46884. playSound: function () {
  46885. if (!this.loaded) {
  46886. warn('Sound not loaded yet. It will be played once it finished loading');
  46887. this.mustPlay = true;
  46888. return;
  46889. }
  46890. var found = false;
  46891. this.isPlaying = true;
  46892. this.pool.children.forEach(function (sound) {
  46893. if (!sound.isPlaying && sound.buffer && !found) {
  46894. sound.play();
  46895. sound.isPaused = false;
  46896. found = true;
  46897. return;
  46898. }
  46899. });
  46900. if (!found) {
  46901. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46902. 'consider increasing the size of pool with the `poolSize` attribute.', this.el);
  46903. return;
  46904. }
  46905. this.mustPlay = false;
  46906. },
  46907. /**
  46908. * Stop all the sounds in the pool.
  46909. */
  46910. stopSound: function () {
  46911. this.isPlaying = false;
  46912. this.pool.children.forEach(function (sound) {
  46913. if (!sound.source || !sound.source.buffer) { return; }
  46914. sound.stop();
  46915. });
  46916. }
  46917. });
  46918. },{"../core/component":126,"../lib/three":174,"../utils/bind":190,"../utils/debug":192}],110:[function(_dereq_,module,exports){
  46919. var createTextGeometry = _dereq_('three-bmfont-text');
  46920. var loadBMFont = _dereq_('load-bmfont');
  46921. var registerComponent = _dereq_('../core/component').registerComponent;
  46922. var coreShader = _dereq_('../core/shader');
  46923. var THREE = _dereq_('../lib/three');
  46924. var utils = _dereq_('../utils/');
  46925. var error = utils.debug('components:text:error');
  46926. var shaders = coreShader.shaders;
  46927. var warn = utils.debug('components:text:warn');
  46928. // 1 to match other A-Frame default widths.
  46929. var DEFAULT_WIDTH = 1;
  46930. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46931. var MAX_ANISOTROPY = 16;
  46932. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46933. var FONTS = {
  46934. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46935. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46936. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46937. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46938. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46939. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46940. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46941. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46942. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46943. };
  46944. var MSDF_FONTS = ['roboto'];
  46945. var DEFAULT_FONT = 'roboto';
  46946. module.exports.FONTS = FONTS;
  46947. var cache = new PromiseCache();
  46948. var fontWidthFactors = {};
  46949. var textures = {};
  46950. /**
  46951. * SDF-based text component.
  46952. * Based on https://github.com/Jam3/three-bmfont-text.
  46953. *
  46954. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46955. * original `sdf` shader.
  46956. */
  46957. module.exports.Component = registerComponent('text', {
  46958. multiple: true,
  46959. schema: {
  46960. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46961. alphaTest: {default: 0.5},
  46962. // `anchor` defaults to center to match geometries.
  46963. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46964. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46965. color: {type: 'color', default: '#FFF'},
  46966. font: {type: 'string', default: DEFAULT_FONT},
  46967. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46968. fontImage: {type: 'string'},
  46969. // `height` has no default, will be populated at layout.
  46970. height: {type: 'number'},
  46971. letterSpacing: {type: 'number', default: 0},
  46972. // `lineHeight` defaults to font's `lineHeight` value.
  46973. lineHeight: {type: 'number'},
  46974. opacity: {type: 'number', default: 1.0},
  46975. shader: {default: 'sdf', oneOf: shaders},
  46976. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46977. tabSize: {default: 4},
  46978. transparent: {default: true},
  46979. value: {type: 'string'},
  46980. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46981. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46982. width: {type: 'number'},
  46983. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46984. wrapCount: {type: 'number', default: 40},
  46985. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46986. wrapPixels: {type: 'number'},
  46987. // `xOffset` to add padding.
  46988. xOffset: {type: 'number', default: 0},
  46989. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46990. yOffset: {type: 'number', default: 0},
  46991. // `zOffset` will provide a small z offset to avoid z-fighting.
  46992. zOffset: {type: 'number', default: 0.001}
  46993. },
  46994. init: function () {
  46995. this.geometry = createTextGeometry();
  46996. this.createOrUpdateMaterial();
  46997. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46998. this.el.setObject3D(this.attrName, this.mesh);
  46999. },
  47000. update: function (oldData) {
  47001. var data = coerceData(this.data);
  47002. var font = this.currentFont;
  47003. var fontImage = this.getFontImageSrc();
  47004. if (textures[fontImage]) {
  47005. this.texture = textures[fontImage];
  47006. } else {
  47007. // Create texture per font.
  47008. this.texture = textures[fontImage] = new THREE.Texture();
  47009. this.texture.anisotropy = MAX_ANISOTROPY;
  47010. }
  47011. // Update material.
  47012. this.createOrUpdateMaterial();
  47013. // New font. `updateFont` will later change data and layout.
  47014. if (oldData.font !== data.font) {
  47015. this.updateFont();
  47016. return;
  47017. }
  47018. // Update geometry and layout.
  47019. if (font) {
  47020. this.updateGeometry(this.geometry, data, font);
  47021. this.updateLayout(data);
  47022. }
  47023. },
  47024. /**
  47025. * Clean up geometry, material, texture, mesh, objects.
  47026. */
  47027. remove: function () {
  47028. this.geometry.dispose();
  47029. this.geometry = null;
  47030. this.el.removeObject3D(this.attrName);
  47031. this.material.dispose();
  47032. this.material = null;
  47033. this.texture.dispose();
  47034. this.texture = null;
  47035. if (this.shaderObject) {
  47036. delete this.shaderObject;
  47037. }
  47038. },
  47039. /**
  47040. * Update the shader of the material.
  47041. */
  47042. createOrUpdateMaterial: function () {
  47043. var data = this.data;
  47044. var hasChangedShader;
  47045. var material = this.material;
  47046. var NewShader;
  47047. var shaderData;
  47048. var shaderName;
  47049. // Infer shader if using a stock font (or from `-msdf` filename convention).
  47050. shaderName = data.shader;
  47051. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  47052. shaderName = 'msdf';
  47053. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  47054. shaderName = 'sdf';
  47055. }
  47056. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  47057. shaderData = {
  47058. alphaTest: data.alphaTest,
  47059. color: data.color,
  47060. map: this.texture,
  47061. opacity: data.opacity,
  47062. side: parseSide(data.side),
  47063. transparent: data.transparent
  47064. };
  47065. // Shader has not changed, do an update.
  47066. if (!hasChangedShader) {
  47067. // Update shader material.
  47068. this.shaderObject.update(shaderData);
  47069. // Apparently, was not set on `init` nor `update`.
  47070. material.transparent = shaderData.transparent;
  47071. updateBaseMaterial(material, shaderData);
  47072. return;
  47073. }
  47074. // Shader has changed. Create a shader material.
  47075. NewShader = createShader(this.el, shaderName, shaderData);
  47076. this.material = NewShader.material;
  47077. this.shaderObject = NewShader.shader;
  47078. // Set new shader material.
  47079. updateBaseMaterial(this.material, shaderData);
  47080. if (this.mesh) { this.mesh.material = this.material; }
  47081. },
  47082. /**
  47083. * Load font for geometry, load font image for material, and apply.
  47084. */
  47085. updateFont: function () {
  47086. var data = this.data;
  47087. var el = this.el;
  47088. var fontSrc;
  47089. var geometry = this.geometry;
  47090. var self = this;
  47091. if (!data.font) { warn('No font specified. Using the default font.'); }
  47092. // Make invisible during font swap.
  47093. this.mesh.visible = false;
  47094. // Look up font URL to use, and perform cached load.
  47095. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  47096. cache.get(fontSrc, function doLoadFont () {
  47097. return loadFont(fontSrc, data.yOffset);
  47098. }).then(function setFont (font) {
  47099. var coercedData;
  47100. var fontImgSrc;
  47101. if (font.pages.length !== 1) {
  47102. throw new Error('Currently only single-page bitmap fonts are supported.');
  47103. }
  47104. if (!fontWidthFactors[fontSrc]) {
  47105. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  47106. }
  47107. // Update geometry given font metrics.
  47108. coercedData = coerceData(data);
  47109. self.updateGeometry(geometry, self.data, font);
  47110. // Set font and update layout.
  47111. self.currentFont = font;
  47112. self.updateLayout(coercedData);
  47113. // Look up font image URL to use, and perform cached load.
  47114. fontImgSrc = self.getFontImageSrc();
  47115. cache.get(fontImgSrc, function () {
  47116. return loadTexture(fontImgSrc);
  47117. }).then(function (image) {
  47118. // Make mesh visible and apply font image as texture.
  47119. var texture = self.texture;
  47120. texture.image = image;
  47121. texture.needsUpdate = true;
  47122. textures[fontImgSrc] = texture;
  47123. self.texture = texture;
  47124. self.mesh.visible = true;
  47125. el.emit('textfontset', {font: data.font, fontObj: font});
  47126. }).catch(function (err) {
  47127. error(err);
  47128. throw err;
  47129. });
  47130. }).catch(function (err) {
  47131. error(err);
  47132. throw err;
  47133. });
  47134. },
  47135. getFontImageSrc: function () {
  47136. var fontSrc = this.lookupFont(this.data.font || DEFAULT_FONT) || this.data.font;
  47137. return this.data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png');
  47138. },
  47139. /**
  47140. * Update layout with anchor, alignment, baseline, and considering any meshes.
  47141. */
  47142. updateLayout: function (data) {
  47143. var anchor;
  47144. var baseline;
  47145. var el = this.el;
  47146. var geometry = this.geometry;
  47147. var geometryComponent = el.getAttribute('geometry');
  47148. var height;
  47149. var layout = geometry.layout;
  47150. var mesh = this.mesh;
  47151. var textRenderWidth;
  47152. var textScale;
  47153. var width;
  47154. var x;
  47155. var y;
  47156. // Determine width to use (defined width, geometry's width, or default width).
  47157. geometryComponent = el.getAttribute('geometry');
  47158. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  47159. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  47160. // Note that experimental factor will never be correct for variable width fonts.
  47161. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  47162. this.currentFont.widthFactor);
  47163. textScale = width / textRenderWidth;
  47164. // Determine height to use.
  47165. height = textScale * (layout.height + layout.descender);
  47166. // Update geometry dimensions to match text layout if width and height are set to 0.
  47167. // For example, scales a plane to fit text.
  47168. if (geometryComponent) {
  47169. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  47170. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  47171. }
  47172. // Calculate X position to anchor text left, center, or right.
  47173. anchor = data.anchor === 'align' ? data.align : data.anchor;
  47174. if (anchor === 'left') {
  47175. x = 0;
  47176. } else if (anchor === 'right') {
  47177. x = -1 * layout.width;
  47178. } else if (anchor === 'center') {
  47179. x = -1 * layout.width / 2;
  47180. } else {
  47181. throw new TypeError('Invalid text.anchor property value', anchor);
  47182. }
  47183. // Calculate Y position to anchor text top, center, or bottom.
  47184. baseline = data.baseline;
  47185. if (baseline === 'bottom') {
  47186. y = 0;
  47187. } else if (baseline === 'top') {
  47188. y = -1 * layout.height + layout.ascender;
  47189. } else if (baseline === 'center') {
  47190. y = -1 * layout.height / 2;
  47191. } else {
  47192. throw new TypeError('Invalid text.baseline property value', baseline);
  47193. }
  47194. // Position and scale mesh to apply layout.
  47195. mesh.position.x = x * textScale + data.xOffset;
  47196. mesh.position.y = y * textScale;
  47197. // Place text slightly in front to avoid Z-fighting.
  47198. mesh.position.z = data.zOffset;
  47199. mesh.scale.set(textScale, -1 * textScale, textScale);
  47200. this.geometry.computeBoundingSphere();
  47201. },
  47202. /**
  47203. * Grab font from the constant.
  47204. * Set as a method for test stubbing purposes.
  47205. */
  47206. lookupFont: function (key) {
  47207. return FONTS[key];
  47208. },
  47209. /**
  47210. * Update the text geometry using `three-bmfont-text.update`.
  47211. */
  47212. updateGeometry: function (geometry, data, font) {
  47213. geometry.update(utils.extend({}, data, {
  47214. font: font,
  47215. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  47216. text: data.value.toString().replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  47217. lineHeight: data.lineHeight || font.common.lineHeight
  47218. }));
  47219. }
  47220. });
  47221. /**
  47222. * Due to using negative scale, we return the opposite side specified.
  47223. * https://github.com/mrdoob/three.js/pull/12787/
  47224. */
  47225. function parseSide (side) {
  47226. switch (side) {
  47227. case 'back': {
  47228. return THREE.FrontSide;
  47229. }
  47230. case 'double': {
  47231. return THREE.DoubleSide;
  47232. }
  47233. default: {
  47234. return THREE.BackSide;
  47235. }
  47236. }
  47237. }
  47238. /**
  47239. * Coerce some data to numbers.
  47240. * as they will be passed directly into text creation and update
  47241. */
  47242. function coerceData (data) {
  47243. data = utils.clone(data);
  47244. if (data.lineHeight !== undefined) {
  47245. data.lineHeight = parseFloat(data.lineHeight);
  47246. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  47247. }
  47248. if (data.width !== undefined) {
  47249. data.width = parseFloat(data.width);
  47250. if (!isFinite(data.width)) { data.width = undefined; }
  47251. }
  47252. return data;
  47253. }
  47254. /**
  47255. * @returns {Promise}
  47256. */
  47257. function loadFont (src, yOffset) {
  47258. return new Promise(function (resolve, reject) {
  47259. loadBMFont(src, function (err, font) {
  47260. if (err) {
  47261. error('Error loading font', src);
  47262. reject(err);
  47263. return;
  47264. }
  47265. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  47266. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  47267. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  47268. resolve(font);
  47269. });
  47270. });
  47271. }
  47272. /**
  47273. * @returns {Promise}
  47274. */
  47275. function loadTexture (src) {
  47276. return new Promise(function (resolve, reject) {
  47277. new THREE.ImageLoader().load(src, function (image) {
  47278. resolve(image);
  47279. }, undefined, function () {
  47280. error('Error loading font image', src);
  47281. reject(null);
  47282. });
  47283. });
  47284. }
  47285. function createShader (el, shaderName, data) {
  47286. var shader;
  47287. var shaderObject;
  47288. // Set up Shader.
  47289. shaderObject = new shaders[shaderName].Shader();
  47290. shaderObject.el = el;
  47291. shaderObject.init(data);
  47292. shaderObject.update(data);
  47293. // Get material.
  47294. shader = shaderObject.material;
  47295. // Apparently, was not set on `init` nor `update`.
  47296. shader.transparent = data.transparent;
  47297. return {
  47298. material: shader,
  47299. shader: shaderObject
  47300. };
  47301. }
  47302. /**
  47303. * @todo Add more supported material properties (e.g., `visible`).
  47304. */
  47305. function updateBaseMaterial (material, data) {
  47306. material.side = data.side;
  47307. }
  47308. /**
  47309. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  47310. * Note that experimental factor will never be correct for variable width fonts.
  47311. */
  47312. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  47313. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  47314. }
  47315. /**
  47316. * Compute default font width factor to use.
  47317. */
  47318. function computeFontWidthFactor (font) {
  47319. var sum = 0;
  47320. var digitsum = 0;
  47321. var digits = 0;
  47322. font.chars.map(function (ch) {
  47323. sum += ch.xadvance;
  47324. if (ch.id >= 48 && ch.id <= 57) {
  47325. digits++;
  47326. digitsum += ch.xadvance;
  47327. }
  47328. });
  47329. return digits ? digitsum / digits : sum / font.chars.length;
  47330. }
  47331. /**
  47332. * Get or create a promise given a key and promise generator.
  47333. * @todo Move to a utility and use in other parts of A-Frame.
  47334. */
  47335. function PromiseCache () {
  47336. var cache = this.cache = {};
  47337. this.get = function (key, promiseGenerator) {
  47338. if (key in cache) {
  47339. return cache[key];
  47340. }
  47341. cache[key] = promiseGenerator();
  47342. return cache[key];
  47343. };
  47344. }
  47345. },{"../core/component":126,"../core/shader":135,"../lib/three":174,"../utils/":196,"load-bmfont":24,"three-bmfont-text":37}],111:[function(_dereq_,module,exports){
  47346. var registerComponent = _dereq_('../core/component').registerComponent;
  47347. var controllerUtils = _dereq_('../utils/tracked-controls');
  47348. var DEFAULT_CAMERA_HEIGHT = _dereq_('../constants').DEFAULT_CAMERA_HEIGHT;
  47349. var THREE = _dereq_('../lib/three');
  47350. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  47351. // Vector from eyes to elbow (divided by user height).
  47352. var EYES_TO_ELBOW = {x: 0.175, y: -0.3, z: -0.03};
  47353. // Vector from eyes to elbow (divided by user height).
  47354. var FOREARM = {x: 0, y: 0, z: -0.175};
  47355. /**
  47356. * Tracked controls component.
  47357. * Wrap the gamepad API for pose and button states.
  47358. * Select the appropriate controller and apply pose to the entity.
  47359. * Observe button states and emit appropriate events.
  47360. *
  47361. * @property {number} controller - Index of controller in array returned by Gamepad API. Only used if hand property is not set.
  47362. * @property {string} id - Selected controller among those returned by Gamepad API.
  47363. * @property {number} hand - If multiple controllers found with id, choose the one with the given value for hand. If set, we ignore 'controller' property
  47364. */
  47365. module.exports.Component = registerComponent('tracked-controls', {
  47366. schema: {
  47367. controller: {default: 0},
  47368. id: {type: 'string', default: ''},
  47369. hand: {type: 'string', default: ''},
  47370. idPrefix: {type: 'string', default: ''},
  47371. rotationOffset: {default: 0},
  47372. // Arm model parameters when not 6DoF.
  47373. armModel: {default: true},
  47374. headElement: {type: 'selector'}
  47375. },
  47376. init: function () {
  47377. this.axis = [0, 0, 0];
  47378. this.buttonStates = {};
  47379. this.changedAxes = [];
  47380. this.targetControllerNumber = this.data.controller;
  47381. this.axisMoveEventDetail = {axis: this.axis, changed: this.changedAxes};
  47382. this.deltaControllerPosition = new THREE.Vector3();
  47383. this.controllerQuaternion = new THREE.Quaternion();
  47384. this.controllerEuler = new THREE.Euler();
  47385. this.updateGamepad();
  47386. // The matrix is manipulate directly in the updatePose method.
  47387. this.el.object3D.matrixAutoUpdate = false;
  47388. },
  47389. tick: function (time, delta) {
  47390. var mesh = this.el.getObject3D('mesh');
  47391. // Update mesh animations.
  47392. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  47393. this.updateGamepad();
  47394. this.updatePose();
  47395. this.updateButtons();
  47396. },
  47397. /**
  47398. * Return default user height to use for non-6DOF arm model.
  47399. */
  47400. defaultUserHeight: function () {
  47401. return DEFAULT_CAMERA_HEIGHT;
  47402. },
  47403. /**
  47404. * Return head element to use for non-6DOF arm model.
  47405. */
  47406. getHeadElement: function () {
  47407. return this.data.headElement || this.el.sceneEl.camera.el;
  47408. },
  47409. /**
  47410. * Handle update controller match criteria (such as `id`, `idPrefix`, `hand`, `controller`)
  47411. */
  47412. updateGamepad: function () {
  47413. var data = this.data;
  47414. var controller = controllerUtils.findMatchingController(
  47415. this.system.controllers,
  47416. data.id,
  47417. data.idPrefix,
  47418. data.hand,
  47419. data.controller
  47420. );
  47421. this.controller = controller;
  47422. },
  47423. applyArmModel: function (controllerPosition) {
  47424. // Use controllerPosition and deltaControllerPosition to avoid creating variables.
  47425. var controller = this.controller;
  47426. var controllerEuler = this.controllerEuler;
  47427. var controllerQuaternion = this.controllerQuaternion;
  47428. var deltaControllerPosition = this.deltaControllerPosition;
  47429. var hand;
  47430. var headEl;
  47431. var headObject3D;
  47432. var pose;
  47433. var userHeight;
  47434. headEl = this.getHeadElement();
  47435. headObject3D = headEl.object3D;
  47436. userHeight = this.defaultUserHeight();
  47437. pose = controller.pose;
  47438. hand = (controller ? controller.hand : undefined) || DEFAULT_HANDEDNESS;
  47439. // Use camera position as head position.
  47440. controllerPosition.copy(headObject3D.position);
  47441. // Set offset for degenerate "arm model" to elbow.
  47442. deltaControllerPosition.set(
  47443. EYES_TO_ELBOW.x * (hand === 'left' ? -1 : hand === 'right' ? 1 : 0),
  47444. EYES_TO_ELBOW.y, // Lower than our eyes.
  47445. EYES_TO_ELBOW.z); // Slightly out in front.
  47446. // Scale offset by user height.
  47447. deltaControllerPosition.multiplyScalar(userHeight);
  47448. // Apply camera Y rotation (not X or Z, so you can look down at your hand).
  47449. deltaControllerPosition.applyAxisAngle(headObject3D.up, headObject3D.rotation.y);
  47450. // Apply rotated offset to position.
  47451. controllerPosition.add(deltaControllerPosition);
  47452. // Set offset for degenerate "arm model" forearm. Forearm sticking out from elbow.
  47453. deltaControllerPosition.set(FOREARM.x, FOREARM.y, FOREARM.z);
  47454. // Scale offset by user height.
  47455. deltaControllerPosition.multiplyScalar(userHeight);
  47456. // Apply controller X/Y rotation (tilting up/down/left/right is usually moving the arm).
  47457. if (pose.orientation) {
  47458. controllerQuaternion.fromArray(pose.orientation);
  47459. } else {
  47460. controllerQuaternion.copy(headObject3D.quaternion);
  47461. }
  47462. controllerEuler.setFromQuaternion(controllerQuaternion);
  47463. controllerEuler.set(controllerEuler.x, controllerEuler.y, 0);
  47464. deltaControllerPosition.applyEuler(controllerEuler);
  47465. // Apply rotated offset to position.
  47466. controllerPosition.add(deltaControllerPosition);
  47467. },
  47468. /**
  47469. * Read pose from controller (from Gamepad API), apply transforms, apply to entity.
  47470. */
  47471. updatePose: function () {
  47472. var controller = this.controller;
  47473. var object3D = this.el.object3D;
  47474. var pose;
  47475. var vrDisplay = this.system.vrDisplay;
  47476. var standingMatrix;
  47477. if (!controller) { return; }
  47478. // Compose pose from Gamepad.
  47479. pose = controller.pose;
  47480. if (pose.position !== null) {
  47481. object3D.position.fromArray(pose.position);
  47482. } else {
  47483. // Controller not 6DOF, apply arm model.
  47484. if (this.data.armModel) { this.applyArmModel(object3D.position); }
  47485. }
  47486. if (pose.orientation !== null) {
  47487. object3D.quaternion.fromArray(pose.orientation);
  47488. }
  47489. // Apply transforms, if 6DOF and in VR.
  47490. if (vrDisplay) {
  47491. standingMatrix = this.el.sceneEl.renderer.vr.getStandingMatrix();
  47492. object3D.matrixAutoUpdate = false;
  47493. object3D.matrix.compose(object3D.position, object3D.quaternion, object3D.scale);
  47494. object3D.matrix.multiplyMatrices(standingMatrix, object3D.matrix);
  47495. object3D.matrixWorldNeedsUpdate = true;
  47496. }
  47497. },
  47498. /**
  47499. * Handle button changes including axes, presses, touches, values.
  47500. */
  47501. updateButtons: function () {
  47502. var buttonState;
  47503. var controller = this.controller;
  47504. var id;
  47505. if (!controller) { return; }
  47506. // Check every button.
  47507. for (id = 0; id < controller.buttons.length; ++id) {
  47508. // Initialize button state.
  47509. if (!this.buttonStates[id]) {
  47510. this.buttonStates[id] = {pressed: false, touched: false, value: 0};
  47511. }
  47512. buttonState = controller.buttons[id];
  47513. this.handleButton(id, buttonState);
  47514. }
  47515. // Check axes.
  47516. this.handleAxes();
  47517. },
  47518. /**
  47519. * Handle presses and touches for a single button.
  47520. *
  47521. * @param {number} id - Index of button in Gamepad button array.
  47522. * @param {number} buttonState - Value of button state from 0 to 1.
  47523. * @returns {boolean} Whether button has changed in any way.
  47524. */
  47525. handleButton: function (id, buttonState) {
  47526. var changed = this.handlePress(id, buttonState) ||
  47527. this.handleTouch(id, buttonState) ||
  47528. this.handleValue(id, buttonState);
  47529. if (!changed) { return false; }
  47530. this.el.emit('buttonchanged', {id: id, state: buttonState});
  47531. return true;
  47532. },
  47533. /**
  47534. * An axis is an array of values from -1 (up, left) to 1 (down, right).
  47535. * Compare each component of the axis to the previous value to determine change.
  47536. *
  47537. * @returns {boolean} Whether axes changed.
  47538. */
  47539. handleAxes: function () {
  47540. var changed = false;
  47541. var controllerAxes = this.controller.axes;
  47542. var i;
  47543. var previousAxis = this.axis;
  47544. var changedAxes = this.changedAxes;
  47545. // Check if axis changed.
  47546. this.changedAxes.length = 0;
  47547. for (i = 0; i < controllerAxes.length; ++i) {
  47548. changedAxes.push(previousAxis[i] !== controllerAxes[i]);
  47549. if (changedAxes[i]) { changed = true; }
  47550. }
  47551. if (!changed) { return false; }
  47552. this.axis.length = 0;
  47553. for (i = 0; i < controllerAxes.length; i++) {
  47554. this.axis.push(controllerAxes[i]);
  47555. }
  47556. this.el.emit('axismove', this.axisMoveEventDetail);
  47557. return true;
  47558. },
  47559. /**
  47560. * Determine whether a button press has occured and emit events as appropriate.
  47561. *
  47562. * @param {string} id - ID of the button to check.
  47563. * @param {object} buttonState - State of the button to check.
  47564. * @returns {boolean} Whether button press state changed.
  47565. */
  47566. handlePress: function (id, buttonState) {
  47567. var evtName;
  47568. var previousButtonState = this.buttonStates[id];
  47569. // Not changed.
  47570. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  47571. evtName = buttonState.pressed ? 'down' : 'up';
  47572. this.el.emit('button' + evtName, {id: id, state: buttonState});
  47573. previousButtonState.pressed = buttonState.pressed;
  47574. return true;
  47575. },
  47576. /**
  47577. * Determine whether a button touch has occured and emit events as appropriate.
  47578. *
  47579. * @param {string} id - ID of the button to check.
  47580. * @param {object} buttonState - State of the button to check.
  47581. * @returns {boolean} Whether button touch state changed.
  47582. */
  47583. handleTouch: function (id, buttonState) {
  47584. var evtName;
  47585. var previousButtonState = this.buttonStates[id];
  47586. // Not changed.
  47587. if (buttonState.touched === previousButtonState.touched) { return false; }
  47588. evtName = buttonState.touched ? 'start' : 'end';
  47589. // Due to unfortunate name collision, add empty touches array to avoid Daydream error.
  47590. this.el.emit('touch' + evtName, {id: id, state: buttonState}, true, {touches: []});
  47591. previousButtonState.touched = buttonState.touched;
  47592. return true;
  47593. },
  47594. /**
  47595. * Determine whether a button value has changed.
  47596. *
  47597. * @param {string} id - Id of the button to check.
  47598. * @param {object} buttonState - State of the button to check.
  47599. * @returns {boolean} Whether button value changed.
  47600. */
  47601. handleValue: function (id, buttonState) {
  47602. var previousButtonState = this.buttonStates[id];
  47603. // Not changed.
  47604. if (buttonState.value === previousButtonState.value) { return false; }
  47605. previousButtonState.value = buttonState.value;
  47606. return true;
  47607. }
  47608. });
  47609. },{"../constants":117,"../core/component":126,"../lib/three":174,"../utils/tracked-controls":201}],112:[function(_dereq_,module,exports){
  47610. var registerComponent = _dereq_('../core/component').registerComponent;
  47611. /**
  47612. * Visibility component.
  47613. */
  47614. module.exports.Component = registerComponent('visible', {
  47615. schema: {default: true},
  47616. update: function () {
  47617. this.el.object3D.visible = this.data;
  47618. }
  47619. });
  47620. },{"../core/component":126}],113:[function(_dereq_,module,exports){
  47621. var registerComponent = _dereq_('../core/component').registerComponent;
  47622. var utils = _dereq_('../utils/');
  47623. var bind = utils.bind;
  47624. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47625. var checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  47626. var emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  47627. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  47628. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  47629. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  47630. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  47631. /**
  47632. * Vive controls.
  47633. * Interface with Vive controllers and map Gamepad events to controller buttons:
  47634. * trackpad, trigger, grip, menu, system
  47635. * Load a controller model and highlight the pressed buttons.
  47636. */
  47637. module.exports.Component = registerComponent('vive-controls', {
  47638. schema: {
  47639. hand: {default: 'left'},
  47640. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  47641. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  47642. model: {default: true},
  47643. rotationOffset: {default: 0}
  47644. },
  47645. /**
  47646. * Button IDs:
  47647. * 0 - trackpad
  47648. * 1 - trigger (intensity value from 0.5 to 1)
  47649. * 2 - grip
  47650. * 3 - menu (dispatch but better for menu options)
  47651. * 4 - system (never dispatched on this layer)
  47652. */
  47653. mapping: {
  47654. axes: {trackpad: [0, 1]},
  47655. buttons: ['trackpad', 'trigger', 'grip', 'menu', 'system']
  47656. },
  47657. init: function () {
  47658. var self = this;
  47659. this.animationActive = 'pointing';
  47660. this.checkControllerPresentAndSetup = checkControllerPresentAndSetup; // To allow mock.
  47661. this.controllerPresent = false;
  47662. this.emitIfAxesChanged = emitIfAxesChanged; // To allow mock.
  47663. this.lastControllerCheck = 0;
  47664. this.onButtonChanged = bind(this.onButtonChanged, this);
  47665. this.onButtonDown = function (evt) { onButtonEvent(evt.detail.id, 'down', self); };
  47666. this.onButtonUp = function (evt) { onButtonEvent(evt.detail.id, 'up', self); };
  47667. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt.detail.id, 'touchend', self); };
  47668. this.onButtonTouchStart = function (evt) { onButtonEvent(evt.detail.id, 'touchstart', self); };
  47669. this.onAxisMoved = bind(this.onAxisMoved, this);
  47670. this.previousButtonValues = {};
  47671. this.bindMethods();
  47672. },
  47673. play: function () {
  47674. this.checkIfControllerPresent();
  47675. this.addControllersUpdateListener();
  47676. },
  47677. pause: function () {
  47678. this.removeEventListeners();
  47679. this.removeControllersUpdateListener();
  47680. },
  47681. bindMethods: function () {
  47682. this.onModelLoaded = bind(this.onModelLoaded, this);
  47683. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  47684. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  47685. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  47686. this.onAxisMoved = bind(this.onAxisMoved, this);
  47687. },
  47688. addEventListeners: function () {
  47689. var el = this.el;
  47690. el.addEventListener('buttonchanged', this.onButtonChanged);
  47691. el.addEventListener('buttondown', this.onButtonDown);
  47692. el.addEventListener('buttonup', this.onButtonUp);
  47693. el.addEventListener('touchend', this.onButtonTouchEnd);
  47694. el.addEventListener('touchstart', this.onButtonTouchStart);
  47695. el.addEventListener('model-loaded', this.onModelLoaded);
  47696. el.addEventListener('axismove', this.onAxisMoved);
  47697. this.controllerEventsActive = true;
  47698. },
  47699. removeEventListeners: function () {
  47700. var el = this.el;
  47701. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47702. el.removeEventListener('buttondown', this.onButtonDown);
  47703. el.removeEventListener('buttonup', this.onButtonUp);
  47704. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47705. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47706. el.removeEventListener('model-loaded', this.onModelLoaded);
  47707. el.removeEventListener('axismove', this.onAxisMoved);
  47708. this.controllerEventsActive = false;
  47709. },
  47710. /**
  47711. * Once OpenVR returns correct hand data in supporting browsers, we can use hand property.
  47712. * var isPresent = this.checkControllerPresentAndSetup(this.el.sceneEl, GAMEPAD_ID_PREFIX,
  47713. { hand: data.hand });
  47714. * Until then, use hardcoded index.
  47715. */
  47716. checkIfControllerPresent: function () {
  47717. var data = this.data;
  47718. var controllerIndex = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47719. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {index: controllerIndex});
  47720. },
  47721. injectTrackedControls: function () {
  47722. var el = this.el;
  47723. var data = this.data;
  47724. // If we have an OpenVR Gamepad, use the fixed mapping.
  47725. el.setAttribute('tracked-controls', {
  47726. idPrefix: GAMEPAD_ID_PREFIX,
  47727. // Hand IDs: 0 = right, 1 = left, 2 = anything else.
  47728. controller: data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2,
  47729. rotationOffset: data.rotationOffset
  47730. });
  47731. // Load model.
  47732. if (!this.data.model) { return; }
  47733. this.el.setAttribute('obj-model', {
  47734. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47735. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47736. });
  47737. },
  47738. addControllersUpdateListener: function () {
  47739. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47740. },
  47741. removeControllersUpdateListener: function () {
  47742. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47743. },
  47744. onControllersUpdate: function () {
  47745. this.checkIfControllerPresent();
  47746. },
  47747. /**
  47748. * Rotate the trigger button based on how hard the trigger is pressed.
  47749. */
  47750. onButtonChanged: function (evt) {
  47751. var button = this.mapping.buttons[evt.detail.id];
  47752. var buttonMeshes = this.buttonMeshes;
  47753. var analogValue;
  47754. if (!button) { return; }
  47755. if (button === 'trigger') {
  47756. analogValue = evt.detail.state.value;
  47757. // Update trigger rotation depending on button value.
  47758. if (buttonMeshes && buttonMeshes.trigger) {
  47759. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 12);
  47760. }
  47761. }
  47762. // Pass along changed event with button state, using button mapping for convenience.
  47763. this.el.emit(button + 'changed', evt.detail.state);
  47764. },
  47765. onModelLoaded: function (evt) {
  47766. var buttonMeshes;
  47767. var controllerObject3D = evt.detail.model;
  47768. var self = this;
  47769. if (!this.data.model) { return; }
  47770. // Store button meshes object to be able to change their colors.
  47771. buttonMeshes = this.buttonMeshes = {};
  47772. buttonMeshes.grip = {
  47773. left: controllerObject3D.getObjectByName('leftgrip'),
  47774. right: controllerObject3D.getObjectByName('rightgrip')
  47775. };
  47776. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47777. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47778. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47779. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47780. // Set default colors.
  47781. Object.keys(buttonMeshes).forEach(function (buttonName) {
  47782. self.setButtonColor(buttonName, self.data.buttonColor);
  47783. });
  47784. // Offset pivot point.
  47785. controllerObject3D.position.set(0, -0.015, 0.04);
  47786. },
  47787. onAxisMoved: function (evt) {
  47788. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  47789. },
  47790. updateModel: function (buttonName, evtName) {
  47791. var color;
  47792. var isTouch;
  47793. if (!this.data.model) { return; }
  47794. isTouch = evtName.indexOf('touch') !== -1;
  47795. // Don't change color for trackpad touch.
  47796. if (isTouch) { return; }
  47797. // Update colors.
  47798. color = evtName === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47799. this.setButtonColor(buttonName, color);
  47800. },
  47801. setButtonColor: function (buttonName, color) {
  47802. var buttonMeshes = this.buttonMeshes;
  47803. if (!buttonMeshes) { return; }
  47804. // Need to do both left and right sides for grip.
  47805. if (buttonName === 'grip') {
  47806. buttonMeshes.grip.left.material.color.set(color);
  47807. buttonMeshes.grip.right.material.color.set(color);
  47808. return;
  47809. }
  47810. buttonMeshes[buttonName].material.color.set(color);
  47811. }
  47812. });
  47813. },{"../core/component":126,"../utils/":196,"../utils/tracked-controls":201}],114:[function(_dereq_,module,exports){
  47814. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47815. var registerComponent = _dereq_('../core/component').registerComponent;
  47816. var THREE = _dereq_('../lib/three');
  47817. var utils = _dereq_('../utils/');
  47818. var bind = utils.bind;
  47819. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47820. var CLAMP_VELOCITY = 0.00001;
  47821. var MAX_DELTA = 0.2;
  47822. var KEYS = [
  47823. 'KeyW', 'KeyA', 'KeyS', 'KeyD',
  47824. 'ArrowUp', 'ArrowLeft', 'ArrowRight', 'ArrowDown'
  47825. ];
  47826. /**
  47827. * WASD component to control entities using WASD keys.
  47828. */
  47829. module.exports.Component = registerComponent('wasd-controls', {
  47830. schema: {
  47831. acceleration: {default: 65},
  47832. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47833. adEnabled: {default: true},
  47834. adInverted: {default: false},
  47835. easing: {default: 20},
  47836. enabled: {default: true},
  47837. fly: {default: false},
  47838. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47839. wsEnabled: {default: true},
  47840. wsInverted: {default: false}
  47841. },
  47842. init: function () {
  47843. // To keep track of the pressed keys.
  47844. this.keys = {};
  47845. this.position = {};
  47846. this.velocity = new THREE.Vector3();
  47847. // Bind methods and add event listeners.
  47848. this.onBlur = bind(this.onBlur, this);
  47849. this.onFocus = bind(this.onFocus, this);
  47850. this.onKeyDown = bind(this.onKeyDown, this);
  47851. this.onKeyUp = bind(this.onKeyUp, this);
  47852. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47853. this.attachVisibilityEventListeners();
  47854. },
  47855. tick: function (time, delta) {
  47856. var currentPosition;
  47857. var data = this.data;
  47858. var el = this.el;
  47859. var movementVector;
  47860. var position = this.position;
  47861. var velocity = this.velocity;
  47862. if (!velocity[data.adAxis] && !velocity[data.wsAxis] &&
  47863. isEmptyObject(this.keys)) { return; }
  47864. // Update velocity.
  47865. delta = delta / 1000;
  47866. this.updateVelocity(delta);
  47867. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47868. // Get movement vector and translate position.
  47869. currentPosition = el.getAttribute('position');
  47870. movementVector = this.getMovementVector(delta);
  47871. position.x = currentPosition.x + movementVector.x;
  47872. position.y = currentPosition.y + movementVector.y;
  47873. position.z = currentPosition.z + movementVector.z;
  47874. el.setAttribute('position', position);
  47875. },
  47876. remove: function () {
  47877. this.removeKeyEventListeners();
  47878. this.removeVisibilityEventListeners();
  47879. },
  47880. play: function () {
  47881. this.attachKeyEventListeners();
  47882. },
  47883. pause: function () {
  47884. this.keys = {};
  47885. this.removeKeyEventListeners();
  47886. },
  47887. updateVelocity: function (delta) {
  47888. var acceleration;
  47889. var adAxis;
  47890. var adSign;
  47891. var data = this.data;
  47892. var keys = this.keys;
  47893. var velocity = this.velocity;
  47894. var wsAxis;
  47895. var wsSign;
  47896. adAxis = data.adAxis;
  47897. wsAxis = data.wsAxis;
  47898. // If FPS too low, reset velocity.
  47899. if (delta > MAX_DELTA) {
  47900. velocity[adAxis] = 0;
  47901. velocity[wsAxis] = 0;
  47902. return;
  47903. }
  47904. // Decay velocity.
  47905. if (velocity[adAxis] !== 0) {
  47906. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  47907. }
  47908. if (velocity[wsAxis] !== 0) {
  47909. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  47910. }
  47911. // Clamp velocity easing.
  47912. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47913. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47914. if (!data.enabled) { return; }
  47915. // Update velocity using keys pressed.
  47916. acceleration = data.acceleration;
  47917. if (data.adEnabled) {
  47918. adSign = data.adInverted ? -1 : 1;
  47919. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47920. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47921. }
  47922. if (data.wsEnabled) {
  47923. wsSign = data.wsInverted ? -1 : 1;
  47924. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47925. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47926. }
  47927. },
  47928. getMovementVector: (function () {
  47929. var directionVector = new THREE.Vector3(0, 0, 0);
  47930. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47931. return function (delta) {
  47932. var rotation = this.el.getAttribute('rotation');
  47933. var velocity = this.velocity;
  47934. var xRotation;
  47935. directionVector.copy(velocity);
  47936. directionVector.multiplyScalar(delta);
  47937. // Absolute.
  47938. if (!rotation) { return directionVector; }
  47939. xRotation = this.data.fly ? rotation.x : 0;
  47940. // Transform direction relative to heading.
  47941. rotationEuler.set(THREE.Math.degToRad(xRotation), THREE.Math.degToRad(rotation.y), 0);
  47942. directionVector.applyEuler(rotationEuler);
  47943. return directionVector;
  47944. };
  47945. })(),
  47946. attachVisibilityEventListeners: function () {
  47947. window.addEventListener('blur', this.onBlur);
  47948. window.addEventListener('focus', this.onFocus);
  47949. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47950. },
  47951. removeVisibilityEventListeners: function () {
  47952. window.removeEventListener('blur', this.onBlur);
  47953. window.removeEventListener('focus', this.onFocus);
  47954. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47955. },
  47956. attachKeyEventListeners: function () {
  47957. window.addEventListener('keydown', this.onKeyDown);
  47958. window.addEventListener('keyup', this.onKeyUp);
  47959. },
  47960. removeKeyEventListeners: function () {
  47961. window.removeEventListener('keydown', this.onKeyDown);
  47962. window.removeEventListener('keyup', this.onKeyUp);
  47963. },
  47964. onBlur: function () {
  47965. this.pause();
  47966. },
  47967. onFocus: function () {
  47968. this.play();
  47969. },
  47970. onVisibilityChange: function () {
  47971. if (document.hidden) {
  47972. this.onBlur();
  47973. } else {
  47974. this.onFocus();
  47975. }
  47976. },
  47977. onKeyDown: function (event) {
  47978. var code;
  47979. if (!shouldCaptureKeyEvent(event)) { return; }
  47980. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47981. if (KEYS.indexOf(code) !== -1) { this.keys[code] = true; }
  47982. },
  47983. onKeyUp: function (event) {
  47984. var code;
  47985. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47986. delete this.keys[code];
  47987. }
  47988. });
  47989. function isEmptyObject (keys) {
  47990. var key;
  47991. for (key in keys) { return false; }
  47992. return true;
  47993. }
  47994. },{"../constants":117,"../core/component":126,"../lib/three":174,"../utils/":196}],115:[function(_dereq_,module,exports){
  47995. /* global THREE */
  47996. var bind = _dereq_('../utils/bind');
  47997. var registerComponent = _dereq_('../core/component').registerComponent;
  47998. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  47999. var onButtonEvent = trackedControlsUtils.onButtonEvent;
  48000. var utils = _dereq_('../utils/');
  48001. var debug = utils.debug('components:windows-motion-controls:debug');
  48002. var warn = utils.debug('components:windows-motion-controls:warn');
  48003. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  48004. var MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/microsoft/';
  48005. var MODEL_FILENAMES = { left: 'left.glb', right: 'right.glb', default: 'universal.glb' };
  48006. var GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  48007. var GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  48008. /**
  48009. * Windows Motion Controller controls.
  48010. * Interface with Windows Motion Controller controllers and map Gamepad events to
  48011. * controller buttons: trackpad, trigger, grip, menu, thumbstick
  48012. * Load a controller model and transform the pressed buttons.
  48013. */
  48014. module.exports.Component = registerComponent('windows-motion-controls', {
  48015. schema: {
  48016. hand: {default: DEFAULT_HANDEDNESS},
  48017. // It is possible to have multiple pairs of controllers attached (a pair has both left and right).
  48018. // Set this to 1 to use a controller from the second pair, 2 from the third pair, etc.
  48019. pair: {default: 0},
  48020. // If true, loads the controller glTF asset.
  48021. model: {default: true},
  48022. // If true, will hide the model from the scene if no matching gamepad (based on ID & hand) is connected.
  48023. hideDisconnected: {default: true}
  48024. },
  48025. mapping: {
  48026. // A-Frame specific semantic axis names
  48027. axes: {'thumbstick': [0, 1], 'trackpad': [2, 3]},
  48028. // A-Frame specific semantic button names
  48029. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  48030. // A mapping of the semantic name to node name in the glTF model file,
  48031. // that should be transformed by axis value.
  48032. // This array mirrors the browser Gamepad.axes array, such that
  48033. // the mesh corresponding to axis 0 is in this array index 0.
  48034. axisMeshNames: [
  48035. 'THUMBSTICK_X',
  48036. 'THUMBSTICK_Y',
  48037. 'TOUCHPAD_TOUCH_X',
  48038. 'TOUCHPAD_TOUCH_Y'
  48039. ],
  48040. // A mapping of the semantic name to button node name in the glTF model file,
  48041. // that should be transformed by button value.
  48042. buttonMeshNames: {
  48043. 'trigger': 'SELECT',
  48044. 'menu': 'MENU',
  48045. 'grip': 'GRASP',
  48046. 'thumbstick': 'THUMBSTICK_PRESS',
  48047. 'trackpad': 'TOUCHPAD_PRESS'
  48048. },
  48049. pointingPoseMeshName: 'POINTING_POSE'
  48050. },
  48051. bindMethods: function () {
  48052. this.onModelError = bind(this.onModelError, this);
  48053. this.onModelLoaded = bind(this.onModelLoaded, this);
  48054. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  48055. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  48056. this.onAxisMoved = bind(this.onAxisMoved, this);
  48057. },
  48058. init: function () {
  48059. var self = this;
  48060. var el = this.el;
  48061. this.onButtonChanged = bind(this.onButtonChanged, this);
  48062. this.onButtonDown = function (evt) { onButtonEvent(evt, 'down', self); };
  48063. this.onButtonUp = function (evt) { onButtonEvent(evt, 'up', self); };
  48064. this.onButtonTouchStart = function (evt) { onButtonEvent(evt, 'touchstart', self); };
  48065. this.onButtonTouchEnd = function (evt) { onButtonEvent(evt, 'touchend', self); };
  48066. this.onControllerConnected = function () { self.setModelVisibility(true); };
  48067. this.onControllerDisconnected = function () { self.setModelVisibility(false); };
  48068. this.controllerPresent = false;
  48069. this.lastControllerCheck = 0;
  48070. this.previousButtonValues = {};
  48071. this.bindMethods();
  48072. // Cache for submeshes that we have looked up by name.
  48073. this.loadedMeshInfo = {
  48074. buttonMeshes: null,
  48075. axisMeshes: null
  48076. };
  48077. // Pointing poses
  48078. this.rayOrigin = {
  48079. origin: new THREE.Vector3(),
  48080. direction: new THREE.Vector3(0, 0, -1),
  48081. createdFromMesh: false
  48082. };
  48083. // Stored on object to allow for mocking in tests
  48084. this.emitIfAxesChanged = trackedControlsUtils.emitIfAxesChanged;
  48085. this.checkControllerPresentAndSetup = trackedControlsUtils.checkControllerPresentAndSetup;
  48086. el.addEventListener('controllerconnected', this.onControllerConnected);
  48087. el.addEventListener('controllerdisconnected', this.onControllerDisconnected);
  48088. },
  48089. addEventListeners: function () {
  48090. var el = this.el;
  48091. el.addEventListener('buttonchanged', this.onButtonChanged);
  48092. el.addEventListener('buttondown', this.onButtonDown);
  48093. el.addEventListener('buttonup', this.onButtonUp);
  48094. el.addEventListener('touchstart', this.onButtonTouchStart);
  48095. el.addEventListener('touchend', this.onButtonTouchEnd);
  48096. el.addEventListener('axismove', this.onAxisMoved);
  48097. el.addEventListener('model-error', this.onModelError);
  48098. el.addEventListener('model-loaded', this.onModelLoaded);
  48099. this.controllerEventsActive = true;
  48100. },
  48101. removeEventListeners: function () {
  48102. var el = this.el;
  48103. el.removeEventListener('buttonchanged', this.onButtonChanged);
  48104. el.removeEventListener('buttondown', this.onButtonDown);
  48105. el.removeEventListener('buttonup', this.onButtonUp);
  48106. el.removeEventListener('touchstart', this.onButtonTouchStart);
  48107. el.removeEventListener('touchend', this.onButtonTouchEnd);
  48108. el.removeEventListener('axismove', this.onAxisMoved);
  48109. el.removeEventListener('model-error', this.onModelError);
  48110. el.removeEventListener('model-loaded', this.onModelLoaded);
  48111. this.controllerEventsActive = false;
  48112. },
  48113. checkIfControllerPresent: function () {
  48114. this.checkControllerPresentAndSetup(this, GAMEPAD_ID_PREFIX, {
  48115. hand: this.data.hand,
  48116. index: this.data.pair
  48117. });
  48118. },
  48119. play: function () {
  48120. this.checkIfControllerPresent();
  48121. this.addControllersUpdateListener();
  48122. },
  48123. pause: function () {
  48124. this.removeEventListeners();
  48125. this.removeControllersUpdateListener();
  48126. },
  48127. updateControllerModel: function () {
  48128. // If we do not want to load a model, or, have already loaded the model, emit the controllermodelready event.
  48129. if (!this.data.model || this.rayOrigin.createdFromMesh) {
  48130. this.modelReady();
  48131. return;
  48132. }
  48133. var sourceUrl = this.createControllerModelUrl();
  48134. this.loadModel(sourceUrl);
  48135. },
  48136. /**
  48137. * Helper function that constructs a URL from the controller ID suffix, for future proofed
  48138. * art assets.
  48139. */
  48140. createControllerModelUrl: function (forceDefault) {
  48141. // Determine the device specific folder based on the ID suffix
  48142. var trackedControlsComponent = this.el.components['tracked-controls'];
  48143. var controller = trackedControlsComponent ? trackedControlsComponent.controller : null;
  48144. var device = 'default';
  48145. var hand = this.data.hand;
  48146. var filename;
  48147. if (controller) {
  48148. // Read hand directly from the controller, rather than this.data, as in the case that the controller
  48149. // is unhanded this.data will still have 'left' or 'right' (depending on what the user inserted in to the scene).
  48150. // In this case, we want to load the universal model, so need to get the '' from the controller.
  48151. hand = controller.hand;
  48152. if (!forceDefault) {
  48153. var match = controller.id.match(GAMEPAD_ID_PATTERN);
  48154. device = ((match && match[0]) || device);
  48155. }
  48156. }
  48157. // Hand
  48158. filename = MODEL_FILENAMES[hand] || MODEL_FILENAMES.default;
  48159. // Final url
  48160. return MODEL_BASE_URL + device + '/' + filename;
  48161. },
  48162. injectTrackedControls: function () {
  48163. var data = this.data;
  48164. this.el.setAttribute('tracked-controls', {
  48165. idPrefix: GAMEPAD_ID_PREFIX,
  48166. controller: data.pair,
  48167. hand: data.hand,
  48168. armModel: false
  48169. });
  48170. this.updateControllerModel();
  48171. },
  48172. addControllersUpdateListener: function () {
  48173. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  48174. },
  48175. removeControllersUpdateListener: function () {
  48176. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  48177. },
  48178. onControllersUpdate: function () {
  48179. this.checkIfControllerPresent();
  48180. },
  48181. onModelError: function (evt) {
  48182. var defaultUrl = this.createControllerModelUrl(true);
  48183. if (evt.detail.src !== defaultUrl) {
  48184. warn('Failed to load controller model for device, attempting to load default.');
  48185. this.loadModel(defaultUrl);
  48186. } else {
  48187. warn('Failed to load default controller model.');
  48188. }
  48189. },
  48190. loadModel: function (url) {
  48191. // The model is loaded by the gltf-model compoent when this attribute is initially set,
  48192. // removed and re-loaded if the given url changes.
  48193. this.el.setAttribute('gltf-model', 'url(' + url + ')');
  48194. },
  48195. onModelLoaded: function (evt) {
  48196. var rootNode = this.controllerModel = evt.detail.model;
  48197. var loadedMeshInfo = this.loadedMeshInfo;
  48198. var i;
  48199. var meshName;
  48200. var mesh;
  48201. var meshInfo;
  48202. debug('Processing model');
  48203. // Reset the caches
  48204. loadedMeshInfo.buttonMeshes = {};
  48205. loadedMeshInfo.axisMeshes = {};
  48206. // Cache our meshes so we aren't traversing the hierarchy per frame
  48207. if (rootNode) {
  48208. // Button Meshes
  48209. for (i = 0; i < this.mapping.buttons.length; i++) {
  48210. meshName = this.mapping.buttonMeshNames[this.mapping.buttons[i]];
  48211. if (!meshName) {
  48212. debug('Skipping unknown button at index: ' + i + ' with mapped name: ' + this.mapping.buttons[i]);
  48213. continue;
  48214. }
  48215. mesh = rootNode.getObjectByName(meshName);
  48216. if (!mesh) {
  48217. warn('Missing button mesh with name: ' + meshName);
  48218. continue;
  48219. }
  48220. meshInfo = {
  48221. index: i,
  48222. value: getImmediateChildByName(mesh, 'VALUE'),
  48223. pressed: getImmediateChildByName(mesh, 'PRESSED'),
  48224. unpressed: getImmediateChildByName(mesh, 'UNPRESSED')
  48225. };
  48226. if (meshInfo.value && meshInfo.pressed && meshInfo.unpressed) {
  48227. loadedMeshInfo.buttonMeshes[this.mapping.buttons[i]] = meshInfo;
  48228. } else {
  48229. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  48230. warn('Missing button submesh under mesh with name: ' + meshName +
  48231. '(VALUE: ' + !!meshInfo.value +
  48232. ', PRESSED: ' + !!meshInfo.pressed +
  48233. ', UNPRESSED:' + !!meshInfo.unpressed +
  48234. ')');
  48235. }
  48236. }
  48237. // Axis Meshes
  48238. for (i = 0; i < this.mapping.axisMeshNames.length; i++) {
  48239. meshName = this.mapping.axisMeshNames[i];
  48240. if (!meshName) {
  48241. debug('Skipping unknown axis at index: ' + i);
  48242. continue;
  48243. }
  48244. mesh = rootNode.getObjectByName(meshName);
  48245. if (!mesh) {
  48246. warn('Missing axis mesh with name: ' + meshName);
  48247. continue;
  48248. }
  48249. meshInfo = {
  48250. index: i,
  48251. value: getImmediateChildByName(mesh, 'VALUE'),
  48252. min: getImmediateChildByName(mesh, 'MIN'),
  48253. max: getImmediateChildByName(mesh, 'MAX')
  48254. };
  48255. if (meshInfo.value && meshInfo.min && meshInfo.max) {
  48256. loadedMeshInfo.axisMeshes[i] = meshInfo;
  48257. } else {
  48258. // If we didn't find the mesh, it simply means this axis won't have transforms applied as mapped axis values change.
  48259. warn('Missing axis submesh under mesh with name: ' + meshName +
  48260. '(VALUE: ' + !!meshInfo.value +
  48261. ', MIN: ' + !!meshInfo.min +
  48262. ', MAX:' + !!meshInfo.max +
  48263. ')');
  48264. }
  48265. }
  48266. this.calculateRayOriginFromMesh(rootNode);
  48267. // Determine if the model has to be visible or not.
  48268. this.setModelVisibility();
  48269. }
  48270. debug('Model load complete.');
  48271. // Look through only immediate children. This will return null if no mesh exists with the given name.
  48272. function getImmediateChildByName (object3d, value) {
  48273. for (var i = 0, l = object3d.children.length; i < l; i++) {
  48274. var obj = object3d.children[i];
  48275. if (obj && obj['name'] === value) {
  48276. return obj;
  48277. }
  48278. }
  48279. return undefined;
  48280. }
  48281. },
  48282. calculateRayOriginFromMesh: (function () {
  48283. var quaternion = new THREE.Quaternion();
  48284. return function (rootNode) {
  48285. var mesh;
  48286. // Calculate the pointer pose (used for rays), by applying the world transform of th POINTER_POSE node
  48287. // in the glTF (assumes that root node is at world origin)
  48288. this.rayOrigin.origin.set(0, 0, 0);
  48289. this.rayOrigin.direction.set(0, 0, -1);
  48290. this.rayOrigin.createdFromMesh = true;
  48291. // Try to read Pointing pose from the source model
  48292. mesh = rootNode.getObjectByName(this.mapping.pointingPoseMeshName);
  48293. if (mesh) {
  48294. var parent = rootNode.parent;
  48295. // We need to read pose transforms accumulated from the root of the glTF, not the scene.
  48296. if (parent) {
  48297. rootNode.parent = null;
  48298. rootNode.updateMatrixWorld(true);
  48299. rootNode.parent = parent;
  48300. }
  48301. mesh.getWorldPosition(this.rayOrigin.origin);
  48302. mesh.getWorldQuaternion(quaternion);
  48303. this.rayOrigin.direction.applyQuaternion(quaternion);
  48304. // Recalculate the world matrices now that the rootNode is re-attached to the parent.
  48305. if (parent) {
  48306. rootNode.updateMatrixWorld(true);
  48307. }
  48308. } else {
  48309. debug('Mesh does not contain pointing origin data, defaulting to none.');
  48310. }
  48311. // Emit event stating that our pointing ray is now accurate.
  48312. this.modelReady();
  48313. };
  48314. })(),
  48315. lerpAxisTransform: (function () {
  48316. var quaternion = new THREE.Quaternion();
  48317. return function (axis, axisValue) {
  48318. var axisMeshInfo = this.loadedMeshInfo.axisMeshes[axis];
  48319. if (!axisMeshInfo) return;
  48320. var min = axisMeshInfo.min;
  48321. var max = axisMeshInfo.max;
  48322. var target = axisMeshInfo.value;
  48323. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  48324. var lerpValue = axisValue * 0.5 + 0.5;
  48325. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, lerpValue));
  48326. target.position.lerpVectors(min.position, max.position, lerpValue);
  48327. };
  48328. })(),
  48329. lerpButtonTransform: (function () {
  48330. var quaternion = new THREE.Quaternion();
  48331. return function (buttonName, buttonValue) {
  48332. var buttonMeshInfo = this.loadedMeshInfo.buttonMeshes[buttonName];
  48333. if (!buttonMeshInfo) return;
  48334. var min = buttonMeshInfo.unpressed;
  48335. var max = buttonMeshInfo.pressed;
  48336. var target = buttonMeshInfo.value;
  48337. target.setRotationFromQuaternion(quaternion.copy(min.quaternion).slerp(max.quaternion, buttonValue));
  48338. target.position.lerpVectors(min.position, max.position, buttonValue);
  48339. };
  48340. })(),
  48341. modelReady: function () {
  48342. this.el.emit('controllermodelready', {
  48343. name: 'windows-motion-controls',
  48344. model: this.data.model,
  48345. rayOrigin: this.rayOrigin
  48346. });
  48347. },
  48348. onButtonChanged: function (evt) {
  48349. var buttonName = this.mapping.buttons[evt.detail.id];
  48350. if (buttonName) {
  48351. // Update the button mesh transform
  48352. if (this.loadedMeshInfo && this.loadedMeshInfo.buttonMeshes) {
  48353. this.lerpButtonTransform(buttonName, evt.detail.state.value);
  48354. }
  48355. // Only emit events for buttons that we know how to map from index to name
  48356. this.el.emit(buttonName + 'changed', evt.detail.state);
  48357. }
  48358. },
  48359. onAxisMoved: function (evt) {
  48360. var numAxes = this.mapping.axisMeshNames.length;
  48361. // Only attempt to update meshes if we have valid data.
  48362. if (this.loadedMeshInfo && this.loadedMeshInfo.axisMeshes) {
  48363. for (var axis = 0; axis < numAxes; axis++) {
  48364. // Update the button mesh transform
  48365. this.lerpAxisTransform(axis, evt.detail.axis[axis] || 0.0);
  48366. }
  48367. }
  48368. this.emitIfAxesChanged(this, this.mapping.axes, evt);
  48369. },
  48370. setModelVisibility: function (visible) {
  48371. var model = this.el.getObject3D('mesh');
  48372. visible = visible !== undefined ? visible : this.modelVisible;
  48373. this.modelVisible = visible;
  48374. if (!model) { return; }
  48375. model.visible = visible;
  48376. }
  48377. });
  48378. },{"../constants":117,"../core/component":126,"../utils/":196,"../utils/bind":190,"../utils/tracked-controls":201}],116:[function(_dereq_,module,exports){
  48379. /**
  48380. * Animation configuration options for TWEEN.js animations.
  48381. * Used by `<a-animation>`.
  48382. */
  48383. var TWEEN = _dereq_('@tweenjs/tween.js');
  48384. var DIRECTIONS = {
  48385. alternate: 'alternate',
  48386. alternateReverse: 'alternate-reverse',
  48387. normal: 'normal',
  48388. reverse: 'reverse'
  48389. };
  48390. var EASING_FUNCTIONS = {
  48391. 'linear': TWEEN.Easing.Linear.None,
  48392. 'ease': TWEEN.Easing.Cubic.InOut,
  48393. 'ease-in': TWEEN.Easing.Cubic.In,
  48394. 'ease-out': TWEEN.Easing.Cubic.Out,
  48395. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  48396. 'ease-cubic': TWEEN.Easing.Cubic.In,
  48397. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  48398. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  48399. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  48400. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  48401. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  48402. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  48403. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  48404. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  48405. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  48406. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  48407. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  48408. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  48409. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  48410. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  48411. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  48412. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  48413. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  48414. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  48415. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  48416. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  48417. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  48418. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  48419. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  48420. 'ease-circ': TWEEN.Easing.Circular.InOut,
  48421. 'ease-in-circ': TWEEN.Easing.Circular.In,
  48422. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  48423. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  48424. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  48425. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  48426. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  48427. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  48428. 'ease-back': TWEEN.Easing.Back.InOut,
  48429. 'ease-in-back': TWEEN.Easing.Back.In,
  48430. 'ease-out-back': TWEEN.Easing.Back.Out,
  48431. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  48432. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  48433. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  48434. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  48435. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  48436. };
  48437. var FILLS = {
  48438. backwards: 'backwards',
  48439. both: 'both',
  48440. forwards: 'forwards',
  48441. none: 'none'
  48442. };
  48443. var REPEATS = {
  48444. indefinite: 'indefinite'
  48445. };
  48446. var DEFAULTS = {
  48447. attribute: 'rotation',
  48448. begin: '',
  48449. end: '',
  48450. delay: 0,
  48451. dur: 1000,
  48452. easing: 'ease',
  48453. direction: DIRECTIONS.normal,
  48454. fill: FILLS.forwards,
  48455. from: undefined,
  48456. repeat: 0,
  48457. to: undefined
  48458. };
  48459. module.exports.defaults = DEFAULTS;
  48460. module.exports.directions = DIRECTIONS;
  48461. module.exports.easingFunctions = EASING_FUNCTIONS;
  48462. module.exports.fills = FILLS;
  48463. module.exports.repeats = REPEATS;
  48464. },{"@tweenjs/tween.js":1}],117:[function(_dereq_,module,exports){
  48465. module.exports = {
  48466. AFRAME_INJECTED: 'aframe-injected',
  48467. DEFAULT_CAMERA_HEIGHT: 1.6,
  48468. DEFAULT_HANDEDNESS: 'right',
  48469. animation: _dereq_('./animation'),
  48470. keyboardevent: _dereq_('./keyboardevent')
  48471. };
  48472. },{"./animation":116,"./keyboardevent":118}],118:[function(_dereq_,module,exports){
  48473. module.exports = {
  48474. // Tiny KeyboardEvent.code polyfill.
  48475. KEYCODE_TO_CODE: {
  48476. '38': 'ArrowUp',
  48477. '37': 'ArrowLeft',
  48478. '40': 'ArrowDown',
  48479. '39': 'ArrowRight',
  48480. '87': 'KeyW',
  48481. '65': 'KeyA',
  48482. '83': 'KeyS',
  48483. '68': 'KeyD'
  48484. }
  48485. };
  48486. },{}],119:[function(_dereq_,module,exports){
  48487. var ANode = _dereq_('./a-node');
  48488. var animationConstants = _dereq_('../constants/animation');
  48489. var coordinates = _dereq_('../utils/').coordinates;
  48490. var parseProperty = _dereq_('./schema').parseProperty;
  48491. var registerElement = _dereq_('./a-register-element').registerElement;
  48492. var TWEEN = _dereq_('@tweenjs/tween.js');
  48493. var THREE = _dereq_('../lib/three');
  48494. var utils = _dereq_('../utils/');
  48495. var bind = utils.bind;
  48496. var getComponentProperty = utils.entity.getComponentProperty;
  48497. var DEFAULTS = animationConstants.defaults;
  48498. var DIRECTIONS = animationConstants.directions;
  48499. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  48500. var FILLS = animationConstants.fills;
  48501. var REPEATS = animationConstants.repeats;
  48502. var isCoordinates = coordinates.isCoordinates;
  48503. /**
  48504. * Animation element that applies Tween animation to parent element (entity).
  48505. * Takes after the Web Animations spec.
  48506. *
  48507. * @member {number} count - Decrementing counter for how many cycles of animations left to
  48508. * run.
  48509. * @member {Element} el - Entity which the animation is modifying.
  48510. * @member initialValue - Value before animation started. Used to restore state.
  48511. * @member {bool} isRunning - Whether animation is currently running.
  48512. * @member {function} partialSetAttribute -
  48513. * setAttribute function that is agnostic to whether we are setting an attribute value
  48514. * or a component property value. The el and the attribute names are bundled with
  48515. * the function.
  48516. * @member {object} tween - tween.js object.
  48517. */
  48518. module.exports.AAnimation = registerElement('a-animation', {
  48519. prototype: Object.create(ANode.prototype, {
  48520. createdCallback: {
  48521. value: function () {
  48522. this.bindMethods();
  48523. this.isRunning = false;
  48524. this.partialSetAttribute = function () { /* no-op */ };
  48525. this.tween = null;
  48526. }
  48527. },
  48528. attachedCallback: {
  48529. value: function () {
  48530. this.el = this.parentNode;
  48531. this.handleMixinUpdate();
  48532. this.update();
  48533. this.load();
  48534. }
  48535. },
  48536. attributeChangedCallback: {
  48537. value: function (attr, oldVal, newVal) {
  48538. if (!this.hasLoaded || !this.isRunning) { return; }
  48539. this.stop();
  48540. this.handleMixinUpdate();
  48541. this.update();
  48542. }
  48543. },
  48544. detachedCallback: {
  48545. value: function () {
  48546. if (!this.isRunning) { return; }
  48547. this.stop();
  48548. }
  48549. },
  48550. /**
  48551. * Builds a Tween object to handle animations.
  48552. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  48553. * Note: tween.js takes objects for its `from` and `to` values.
  48554. *
  48555. * @returns {object}
  48556. */
  48557. getTween: {
  48558. value: function () {
  48559. var self = this;
  48560. var data = self.data;
  48561. var el = self.el;
  48562. var animationValues;
  48563. var attribute = data.attribute;
  48564. var delay = parseInt(data.delay, 10);
  48565. var currentValue = getComponentProperty(el, attribute);
  48566. var direction = self.getDirection(data.direction);
  48567. var easing = EASING_FUNCTIONS[data.easing];
  48568. var fill = data.fill;
  48569. var from;
  48570. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  48571. var to;
  48572. var toTemp;
  48573. var yoyo = false;
  48574. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  48575. from = animationValues.from;
  48576. to = animationValues.to;
  48577. self.partialSetAttribute = animationValues.partialSetAttribute;
  48578. if (self.count === undefined) {
  48579. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  48580. }
  48581. if (isNaN(delay)) { delay = 0; }
  48582. // Store initial state.
  48583. self.initialValue = self.initialValue || cloneValue(currentValue);
  48584. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  48585. if (repeat === Infinity && fill === FILLS.forwards &&
  48586. [DIRECTIONS.alternate,
  48587. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  48588. yoyo = true;
  48589. }
  48590. // If reversing, swap from and to.
  48591. if (direction === DIRECTIONS.reverse) {
  48592. toTemp = to;
  48593. to = cloneValue(from);
  48594. from = cloneValue(toTemp);
  48595. }
  48596. // If fill is backwards or both, start animation at the specified from.
  48597. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  48598. self.partialSetAttribute(from);
  48599. }
  48600. // Create Tween.
  48601. return new TWEEN.Tween(cloneValue(from))
  48602. .to(to, data.dur)
  48603. .delay(delay)
  48604. .easing(easing)
  48605. .repeat(repeat)
  48606. .yoyo(yoyo)
  48607. .onUpdate(function () {
  48608. self.partialSetAttribute(this);
  48609. })
  48610. .onComplete(bind(self.onCompleted, self));
  48611. }
  48612. },
  48613. /**
  48614. * Animation parameters changed. Stop current animation, get a new one, and start it.
  48615. */
  48616. update: {
  48617. value: function () {
  48618. var data = this.data;
  48619. // Terminology warning if infinite used instead of indefinite
  48620. if (data.repeat === 'infinite') {
  48621. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  48622. }
  48623. // Deprecation warning for begin when used as a delay.
  48624. if (data.begin !== '' && !isNaN(data.begin)) {
  48625. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  48626. data.delay = data.begin;
  48627. data.begin = '';
  48628. }
  48629. var begin = data.begin;
  48630. var end = data.end;
  48631. // Cancel previous event listeners
  48632. if (this.evt) { this.removeEventListeners(this.evt); }
  48633. // Store new event name.
  48634. this.evt = {begin: begin, end: end};
  48635. // Add new event listeners
  48636. this.addEventListeners(this.evt);
  48637. // If `begin` is not defined, start the animation right away.
  48638. if (begin === '') {
  48639. this.stop();
  48640. this.start();
  48641. }
  48642. },
  48643. writable: window.debug
  48644. },
  48645. /**
  48646. * Callback for when a cycle of an animation is complete. Handles when to completely
  48647. * finish the animation.
  48648. *
  48649. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  48650. * handled by ending the current animation and creating a new one with `count` updated.
  48651. * Note that this method is *not* called if repeat is set to `indefinite`.
  48652. */
  48653. onCompleted: {
  48654. value: function () {
  48655. var data = this.data;
  48656. this.isRunning = false;
  48657. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  48658. this.partialSetAttribute(this.initialValue);
  48659. }
  48660. if (this.count === 0) {
  48661. this.count = undefined;
  48662. this.emit('animationend');
  48663. return;
  48664. }
  48665. this.isRunning = false;
  48666. this.count--;
  48667. this.start();
  48668. }
  48669. },
  48670. start: {
  48671. value: function () {
  48672. var self = this;
  48673. // Postpone animation start until the entity has loaded
  48674. if (!this.el.hasLoaded) {
  48675. this.el.addEventListener('loaded', function () { self.start(); });
  48676. return;
  48677. }
  48678. if (this.isRunning || !this.el.isPlaying) { return; }
  48679. this.tween = this.getTween();
  48680. this.isRunning = true;
  48681. this.tween.start();
  48682. this.emit('animationstart');
  48683. },
  48684. writable: true
  48685. },
  48686. stop: {
  48687. value: function () {
  48688. var tween = this.tween;
  48689. if (!tween) { return; }
  48690. tween.stop();
  48691. this.isRunning = false;
  48692. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  48693. this.partialSetAttribute(this.initialValue);
  48694. }
  48695. this.emit('animationstop');
  48696. },
  48697. writable: true
  48698. },
  48699. /**
  48700. * Handle alternating directions. Given the current direction, calculate the next one,
  48701. * and store the current one.
  48702. *
  48703. * @param {string} direction
  48704. * @returns {string} Direction that the next individual cycle of the animation will go
  48705. * towards.
  48706. */
  48707. getDirection: {
  48708. value: function (direction) {
  48709. if (direction === DIRECTIONS.alternate) {
  48710. this.prevDirection =
  48711. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  48712. return this.prevDirection;
  48713. }
  48714. if (direction === DIRECTIONS.alternateReverse) {
  48715. this.prevDirection =
  48716. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  48717. return this.prevDirection;
  48718. }
  48719. return direction;
  48720. }
  48721. },
  48722. /**
  48723. * Preemptive binding to attach/detach event listeners (see `update`).
  48724. */
  48725. bindMethods: {
  48726. value: function () {
  48727. this.start = bind(this.start, this);
  48728. this.stop = bind(this.stop, this);
  48729. this.onStateAdded = bind(this.onStateAdded, this);
  48730. this.onStateRemoved = bind(this.onStateRemoved, this);
  48731. }
  48732. },
  48733. addEventListeners: {
  48734. value: function (evts) {
  48735. var el = this.el;
  48736. var self = this;
  48737. utils.splitString(evts.begin).forEach(function (evt) {
  48738. el.addEventListener(evt, self.start);
  48739. });
  48740. utils.splitString(evts.end).forEach(function (evt) {
  48741. el.addEventListener(evt, self.stop);
  48742. });
  48743. // If "begin" is an event name, wait. If it is not defined, start.
  48744. if (evts.begin === '') { el.addEventListener('play', this.start); }
  48745. el.addEventListener('pause', this.stop);
  48746. el.addEventListener('stateadded', this.onStateAdded);
  48747. el.addEventListener('stateremoved', this.onStateRemoved);
  48748. }
  48749. },
  48750. removeEventListeners: {
  48751. value: function (evts) {
  48752. var el = this.el;
  48753. var start = this.start;
  48754. var stop = this.stop;
  48755. utils.splitString(evts.begin).forEach(function (evt) {
  48756. el.removeEventListener(evt, start);
  48757. });
  48758. utils.splitString(evts.end).forEach(function (evt) {
  48759. el.removeEventListener(evt, stop);
  48760. });
  48761. el.removeEventListener('stateadded', this.onStateAdded);
  48762. el.removeEventListener('stateremoved', this.onStateRemoved);
  48763. }
  48764. },
  48765. onStateAdded: {
  48766. value: function (evt) {
  48767. if (evt.detail.state === this.data.begin) { this.start(); }
  48768. },
  48769. writable: true
  48770. },
  48771. onStateRemoved: {
  48772. value: function (evt) {
  48773. if (evt.detail.state === this.data.begin) { this.stop(); }
  48774. },
  48775. writable: true
  48776. },
  48777. /**
  48778. * Applies animation data from a mixin element.
  48779. * Works the same as component mixins but reimplemented because animations
  48780. * aren't components.
  48781. */
  48782. handleMixinUpdate: {
  48783. value: function () {
  48784. var data = {};
  48785. var elData;
  48786. var mixinData;
  48787. var mixinEl;
  48788. // Get mixin data.
  48789. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  48790. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  48791. elData = utils.getElData(this, DEFAULTS);
  48792. utils.extend(data, DEFAULTS, mixinData, elData);
  48793. this.data = data;
  48794. }
  48795. }
  48796. })
  48797. });
  48798. function cloneValue (val) {
  48799. return utils.extend({}, val);
  48800. }
  48801. /**
  48802. * Deduces different animation values based on whether we are:
  48803. * - animating an inner attribute of a component.
  48804. * - animating a coordinate component.
  48805. * - animating a boolean.
  48806. * - animating a number.
  48807. *
  48808. * @param {Element} el
  48809. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  48810. * @param {string} dataFrom - Data `from` value.
  48811. * @param {string} dataTo - Data `to` value.
  48812. * @param currentValue
  48813. * @returns {object}
  48814. * Object with keys [from, to, partialSetAttribute].
  48815. * `from` and `to`
  48816. * Objects where key is attribute being animated and value is value.
  48817. * `partialSetAttribute`
  48818. * Closured-function that tells tween how to update the component.
  48819. */
  48820. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  48821. var attributeSplit = attribute.split('.');
  48822. var schema;
  48823. var component;
  48824. var componentPropName;
  48825. var componentName;
  48826. var from = {};
  48827. var partialSetAttribute;
  48828. var to = {};
  48829. if (attributeSplit.length === 2) {
  48830. if (isColor()) {
  48831. getForColorComponent();
  48832. } else {
  48833. getForComponentAttribute();
  48834. }
  48835. } else if (dataTo && isCoordinates(dataTo)) {
  48836. getForCoordinateComponent();
  48837. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  48838. getForBoolean();
  48839. } else if (isNaN(dataTo)) {
  48840. getForColorComponent();
  48841. } else {
  48842. getForNumber();
  48843. }
  48844. return {
  48845. from: from,
  48846. partialSetAttribute: partialSetAttribute,
  48847. to: to
  48848. };
  48849. /**
  48850. * Match the schema type to color
  48851. * @return {bool} if the schema is of type color
  48852. */
  48853. function isColor () {
  48854. var componentName = attributeSplit[0];
  48855. var propertyName = attributeSplit[1];
  48856. var component = el.components[componentName];
  48857. var schema = component && component.schema;
  48858. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  48859. }
  48860. /**
  48861. * Animating a component that has multiple attributes (e.g., geometry.width).
  48862. */
  48863. function getForComponentAttribute () {
  48864. componentName = attributeSplit[0];
  48865. componentPropName = attributeSplit[1];
  48866. component = el.components[componentName];
  48867. if (!component) {
  48868. el.setAttribute(componentName, '');
  48869. component = el.components[componentName];
  48870. }
  48871. schema = component.schema;
  48872. if (dataFrom === undefined) { // dataFrom can be 0.
  48873. from[attribute] = getComponentProperty(el, attribute);
  48874. } else {
  48875. from[attribute] = dataFrom;
  48876. }
  48877. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  48878. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  48879. partialSetAttribute = function (value) {
  48880. if (!(attribute in value)) { return; }
  48881. el.setAttribute(componentName, componentPropName, value[attribute]);
  48882. };
  48883. }
  48884. /**
  48885. * Animating a component that is an XYZ coordinate (e.g., position).
  48886. * Will be tweening {x, y, z} all at once.
  48887. */
  48888. function getForCoordinateComponent () {
  48889. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  48890. to = coordinates.parse(dataTo);
  48891. partialSetAttribute = function (value) {
  48892. el.setAttribute(attribute, value);
  48893. };
  48894. }
  48895. /**
  48896. * Animation a boolean (e.g., visible).
  48897. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  48898. */
  48899. function getForBoolean () {
  48900. if (dataFrom === undefined) {
  48901. from[attribute] = false;
  48902. } else {
  48903. from[attribute] = strToBool(dataFrom);
  48904. }
  48905. from[attribute] = boolToNum(from[attribute]);
  48906. to[attribute] = boolToNum(strToBool(dataTo));
  48907. partialSetAttribute = function (value) {
  48908. el.setAttribute(attribute, !!value[attribute]);
  48909. };
  48910. }
  48911. /**
  48912. * Animating a color component
  48913. * Will convert a hex value to a THREE.Color
  48914. * Then converts to hex for the setAttribute
  48915. */
  48916. function getForColorComponent () {
  48917. from = new THREE.Color(dataFrom || el.getAttribute(attribute));
  48918. to = new THREE.Color(dataTo);
  48919. partialSetAttribute = function (value) {
  48920. if (attributeSplit.length > 1) {
  48921. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  48922. }
  48923. el.setAttribute(attribute, rgbVectorToHex(value));
  48924. };
  48925. }
  48926. /**
  48927. * Animating a numbered attribute (e.g., opacity).
  48928. */
  48929. function getForNumber () {
  48930. if (dataFrom === undefined) { // dataFrom can be 0.
  48931. from[attribute] = parseFloat(el.getAttribute(attribute));
  48932. } else {
  48933. from[attribute] = parseFloat(dataFrom);
  48934. }
  48935. to[attribute] = parseFloat(dataTo);
  48936. partialSetAttribute = function (value) {
  48937. el.setAttribute(attribute, value[attribute]);
  48938. };
  48939. }
  48940. }
  48941. module.exports.getAnimationValues = getAnimationValues;
  48942. /**
  48943. * Converts string to bool.
  48944. *
  48945. * @param {string} str - `true` or `false`.
  48946. * @returns {bool}
  48947. */
  48948. function strToBool (str) {
  48949. if (str === 'true') { return true; }
  48950. return false;
  48951. }
  48952. /**
  48953. * Converts boolean to number.
  48954. *
  48955. * @param {bool}
  48956. * @returns {number}
  48957. */
  48958. function boolToNum (bool) {
  48959. return bool ? 1 : 0;
  48960. }
  48961. /**
  48962. * Converts a number 0-255 to hex
  48963. * @param {number} color number 0 - 255
  48964. * @returns {string} hex value of number bassed
  48965. */
  48966. function componentToHex (color) {
  48967. var hex = color.toString(16);
  48968. return hex.length === 1 ? '0' + hex : hex;
  48969. }
  48970. /**
  48971. * Clamps a number to 0-1
  48972. * Then converts that number to 0-255
  48973. * @param {number} color number 0 - 1
  48974. * @returns {number} color number 0 - 255
  48975. */
  48976. function convertToIntegerColor (color) {
  48977. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  48978. }
  48979. /**
  48980. * Converts a rgb object into a hex string
  48981. * @param {object} color { r: 1, g: 1, b: 1 }
  48982. * @returns {string} hex value #ffffff
  48983. */
  48984. function rgbVectorToHex (color) {
  48985. return '#' + ['r', 'g', 'b'].map(function (prop) {
  48986. return componentToHex(convertToIntegerColor(color[prop]));
  48987. }).join('');
  48988. }
  48989. },{"../constants/animation":116,"../lib/three":174,"../utils/":196,"./a-node":124,"./a-register-element":125,"./schema":134,"@tweenjs/tween.js":1}],120:[function(_dereq_,module,exports){
  48990. var ANode = _dereq_('./a-node');
  48991. var bind = _dereq_('../utils/bind');
  48992. var debug = _dereq_('../utils/debug');
  48993. var registerElement = _dereq_('./a-register-element').registerElement;
  48994. var THREE = _dereq_('../lib/three');
  48995. var fileLoader = new THREE.FileLoader();
  48996. var warn = debug('core:a-assets:warn');
  48997. /**
  48998. * Asset management system. Handles blocking on asset loading.
  48999. */
  49000. module.exports = registerElement('a-assets', {
  49001. prototype: Object.create(ANode.prototype, {
  49002. createdCallback: {
  49003. value: function () {
  49004. this.isAssets = true;
  49005. this.fileLoader = fileLoader;
  49006. this.timeout = null;
  49007. }
  49008. },
  49009. attachedCallback: {
  49010. value: function () {
  49011. var self = this;
  49012. var i;
  49013. var loaded = [];
  49014. var mediaEl;
  49015. var mediaEls;
  49016. var imgEl;
  49017. var imgEls;
  49018. var timeout;
  49019. if (!this.parentNode.isScene) {
  49020. throw new Error('<a-assets> must be a child of a <a-scene>.');
  49021. }
  49022. // Wait for <img>s.
  49023. imgEls = this.querySelectorAll('img');
  49024. for (i = 0; i < imgEls.length; i++) {
  49025. imgEl = fixUpMediaElement(imgEls[i]);
  49026. loaded.push(new Promise(function (resolve, reject) {
  49027. // Set in cache because we won't be needing to call three.js loader if we have.
  49028. // a loaded media element.
  49029. THREE.Cache.files[imgEls[i].getAttribute('src')] = imgEl;
  49030. imgEl.onload = resolve;
  49031. imgEl.onerror = reject;
  49032. }));
  49033. }
  49034. // Wait for <audio>s and <video>s.
  49035. mediaEls = this.querySelectorAll('audio, video');
  49036. for (i = 0; i < mediaEls.length; i++) {
  49037. mediaEl = fixUpMediaElement(mediaEls[i]);
  49038. if (!mediaEl.src && !mediaEl.srcObject) {
  49039. warn('Audio/video asset has neither `src` nor `srcObject` attributes.');
  49040. }
  49041. loaded.push(mediaElementLoaded(mediaEl));
  49042. }
  49043. // Trigger loaded for scene to start rendering.
  49044. Promise.all(loaded).then(bind(this.load, this));
  49045. // Timeout to start loading anyways.
  49046. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  49047. this.timeout = setTimeout(function () {
  49048. if (self.hasLoaded) { return; }
  49049. warn('Asset loading timed out in ', timeout, 'ms');
  49050. self.emit('timeout');
  49051. self.load();
  49052. }, timeout);
  49053. }
  49054. },
  49055. detachedCallback: {
  49056. value: function () {
  49057. if (this.timeout) { clearTimeout(this.timeout); }
  49058. }
  49059. },
  49060. load: {
  49061. value: function () {
  49062. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  49063. return el.isAssetItem && el.hasAttribute('src');
  49064. });
  49065. }
  49066. }
  49067. })
  49068. });
  49069. /**
  49070. * Preload using XHRLoader for any type of asset.
  49071. */
  49072. registerElement('a-asset-item', {
  49073. prototype: Object.create(ANode.prototype, {
  49074. createdCallback: {
  49075. value: function () {
  49076. this.data = null;
  49077. this.isAssetItem = true;
  49078. }
  49079. },
  49080. attachedCallback: {
  49081. value: function () {
  49082. var self = this;
  49083. var src = this.getAttribute('src');
  49084. fileLoader.setResponseType(
  49085. this.getAttribute('response-type') || inferResponseType(src));
  49086. fileLoader.load(src, function handleOnLoad (response) {
  49087. self.data = response;
  49088. /*
  49089. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  49090. previous one closes, the second request never finishes.
  49091. setTimeout finishes the first request and lets the logic triggered by load open
  49092. subsequent requests.
  49093. setTimeout can be removed once the fix for the bug below ships:
  49094. 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
  49095. */
  49096. setTimeout(function load () { ANode.prototype.load.call(self); });
  49097. }, function handleOnProgress (xhr) {
  49098. self.emit('progress', {
  49099. loadedBytes: xhr.loaded,
  49100. totalBytes: xhr.total,
  49101. xhr: xhr
  49102. });
  49103. }, function handleOnError (xhr) {
  49104. self.emit('error', {xhr: xhr});
  49105. });
  49106. }
  49107. }
  49108. })
  49109. });
  49110. /**
  49111. * Create a Promise that resolves once the media element has finished buffering.
  49112. *
  49113. * @param {Element} el - HTMLMediaElement.
  49114. * @returns {Promise}
  49115. */
  49116. function mediaElementLoaded (el) {
  49117. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  49118. return;
  49119. }
  49120. // If media specifies autoplay or preload, wait until media is completely buffered.
  49121. return new Promise(function (resolve, reject) {
  49122. if (el.readyState === 4) { return resolve(); } // Already loaded.
  49123. if (el.error) { return reject(); } // Error.
  49124. el.addEventListener('loadeddata', checkProgress, false);
  49125. el.addEventListener('progress', checkProgress, false);
  49126. el.addEventListener('error', reject, false);
  49127. function checkProgress () {
  49128. // Add up the seconds buffered.
  49129. var secondsBuffered = 0;
  49130. for (var i = 0; i < el.buffered.length; i++) {
  49131. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  49132. }
  49133. // Compare seconds buffered to media duration.
  49134. if (secondsBuffered >= el.duration) {
  49135. // Set in cache because we won't be needing to call three.js loader if we have.
  49136. // a loaded media element.
  49137. THREE.Cache.files[el.getAttribute('src')] = el;
  49138. resolve();
  49139. }
  49140. }
  49141. });
  49142. }
  49143. /**
  49144. * Automatically add attributes to media elements where convenient.
  49145. * crossorigin, playsinline.
  49146. */
  49147. function fixUpMediaElement (mediaEl) {
  49148. // Cross-origin.
  49149. var newMediaEl = setCrossOrigin(mediaEl);
  49150. // Plays inline for mobile.
  49151. if (newMediaEl.tagName && newMediaEl.tagName.toLowerCase() === 'video') {
  49152. newMediaEl.setAttribute('playsinline', '');
  49153. newMediaEl.setAttribute('webkit-playsinline', '');
  49154. }
  49155. if (newMediaEl !== mediaEl) {
  49156. mediaEl.parentNode.appendChild(newMediaEl);
  49157. mediaEl.parentNode.removeChild(mediaEl);
  49158. }
  49159. return newMediaEl;
  49160. }
  49161. /**
  49162. * Automatically set `crossorigin` if not defined on the media element.
  49163. * If it is not defined, we must create and re-append a new media element <img> and
  49164. * have the browser re-request it with `crossorigin` set.
  49165. *
  49166. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  49167. * @returns {Element} Media element to be used to listen to for loaded events.
  49168. */
  49169. function setCrossOrigin (mediaEl) {
  49170. var newMediaEl;
  49171. var src;
  49172. // Already has crossorigin set.
  49173. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  49174. src = mediaEl.getAttribute('src');
  49175. if (src !== null) {
  49176. // Does not have protocol.
  49177. if (src.indexOf('://') === -1) { return mediaEl; }
  49178. // Determine if cross origin is actually needed.
  49179. if (extractDomain(src) === window.location.host) { return mediaEl; }
  49180. }
  49181. warn('Cross-origin element (e.g., <img>) was requested without `crossorigin` set. ' +
  49182. 'A-Frame will re-request the asset with `crossorigin` attribute set. ' +
  49183. 'Please set `crossorigin` on the element (e.g., <img crossorigin="anonymous">)', src);
  49184. mediaEl.crossOrigin = 'anonymous';
  49185. newMediaEl = mediaEl.cloneNode(true);
  49186. return newMediaEl;
  49187. }
  49188. /**
  49189. * Extract domain out of URL.
  49190. *
  49191. * @param {string} url
  49192. * @returns {string}
  49193. */
  49194. function extractDomain (url) {
  49195. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  49196. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  49197. // Find and remove port number.
  49198. return domain.substring(0, domain.indexOf(':'));
  49199. }
  49200. /**
  49201. * Infer response-type attribute from src.
  49202. * Default is text(default XMLHttpRequest.responseType)
  49203. * but we use arraybuffer for .gltf and .glb files
  49204. * because of THREE.GLTFLoader specification.
  49205. *
  49206. * @param {string} src
  49207. * @returns {string}
  49208. */
  49209. function inferResponseType (src) {
  49210. var dotLastIndex = src.lastIndexOf('.');
  49211. if (dotLastIndex >= 0) {
  49212. var extension = src.slice(dotLastIndex, src.length);
  49213. if (extension === '.gltf' || extension === '.glb') {
  49214. return 'arraybuffer';
  49215. }
  49216. }
  49217. return 'text';
  49218. }
  49219. module.exports.inferResponseType = inferResponseType;
  49220. },{"../lib/three":174,"../utils/bind":190,"../utils/debug":192,"./a-node":124,"./a-register-element":125}],121:[function(_dereq_,module,exports){
  49221. var debug = _dereq_('../utils/debug');
  49222. var registerElement = _dereq_('./a-register-element').registerElement;
  49223. var warn = debug('core:cubemap:warn');
  49224. /**
  49225. * Cubemap element that handles validation and exposes list of URLs.
  49226. * Does not listen to updates.
  49227. */
  49228. module.exports = registerElement('a-cubemap', {
  49229. prototype: Object.create(window.HTMLElement.prototype, {
  49230. /**
  49231. * Calculates this.srcs.
  49232. */
  49233. attachedCallback: {
  49234. value: function () {
  49235. this.srcs = this.validate();
  49236. },
  49237. writable: window.debug
  49238. },
  49239. /**
  49240. * Checks for exactly six elements with [src].
  49241. * Does not check explicitly for <img>s in case user does not want
  49242. * prefetching.
  49243. *
  49244. * @returns {Array|null} - six URLs if valid, else null.
  49245. */
  49246. validate: {
  49247. value: function () {
  49248. var elements = this.querySelectorAll('[src]');
  49249. var i;
  49250. var srcs = [];
  49251. if (elements.length === 6) {
  49252. for (i = 0; i < elements.length; i++) {
  49253. srcs.push(elements[i].getAttribute('src'));
  49254. }
  49255. return srcs;
  49256. }
  49257. // Else if there are not six elements, throw a warning.
  49258. warn(
  49259. '<a-cubemap> did not contain exactly six elements each with a ' +
  49260. '`src` attribute.');
  49261. },
  49262. writable: window.debug
  49263. }
  49264. })
  49265. });
  49266. },{"../utils/debug":192,"./a-register-element":125}],122:[function(_dereq_,module,exports){
  49267. var ANode = _dereq_('./a-node');
  49268. var COMPONENTS = _dereq_('./component').components;
  49269. var registerElement = _dereq_('./a-register-element').registerElement;
  49270. var THREE = _dereq_('../lib/three');
  49271. var utils = _dereq_('../utils/');
  49272. var AEntity;
  49273. var debug = utils.debug('core:a-entity:debug');
  49274. var warn = utils.debug('core:a-entity:warn');
  49275. var MULTIPLE_COMPONENT_DELIMITER = '__';
  49276. /**
  49277. * Entity is a container object that components are plugged into to comprise everything in
  49278. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  49279. *
  49280. * To be able to take components, the scene element inherits from the entity definition.
  49281. *
  49282. * @member {object} components - entity's currently initialized components.
  49283. * @member {object} object3D - three.js object.
  49284. * @member {array} states
  49285. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  49286. */
  49287. var proto = Object.create(ANode.prototype, {
  49288. defaultComponents: {
  49289. value: {
  49290. position: '',
  49291. rotation: '',
  49292. scale: '',
  49293. visible: ''
  49294. }
  49295. },
  49296. createdCallback: {
  49297. value: function () {
  49298. this.components = {};
  49299. // To avoid double initializations and infinite loops.
  49300. this.initializingComponents = {};
  49301. this.componentsToUpdate = {};
  49302. this.isEntity = true;
  49303. this.isPlaying = false;
  49304. this.object3D = new THREE.Group();
  49305. this.object3D.el = this;
  49306. this.object3DMap = {};
  49307. this.parentEl = null;
  49308. this.rotationObj = {};
  49309. this.states = [];
  49310. }
  49311. },
  49312. /**
  49313. * Handle changes coming from the browser DOM inspector.
  49314. */
  49315. attributeChangedCallback: {
  49316. value: function (attr, oldVal, newVal) {
  49317. var component = this.components[attr];
  49318. // If the empty string is passed by the component initialization
  49319. // logic we ignore the component update.
  49320. if (component && component.justInitialized && newVal === '') {
  49321. delete component.justInitialized;
  49322. return;
  49323. }
  49324. // When a component is removed after calling el.removeAttribute('material')
  49325. if (!component && newVal === null) { return; }
  49326. this.setEntityAttribute(attr, oldVal, newVal);
  49327. }
  49328. },
  49329. /**
  49330. * Add to parent, load, play.
  49331. */
  49332. attachedCallback: {
  49333. value: function () {
  49334. var assetsEl; // Asset management system element.
  49335. var sceneEl = this.sceneEl;
  49336. var self = this; // Component.
  49337. this.addToParent();
  49338. // Don't .load() scene on attachedCallback.
  49339. if (this.isScene) { return; }
  49340. // Gracefully not error when outside of <a-scene> (e.g., tests).
  49341. if (!sceneEl) {
  49342. this.load();
  49343. return;
  49344. }
  49345. // Wait for asset management system to finish before loading.
  49346. assetsEl = sceneEl.querySelector('a-assets');
  49347. if (assetsEl && !assetsEl.hasLoaded) {
  49348. assetsEl.addEventListener('loaded', function () { self.load(); });
  49349. return;
  49350. }
  49351. this.load();
  49352. }
  49353. },
  49354. /**
  49355. * Tell parent to remove this element's object3D from its object3D.
  49356. * Do not call on scene element because that will cause a call to document.body.remove().
  49357. */
  49358. detachedCallback: {
  49359. value: function () {
  49360. var componentName;
  49361. if (!this.parentEl) { return; }
  49362. // Remove components.
  49363. for (componentName in this.components) { this.removeComponent(componentName); }
  49364. if (this.isScene) { return; }
  49365. this.removeFromParent();
  49366. ANode.prototype.detachedCallback.call(this);
  49367. // Remove cyclic reference.
  49368. this.object3D.el = null;
  49369. }
  49370. },
  49371. /**
  49372. * Apply mixin to component.
  49373. */
  49374. handleMixinUpdate: {
  49375. value: function (attrName) {
  49376. if (!attrName) {
  49377. this.updateComponents();
  49378. return;
  49379. }
  49380. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  49381. }
  49382. },
  49383. getObject3D: {
  49384. value: function (type) {
  49385. return this.object3DMap[type];
  49386. }
  49387. },
  49388. /**
  49389. * Set a THREE.Object3D into the map.
  49390. *
  49391. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  49392. * @param {object} obj - A THREE.Object3D.
  49393. */
  49394. setObject3D: {
  49395. value: function (type, obj) {
  49396. var oldObj;
  49397. var self = this;
  49398. if (!(obj instanceof THREE.Object3D)) {
  49399. throw new Error(
  49400. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  49401. 'THREE.Object3D.'
  49402. );
  49403. }
  49404. // Remove existing object of the type.
  49405. oldObj = this.getObject3D(type);
  49406. if (oldObj) { this.object3D.remove(oldObj); }
  49407. // Set references to A-Frame entity.
  49408. obj.el = this;
  49409. if (obj.children.length) {
  49410. obj.traverse(function bindEl (child) {
  49411. child.el = self;
  49412. });
  49413. }
  49414. // Add.
  49415. this.object3D.add(obj);
  49416. this.object3DMap[type] = obj;
  49417. this.emit('object3dset', {object: obj, type: type});
  49418. }
  49419. },
  49420. /**
  49421. * Remove object from scene and entity object3D map.
  49422. */
  49423. removeObject3D: {
  49424. value: function (type) {
  49425. var obj = this.getObject3D(type);
  49426. if (!obj) {
  49427. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  49428. return;
  49429. }
  49430. this.object3D.remove(obj);
  49431. delete this.object3DMap[type];
  49432. this.emit('object3dremove', {type: type});
  49433. }
  49434. },
  49435. /**
  49436. * Gets or creates an object3D of a given type.
  49437. *
  49438. * @param {string} type - Type of the object3D.
  49439. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  49440. * @returns {object}
  49441. */
  49442. getOrCreateObject3D: {
  49443. value: function (type, Constructor) {
  49444. var object3D = this.getObject3D(type);
  49445. if (!object3D && Constructor) {
  49446. object3D = new Constructor();
  49447. this.setObject3D(type, object3D);
  49448. }
  49449. warn('`getOrCreateObject3D` has been deprecated. Use `setObject3D()` ' +
  49450. 'and `object3dset` event instead.');
  49451. return object3D;
  49452. }
  49453. },
  49454. /**
  49455. * Add child entity.
  49456. *
  49457. * @param {Element} el - Child entity.
  49458. */
  49459. add: {
  49460. value: function (el) {
  49461. if (!el.object3D) {
  49462. throw new Error("Trying to add an element that doesn't have an `object3D`");
  49463. }
  49464. this.object3D.add(el.object3D);
  49465. this.emit('child-attached', {el: el});
  49466. }
  49467. },
  49468. /**
  49469. * Tell parentNode to add this entity to itself.
  49470. */
  49471. addToParent: {
  49472. value: function () {
  49473. var parentNode = this.parentEl = this.parentNode;
  49474. // `!parentNode` check primarily for unit tests.
  49475. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  49476. parentNode.add(this);
  49477. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  49478. }
  49479. },
  49480. /**
  49481. * Tell parentNode to remove this entity from itself.
  49482. */
  49483. removeFromParent: {
  49484. value: function () {
  49485. var parentEl = this.parentEl;
  49486. this.parentEl.remove(this);
  49487. this.attachedToParent = false;
  49488. this.parentEl = this.parentNode = null;
  49489. parentEl.emit('child-detached', {el: this});
  49490. }
  49491. },
  49492. load: {
  49493. value: function () {
  49494. var self = this;
  49495. if (this.hasLoaded || !this.parentEl) { return; }
  49496. ANode.prototype.load.call(this, function entityLoadCallback () {
  49497. // Check if entity was detached while it was waiting to load.
  49498. if (!self.parentEl) { return; }
  49499. self.updateComponents();
  49500. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  49501. });
  49502. },
  49503. writable: window.debug
  49504. },
  49505. /**
  49506. * Remove child entity.
  49507. *
  49508. * @param {Element} el - Child entity.
  49509. */
  49510. remove: {
  49511. value: function (el) {
  49512. this.object3D.remove(el.object3D);
  49513. }
  49514. },
  49515. /**
  49516. * @returns {array} Direct children that are entities.
  49517. */
  49518. getChildEntities: {
  49519. value: function () {
  49520. var children = this.children;
  49521. var childEntities = [];
  49522. for (var i = 0; i < children.length; i++) {
  49523. var child = children[i];
  49524. if (child instanceof AEntity) {
  49525. childEntities.push(child);
  49526. }
  49527. }
  49528. return childEntities;
  49529. }
  49530. },
  49531. /**
  49532. * Initialize component.
  49533. *
  49534. * @param {string} attrName - Attribute name asociated to the component.
  49535. * @param {object} data - Component data
  49536. * @param {boolean} isDependency - True if the component is a dependency.
  49537. */
  49538. initComponent: {
  49539. value: function (attrName, data, isDependency) {
  49540. var component;
  49541. var componentId;
  49542. var componentInfo;
  49543. var componentName;
  49544. var isComponentDefined;
  49545. componentInfo = utils.split(attrName, MULTIPLE_COMPONENT_DELIMITER);
  49546. componentId = componentInfo[1];
  49547. componentName = componentInfo[0];
  49548. // Not a registered component.
  49549. if (!COMPONENTS[componentName]) { return; }
  49550. // Component is not a dependency and is undefined.
  49551. // If a component is a dependency, then it is okay to have no data.
  49552. isComponentDefined = checkComponentDefined(this, attrName) ||
  49553. data !== undefined;
  49554. if (!isComponentDefined && !isDependency) { return; }
  49555. // Component already initialized.
  49556. if (attrName in this.components) { return; }
  49557. // Initialize dependencies first
  49558. this.initComponentDependencies(componentName);
  49559. // If component name has an id we check component type multiplic
  49560. if (componentId && !COMPONENTS[componentName].multiple) {
  49561. throw new Error('Trying to initialize multiple ' +
  49562. 'components of type `' + componentName +
  49563. '`. There can only be one component of this type per entity.');
  49564. }
  49565. component = new COMPONENTS[componentName].Component(this, data, componentId);
  49566. if (this.isPlaying) { component.play(); }
  49567. // Components are reflected in the DOM as attributes but the state is not shown
  49568. // hence we set the attribute to empty string.
  49569. // The flag justInitialized is for attributeChangedCallback to not overwrite
  49570. // the component with the empty string.
  49571. if (!this.hasAttribute(attrName)) {
  49572. component.justInitialized = true;
  49573. window.HTMLElement.prototype.setAttribute.call(this, attrName, '');
  49574. }
  49575. debug('Component initialized: %s', attrName);
  49576. },
  49577. writable: window.debug
  49578. },
  49579. /**
  49580. * Initialize dependencies of a component.
  49581. *
  49582. * @param {string} name - Root component name.
  49583. */
  49584. initComponentDependencies: {
  49585. value: function (name) {
  49586. var self = this;
  49587. var component = COMPONENTS[name];
  49588. var dependencies;
  49589. var i;
  49590. // Not a component.
  49591. if (!component) { return; }
  49592. // No dependencies.
  49593. dependencies = COMPONENTS[name].dependencies;
  49594. if (!dependencies) { return; }
  49595. // Initialize dependencies.
  49596. for (i = 0; i < dependencies.length; i++) {
  49597. // Call getAttribute to initialize the data from the DOM.
  49598. self.initComponent(
  49599. dependencies[i],
  49600. window.HTMLElement.prototype.getAttribute.call(self, dependencies[i]) || undefined,
  49601. true
  49602. );
  49603. }
  49604. }
  49605. },
  49606. removeComponent: {
  49607. value: function (name) {
  49608. var component;
  49609. var isDefault;
  49610. // Don't remove default or mixed-in components.
  49611. isDefault = name in this.defaultComponents;
  49612. if (isDefault) { return; }
  49613. component = this.components[name];
  49614. if (!component) { return; }
  49615. // Wait for component to initialize.
  49616. if (!component.initialized) {
  49617. this.addEventListener('componentinitialized', function tryRemoveLater (evt) {
  49618. if (evt.detail.name !== name) { return; }
  49619. this.removeComponent(name);
  49620. this.removeEventListener('componentinitialized', tryRemoveLater);
  49621. });
  49622. return;
  49623. }
  49624. component.pause();
  49625. component.remove();
  49626. delete this.components[name];
  49627. this.emit('componentremoved', component.evtDetail);
  49628. },
  49629. writable: window.debug
  49630. },
  49631. /**
  49632. * Initialize or update all components.
  49633. * Build data using initial components, defined attributes, mixins, and defaults.
  49634. * Update default components before the rest.
  49635. *
  49636. * @member {function} getExtraComponents - Can be implemented to include component data
  49637. * from other sources (e.g., implemented by primitives).
  49638. */
  49639. updateComponents: {
  49640. value: function () {
  49641. var data;
  49642. var extraComponents;
  49643. var i;
  49644. var name;
  49645. var componentsToUpdate = this.componentsToUpdate;
  49646. if (!this.hasLoaded) { return; }
  49647. // Gather mixin-defined components.
  49648. for (i = 0; i < this.mixinEls.length; i++) {
  49649. for (name in this.mixinEls[i].componentCache) {
  49650. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49651. }
  49652. }
  49653. // Gather from extra initial component data if defined (e.g., primitives).
  49654. if (this.getExtraComponents) {
  49655. extraComponents = this.getExtraComponents();
  49656. for (name in extraComponents) {
  49657. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49658. }
  49659. }
  49660. // Gather entity-defined components.
  49661. for (i = 0; i < this.attributes.length; ++i) {
  49662. name = this.attributes[i].name;
  49663. if (isComponent(name)) { componentsToUpdate[name] = true; }
  49664. }
  49665. // Initialze or update default components first.
  49666. for (name in this.defaultComponents) {
  49667. data = mergeComponentData(this.getDOMAttribute(name),
  49668. extraComponents && extraComponents[name]);
  49669. this.updateComponent(name, data);
  49670. delete componentsToUpdate[name];
  49671. }
  49672. // Initialize or update rest of components.
  49673. for (name in componentsToUpdate) {
  49674. data = mergeComponentData(this.getDOMAttribute(name),
  49675. extraComponents && extraComponents[name]);
  49676. this.updateComponent(name, data);
  49677. delete componentsToUpdate[name];
  49678. }
  49679. },
  49680. writable: window.debug
  49681. },
  49682. /**
  49683. * Initialize, update, or remove a single component.
  49684. *
  49685. * When initializing, we set the component on `this.components`.
  49686. *
  49687. * @param {string} attr - Component name.
  49688. * @param {object} attrValue - Value of the DOM attribute.
  49689. * @param {boolean} clobber - If new attrValue completely replaces previous properties.
  49690. */
  49691. updateComponent: {
  49692. value: function (attr, attrValue, clobber) {
  49693. var component = this.components[attr];
  49694. var isDefault = attr in this.defaultComponents;
  49695. if (component) {
  49696. // Remove component.
  49697. if (attrValue === null && !isDefault) {
  49698. this.removeComponent(attr);
  49699. return;
  49700. }
  49701. // Component already initialized. Update component.
  49702. component.updateProperties(attrValue, clobber);
  49703. return;
  49704. }
  49705. // Component not yet initialized. Initialize component.
  49706. this.initComponent(attr, attrValue, false);
  49707. }
  49708. },
  49709. /**
  49710. * If `attr` is a component name, detach the component from the entity.
  49711. *
  49712. * If `propertyName` is given, reset the component property value to its default.
  49713. *
  49714. * @param {string} attr - Attribute name, which could also be a component name.
  49715. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  49716. */
  49717. removeAttribute: {
  49718. value: function (attr, propertyName) {
  49719. var component = this.components[attr];
  49720. // Remove component.
  49721. if (component && propertyName === undefined) {
  49722. this.removeComponent(attr);
  49723. // Do not remove the component from the DOM if default component.
  49724. if (this.components[attr]) { return; }
  49725. }
  49726. // Reset component property value.
  49727. if (component && propertyName !== undefined) {
  49728. component.resetProperty(propertyName);
  49729. return;
  49730. }
  49731. // Remove mixins.
  49732. if (attr === 'mixin') {
  49733. this.mixinUpdate('');
  49734. }
  49735. window.HTMLElement.prototype.removeAttribute.call(this, attr);
  49736. }
  49737. },
  49738. /**
  49739. * Start dynamic behavior associated with entity such as dynamic components and animations.
  49740. * Tell all children entities to also play.
  49741. */
  49742. play: {
  49743. value: function () {
  49744. var entities;
  49745. var i;
  49746. var key;
  49747. // Already playing.
  49748. if (this.isPlaying || !this.hasLoaded) { return; }
  49749. this.isPlaying = true;
  49750. // Wake up all components.
  49751. for (key in this.components) { this.components[key].play(); }
  49752. // Tell all child entities to play.
  49753. entities = this.getChildEntities();
  49754. for (i = 0; i < entities.length; i++) { entities[i].play(); }
  49755. this.emit('play');
  49756. },
  49757. writable: true
  49758. },
  49759. /**
  49760. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  49761. * Tell all children entities to also pause.
  49762. */
  49763. pause: {
  49764. value: function () {
  49765. var entities;
  49766. var i;
  49767. var key;
  49768. if (!this.isPlaying) { return; }
  49769. this.isPlaying = false;
  49770. // Sleep all components.
  49771. for (key in this.components) { this.components[key].pause(); }
  49772. // Tell all child entities to pause.
  49773. entities = this.getChildEntities();
  49774. for (i = 0; i < entities.length; i++) { entities[i].pause(); }
  49775. this.emit('pause');
  49776. },
  49777. writable: true
  49778. },
  49779. /**
  49780. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  49781. *
  49782. * @param {string} attr
  49783. * @param {string} oldVal
  49784. * @param {string|object} newVal
  49785. */
  49786. setEntityAttribute: {
  49787. value: function (attr, oldVal, newVal) {
  49788. if (COMPONENTS[attr] || this.components[attr]) {
  49789. this.updateComponent(attr, newVal);
  49790. return;
  49791. }
  49792. if (attr === 'mixin') {
  49793. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  49794. if (newVal === this.computedMixinStr) { return; }
  49795. this.mixinUpdate(newVal, oldVal);
  49796. }
  49797. }
  49798. },
  49799. mixinUpdate: {
  49800. value: function (newMixins, oldMixins) {
  49801. oldMixins = oldMixins || this.getAttribute('mixin');
  49802. this.updateMixins(newMixins, oldMixins);
  49803. this.updateComponents();
  49804. }
  49805. },
  49806. /**
  49807. * setAttribute can:
  49808. *
  49809. * 1. Set a single property of a multi-property component.
  49810. * 2. Set multiple properties of a multi-property component.
  49811. * 3. Replace properties of a multi-property component.
  49812. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  49813. *
  49814. * @param {string} attrName - Component or attribute name.
  49815. * @param {*} arg1 - Can be a value, property name, CSS-style property string, or
  49816. * object of properties.
  49817. * @param {*|bool} arg2 - If arg1 is a property name, this should be a value. Otherwise,
  49818. * it is a boolean indicating whether to clobber previous values (defaults to false).
  49819. */
  49820. setAttribute: {
  49821. value: function (attrName, arg1, arg2) {
  49822. var newAttrValue;
  49823. var clobber;
  49824. var componentName;
  49825. var delimiterIndex;
  49826. var isDebugMode;
  49827. delimiterIndex = attrName.indexOf(MULTIPLE_COMPONENT_DELIMITER);
  49828. componentName = delimiterIndex > 0 ? attrName.substring(0, delimiterIndex) : attrName;
  49829. // Not a component. Normal set attribute.
  49830. if (!COMPONENTS[componentName]) {
  49831. if (attrName === 'mixin') { this.mixinUpdate(arg1); }
  49832. ANode.prototype.setAttribute.call(this, attrName, arg1);
  49833. return;
  49834. }
  49835. // Initialize component first if not yet initialized.
  49836. if (!this.components[attrName] && this.hasAttribute(attrName)) {
  49837. this.updateComponent(attrName,
  49838. window.HTMLElement.prototype.getAttribute.call(this, attrName));
  49839. }
  49840. // Determine new attributes from the arguments
  49841. if (typeof arg2 !== 'undefined' &&
  49842. typeof arg1 === 'string' &&
  49843. arg1.length > 0 &&
  49844. typeof utils.styleParser.parse(arg1) === 'string') {
  49845. // Update a single property of a multi-property component
  49846. newAttrValue = {};
  49847. newAttrValue[arg1] = arg2;
  49848. clobber = false;
  49849. } else {
  49850. // Update with a value, object, or CSS-style property string, with the possiblity
  49851. // of clobbering previous values.
  49852. newAttrValue = arg1;
  49853. clobber = (arg2 === true);
  49854. }
  49855. // Update component
  49856. this.updateComponent(attrName, newAttrValue, clobber);
  49857. // In debug mode, write component data up to the DOM.
  49858. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  49859. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  49860. },
  49861. writable: window.debug
  49862. },
  49863. /**
  49864. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  49865. *
  49866. * @param {bool} recursive - Also flushToDOM on the children.
  49867. **/
  49868. flushToDOM: {
  49869. value: function (recursive) {
  49870. var components = this.components;
  49871. var defaultComponents = this.defaultComponents;
  49872. var child;
  49873. var children = this.children;
  49874. var i;
  49875. var key;
  49876. // Flush entity's components to DOM.
  49877. for (key in components) {
  49878. components[key].flushToDOM(key in defaultComponents);
  49879. }
  49880. // Recurse.
  49881. if (!recursive) { return; }
  49882. for (i = 0; i < children.length; ++i) {
  49883. child = children[i];
  49884. if (!child.flushToDOM) { continue; }
  49885. child.flushToDOM(recursive);
  49886. }
  49887. }
  49888. },
  49889. /**
  49890. * If `attr` is a component, returns ALL component data including applied mixins and
  49891. * defaults.
  49892. *
  49893. * If `attr` is not a component, fall back to HTML getAttribute.
  49894. *
  49895. * @param {string} attr
  49896. * @returns {object|string} Object if component, else string.
  49897. */
  49898. getAttribute: {
  49899. value: function (attr) {
  49900. // If component, return component data.
  49901. var component;
  49902. if (attr === 'position') { return this.object3D.position; }
  49903. if (attr === 'rotation') { return getRotation(this); }
  49904. if (attr === 'scale') { return this.object3D.scale; }
  49905. if (attr === 'visible') { return this.object3D.visible; }
  49906. component = this.components[attr];
  49907. if (component) { return component.data; }
  49908. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49909. },
  49910. writable: window.debug
  49911. },
  49912. /**
  49913. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  49914. * what `getAttribute` is now. Now legacy code.
  49915. *
  49916. * @param {string} attr
  49917. * @returns {object|string} Object if component, else string.
  49918. */
  49919. getComputedAttribute: {
  49920. value: function (attr) {
  49921. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  49922. return this.getAttribute(attr);
  49923. }
  49924. },
  49925. /**
  49926. * If `attr` is a component, returns JUST the component data defined on the entity.
  49927. * Like a partial version of `getComputedAttribute` as returned component data
  49928. * does not include applied mixins or defaults.
  49929. *
  49930. * If `attr` is not a component, fall back to HTML getAttribute.
  49931. *
  49932. * @param {string} attr
  49933. * @returns {object|string} Object if component, else string.
  49934. */
  49935. getDOMAttribute: {
  49936. value: function (attr) {
  49937. // If cached value exists, return partial component data.
  49938. var component = this.components[attr];
  49939. if (component) { return component.attrValue; }
  49940. return window.HTMLElement.prototype.getAttribute.call(this, attr);
  49941. },
  49942. writable: window.debug
  49943. },
  49944. addState: {
  49945. value: function (state) {
  49946. if (this.is(state)) { return; }
  49947. this.states.push(state);
  49948. this.emit('stateadded', state);
  49949. }
  49950. },
  49951. removeState: {
  49952. value: function (state) {
  49953. var stateIndex = this.states.indexOf(state);
  49954. if (stateIndex === -1) { return; }
  49955. this.states.splice(stateIndex, 1);
  49956. this.emit('stateremoved', state);
  49957. }
  49958. },
  49959. /**
  49960. * Checks if the element is in a given state. e.g. el.is('alive');
  49961. * @type {string} state - Name of the state we want to check
  49962. */
  49963. is: {
  49964. value: function (state) {
  49965. return this.states.indexOf(state) !== -1;
  49966. }
  49967. }
  49968. });
  49969. /**
  49970. * Check if a component is *defined* for an entity, including defaults and mixins.
  49971. * Does not check whether the component has been *initialized* for an entity.
  49972. *
  49973. * @param {string} el - Entity.
  49974. * @param {string} name - Component name.
  49975. * @returns {boolean}
  49976. */
  49977. function checkComponentDefined (el, name) {
  49978. // Check if default components contain the component.
  49979. if (el.defaultComponents[name] !== undefined) { return true; }
  49980. // Check if element contains the component.
  49981. if (el.components[name] && el.components[name].attrValue) { return true; }
  49982. return isComponentMixedIn(name, el.mixinEls);
  49983. }
  49984. /**
  49985. * Check if any mixins contains a component.
  49986. *
  49987. * @param {string} name - Component name.
  49988. * @param {array} mixinEls - Array of <a-mixin>s.
  49989. */
  49990. function isComponentMixedIn (name, mixinEls) {
  49991. var i;
  49992. var inMixin = false;
  49993. for (i = 0; i < mixinEls.length; ++i) {
  49994. inMixin = mixinEls[i].hasAttribute(name);
  49995. if (inMixin) { break; }
  49996. }
  49997. return inMixin;
  49998. }
  49999. /**
  50000. * Given entity defined value, merge in extra data if necessary.
  50001. * Handle both single and multi-property components.
  50002. *
  50003. * @param {string} attrValue - Entity data.
  50004. * @param extraData - Entity data from another source to merge in.
  50005. */
  50006. function mergeComponentData (attrValue, extraData) {
  50007. // Extra data not defined, just return attrValue.
  50008. if (!extraData) { return attrValue; }
  50009. // Merge multi-property data.
  50010. if (extraData.constructor === Object) {
  50011. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  50012. }
  50013. // Return data, precendence to the defined value.
  50014. return attrValue || extraData;
  50015. }
  50016. function isComponent (componentName) {
  50017. if (componentName.indexOf(MULTIPLE_COMPONENT_DELIMITER) !== -1) {
  50018. componentName = utils.split(componentName, MULTIPLE_COMPONENT_DELIMITER)[0];
  50019. }
  50020. if (!COMPONENTS[componentName]) { return false; }
  50021. return true;
  50022. }
  50023. function getRotation (entityEl) {
  50024. var radToDeg = THREE.Math.radToDeg;
  50025. var rotation = entityEl.object3D.rotation;
  50026. var rotationObj = entityEl.rotationObj;
  50027. rotationObj.x = radToDeg(rotation.x);
  50028. rotationObj.y = radToDeg(rotation.y);
  50029. rotationObj.z = radToDeg(rotation.z);
  50030. return rotationObj;
  50031. }
  50032. AEntity = registerElement('a-entity', {prototype: proto});
  50033. module.exports = AEntity;
  50034. },{"../lib/three":174,"../utils/":196,"./a-node":124,"./a-register-element":125,"./component":126}],123:[function(_dereq_,module,exports){
  50035. var ANode = _dereq_('./a-node');
  50036. var registerElement = _dereq_('./a-register-element').registerElement;
  50037. var components = _dereq_('./component').components;
  50038. var utils = _dereq_('../utils');
  50039. var MULTIPLE_COMPONENT_DELIMITER = '__';
  50040. /**
  50041. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  50042. * are component names and the values are already parsed by the component.
  50043. */
  50044. module.exports = registerElement('a-mixin', {
  50045. prototype: Object.create(ANode.prototype, {
  50046. createdCallback: {
  50047. value: function () {
  50048. this.componentCache = {};
  50049. this.id = this.getAttribute('id');
  50050. this.isMixin = true;
  50051. }
  50052. },
  50053. attributeChangedCallback: {
  50054. value: function (attr, oldVal, newVal) {
  50055. this.cacheAttribute(attr, newVal);
  50056. }
  50057. },
  50058. attachedCallback: {
  50059. value: function () {
  50060. this.sceneEl = this.closestScene();
  50061. this.cacheAttributes();
  50062. this.updateEntities();
  50063. this.load();
  50064. }
  50065. },
  50066. /**
  50067. * setAttribute that parses and caches component values.
  50068. */
  50069. setAttribute: {
  50070. value: function (attr, value) {
  50071. window.HTMLElement.prototype.setAttribute.call(this, attr, value);
  50072. this.cacheAttribute(attr, value);
  50073. }
  50074. },
  50075. /**
  50076. * If `attr` is a component, then parse the value using the schema and store it.
  50077. */
  50078. cacheAttribute: {
  50079. value: function (attr, value) {
  50080. var component;
  50081. var componentName;
  50082. // Get component data.
  50083. componentName = utils.split(attr, MULTIPLE_COMPONENT_DELIMITER)[0];
  50084. component = components[componentName];
  50085. if (!component) { return; }
  50086. if (value === undefined) {
  50087. value = window.HTMLElement.prototype.getAttribute.call(this, attr);
  50088. }
  50089. this.componentCache[attr] = component.parseAttrValueForCache(value);
  50090. }
  50091. },
  50092. /**
  50093. * If `attr` is a component, then grab pre-parsed value from the cache.
  50094. * Else do a normal getAttribute.
  50095. */
  50096. getAttribute: {
  50097. value: function (attr) {
  50098. return this.componentCache[attr] ||
  50099. window.HTMLElement.prototype.getAttribute.call(this, attr);
  50100. }
  50101. },
  50102. /**
  50103. * Parse and cache every component defined on the mixin.
  50104. */
  50105. cacheAttributes: {
  50106. value: function () {
  50107. var attributes = this.attributes;
  50108. var attrName;
  50109. var i;
  50110. for (i = 0; i < attributes.length; i++) {
  50111. attrName = attributes[i].name;
  50112. this.cacheAttribute(attrName);
  50113. }
  50114. }
  50115. },
  50116. /**
  50117. * For entities that already have been loaded by the time the mixin was attached, tell
  50118. * those entities to register the mixin and refresh their component data.
  50119. */
  50120. updateEntities: {
  50121. value: function () {
  50122. var entity;
  50123. var entities;
  50124. var i;
  50125. if (!this.sceneEl) { return; }
  50126. entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  50127. for (i = 0; i < entities.length; i++) {
  50128. entity = entities[i];
  50129. if (!entity.hasLoaded || entity.isMixin) { continue; }
  50130. entity.mixinUpdate(this.id);
  50131. }
  50132. }
  50133. }
  50134. })
  50135. });
  50136. },{"../utils":196,"./a-node":124,"./a-register-element":125,"./component":126}],124:[function(_dereq_,module,exports){
  50137. /* global CustomEvent, MutationObserver */
  50138. var registerElement = _dereq_('./a-register-element').registerElement;
  50139. var isNode = _dereq_('./a-register-element').isNode;
  50140. var utils = _dereq_('../utils/');
  50141. var warn = utils.debug('core:a-node:warn');
  50142. var MIXIN_OBSERVER_CONFIG = {attributes: true};
  50143. /**
  50144. * Base class for A-Frame that manages loading of objects.
  50145. *
  50146. * Nodes can be modified using mixins.
  50147. * Nodes emit a `loaded` event when they and their children have initialized.
  50148. */
  50149. module.exports = registerElement('a-node', {
  50150. prototype: Object.create(window.HTMLElement.prototype, {
  50151. createdCallback: {
  50152. value: function () {
  50153. this.computedMixinStr = '';
  50154. this.hasLoaded = false;
  50155. this.isNode = true;
  50156. this.mixinEls = [];
  50157. this.mixinObservers = {};
  50158. },
  50159. writable: window.debug
  50160. },
  50161. attachedCallback: {
  50162. value: function () {
  50163. var mixins;
  50164. this.sceneEl = this.closestScene();
  50165. if (!this.sceneEl) {
  50166. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  50167. 'scene. Append this element to `<a-scene>` instead.');
  50168. }
  50169. this.hasLoaded = false;
  50170. this.emit('nodeready', undefined, false);
  50171. if (!this.isMixin) {
  50172. mixins = this.getAttribute('mixin');
  50173. if (mixins) { this.updateMixins(mixins); }
  50174. }
  50175. },
  50176. writable: window.debug
  50177. },
  50178. /**
  50179. * Handle mixin.
  50180. */
  50181. attributeChangedCallback: {
  50182. value: function (attr, oldVal, newVal) {
  50183. // Ignore if `<a-node>` code is just updating computed mixin in the DOM.
  50184. if (newVal === this.computedMixinStr) { return; }
  50185. if (attr === 'mixin' && !this.isMixin) {
  50186. this.updateMixins(newVal, oldVal);
  50187. }
  50188. }
  50189. },
  50190. /**
  50191. * Returns the first scene by traversing up the tree starting from and
  50192. * including receiver element.
  50193. */
  50194. closestScene: {
  50195. value: function closest () {
  50196. var element = this;
  50197. while (element) {
  50198. if (element.isScene) { break; }
  50199. element = element.parentElement;
  50200. }
  50201. return element;
  50202. }
  50203. },
  50204. /**
  50205. * Returns first element matching a selector by traversing up the tree starting
  50206. * from and including receiver element.
  50207. *
  50208. * @param {string} selector - Selector of element to find.
  50209. */
  50210. closest: {
  50211. value: function closest (selector) {
  50212. var matches = this.matches || this.mozMatchesSelector ||
  50213. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  50214. var element = this;
  50215. while (element) {
  50216. if (matches.call(element, selector)) { break; }
  50217. element = element.parentElement;
  50218. }
  50219. return element;
  50220. }
  50221. },
  50222. detachedCallback: {
  50223. value: function () {
  50224. this.hasLoaded = false;
  50225. }
  50226. },
  50227. /**
  50228. * Wait for children to load, if any.
  50229. * Then emit `loaded` event and set `hasLoaded`.
  50230. */
  50231. load: {
  50232. value: function (cb, childFilter) {
  50233. var children;
  50234. var childrenLoaded;
  50235. var self = this;
  50236. if (this.hasLoaded) { return; }
  50237. // Default to waiting for all nodes.
  50238. childFilter = childFilter || isNode;
  50239. // Wait for children to load (if any), then load.
  50240. children = this.getChildren();
  50241. childrenLoaded = children.filter(childFilter).map(function (child) {
  50242. return new Promise(function waitForLoaded (resolve) {
  50243. if (child.hasLoaded) { return resolve(); }
  50244. child.addEventListener('loaded', resolve);
  50245. });
  50246. });
  50247. Promise.all(childrenLoaded).then(function emitLoaded () {
  50248. self.hasLoaded = true;
  50249. if (cb) { cb(); }
  50250. self.emit('loaded', undefined, false);
  50251. });
  50252. },
  50253. writable: true
  50254. },
  50255. getChildren: {
  50256. value: function () {
  50257. return Array.prototype.slice.call(this.children, 0);
  50258. }
  50259. },
  50260. /**
  50261. * Unregister old mixins and listeners.
  50262. * Register new mixins and listeners.
  50263. * Registering means to update `this.mixinEls` with listeners.
  50264. */
  50265. updateMixins: {
  50266. value: (function () {
  50267. var newMixinIdArray = [];
  50268. var oldMixinIdArray = [];
  50269. return function (newMixins, oldMixins) {
  50270. var i;
  50271. var newMixinIds;
  50272. var oldMixinIds;
  50273. newMixinIdArray.length = 0;
  50274. oldMixinIdArray.length = 0;
  50275. newMixinIds = newMixins ? utils.split(newMixins.trim(), /\s+/) : newMixinIdArray;
  50276. oldMixinIds = oldMixins ? utils.split(oldMixins.trim(), /\s+/) : oldMixinIdArray;
  50277. // Unregister old mixins.
  50278. for (i = 0; i < oldMixinIds.length; i++) {
  50279. if (newMixinIds.indexOf(oldMixinIds[i]) === -1) {
  50280. this.unregisterMixin(oldMixinIds[i]);
  50281. }
  50282. }
  50283. // Register new mixins.
  50284. this.computedMixinStr = '';
  50285. this.mixinEls.length = 0;
  50286. for (i = 0; i < newMixinIds.length; i++) {
  50287. this.registerMixin(document.getElementById(newMixinIds[i]));
  50288. }
  50289. // Update DOM. Keep track of `computedMixinStr` to not recurse back here after
  50290. // update.
  50291. if (this.computedMixinStr) {
  50292. this.computedMixinStr = this.computedMixinStr.trim();
  50293. window.HTMLElement.prototype.setAttribute.call(this, 'mixin',
  50294. this.computedMixinStr);
  50295. }
  50296. };
  50297. })()
  50298. },
  50299. /**
  50300. * From mixin ID, add mixin element to `mixinEls`.
  50301. *
  50302. * @param {Element} mixinEl
  50303. */
  50304. registerMixin: {
  50305. value: function (mixinEl) {
  50306. var compositedMixinIds;
  50307. var i;
  50308. var mixin;
  50309. if (!mixinEl) { return; }
  50310. // Register composited mixins (if mixin has mixins).
  50311. mixin = mixinEl.getAttribute('mixin');
  50312. if (mixin) {
  50313. compositedMixinIds = utils.split(mixin.trim(), /\s+/);
  50314. for (i = 0; i < compositedMixinIds.length; i++) {
  50315. this.registerMixin(document.getElementById(compositedMixinIds[i]));
  50316. }
  50317. }
  50318. // Register mixin.
  50319. this.computedMixinStr = this.computedMixinStr + ' ' + mixinEl.id;
  50320. this.mixinEls.push(mixinEl);
  50321. this.attachMixinListener(mixinEl);
  50322. }
  50323. },
  50324. setAttribute: {
  50325. value: function (attr, newValue) {
  50326. if (attr === 'mixin') { this.updateMixins(newValue); }
  50327. window.HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  50328. }
  50329. },
  50330. unregisterMixin: {
  50331. value: function (mixinId) {
  50332. var i;
  50333. var mixinEls = this.mixinEls;
  50334. var mixinEl;
  50335. for (i = 0; i < mixinEls.length; ++i) {
  50336. mixinEl = mixinEls[i];
  50337. if (mixinId === mixinEl.id) {
  50338. mixinEls.splice(i, 1);
  50339. break;
  50340. }
  50341. }
  50342. this.removeMixinListener(mixinId);
  50343. }
  50344. },
  50345. removeMixinListener: {
  50346. value: function (mixinId) {
  50347. var observer = this.mixinObservers[mixinId];
  50348. if (!observer) { return; }
  50349. observer.disconnect();
  50350. this.mixinObservers[mixinId] = null;
  50351. }
  50352. },
  50353. /**
  50354. * Add mutation observer from entity to mixin.
  50355. */
  50356. attachMixinListener: {
  50357. value: function (mixinEl) {
  50358. var currentObserver;
  50359. var mixinId;
  50360. var observer;
  50361. var self = this;
  50362. if (!mixinEl) { return; }
  50363. mixinId = mixinEl.id;
  50364. currentObserver = this.mixinObservers[mixinId];
  50365. if (currentObserver) { return; }
  50366. // Add observer.
  50367. observer = new MutationObserver(function (mutations) {
  50368. self.handleMixinUpdate(mutations[0].attributeName);
  50369. });
  50370. observer.observe(mixinEl, MIXIN_OBSERVER_CONFIG);
  50371. this.mixinObservers[mixinId] = observer;
  50372. }
  50373. },
  50374. handleMixinUpdate: {
  50375. value: function () { /* no-op */ }
  50376. },
  50377. /**
  50378. * Emit a DOM event.
  50379. *
  50380. * @param {string} name - Name of event.
  50381. * @param {object} [detail={}] - Custom data to pass as `detail` to the event.
  50382. * @param {boolean} [bubbles=true] - Whether the event should bubble.
  50383. * @param {object} [extraData] - Extra data to pass to the event, if any.
  50384. */
  50385. emit: {
  50386. value: (function () {
  50387. var data = {};
  50388. return function (name, detail, bubbles, extraData) {
  50389. if (bubbles === undefined) { bubbles = true; }
  50390. data.bubbles = !!bubbles;
  50391. data.detail = detail;
  50392. // If extra data is present, we need to create a new object.
  50393. if (extraData) { data = utils.extend({}, extraData, data); }
  50394. this.dispatchEvent(new CustomEvent(name, data));
  50395. };
  50396. })(),
  50397. writable: window.debug
  50398. }
  50399. })
  50400. });
  50401. },{"../utils/":196,"./a-register-element":125}],125:[function(_dereq_,module,exports){
  50402. /*
  50403. ------------------------------------------------------------
  50404. ------------- WARNING WARNING WARNING WARNING --------------
  50405. ------------------------------------------------------------
  50406. This module wraps registerElement to deal with components that inherit from
  50407. `ANode` and `AEntity`. It's a pass through in any other case.
  50408. It wraps some of the prototype methods of the created element to make sure
  50409. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  50410. are also invoked. The method in the base prototype is always called before the one
  50411. in the derived prototype.
  50412. */
  50413. // Polyfill `document.registerElement`.
  50414. _dereq_('document-register-element');
  50415. var ANode; // Must declare before AEntity. Initialized at the bottom.
  50416. var AEntity;
  50417. var knownTags = module.exports.knownTags = {};
  50418. function addTagName (tagName) {
  50419. knownTags[tagName.toLowerCase()] = true;
  50420. }
  50421. /**
  50422. * Return whether the element type is one of our known registered ones.
  50423. *
  50424. * @param {string} node - The name of the tag to register.
  50425. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  50426. */
  50427. module.exports.isNode = function (node) {
  50428. return node.tagName.toLowerCase() in knownTags || node.isNode;
  50429. };
  50430. /**
  50431. * @param {string} tagName - The name of the tag to register.
  50432. * @param {object} obj - The prototype of the new element.
  50433. * @returns {object} The prototype of the new element.
  50434. */
  50435. module.exports.registerElement = function (tagName, obj) {
  50436. var proto = Object.getPrototypeOf(obj.prototype);
  50437. var newObj = obj;
  50438. var isANode = ANode && proto === ANode.prototype;
  50439. var isAEntity = AEntity && proto === AEntity.prototype;
  50440. if (isANode || isAEntity) { addTagName(tagName); }
  50441. // Wrap if element inherits from `ANode`.
  50442. if (isANode) {
  50443. newObj = wrapANodeMethods(obj.prototype);
  50444. newObj = {prototype: Object.create(proto, newObj)};
  50445. }
  50446. // Wrap if element inherits from `AEntity`.
  50447. if (isAEntity) {
  50448. newObj = wrapAEntityMethods(obj.prototype);
  50449. newObj = {prototype: Object.create(proto, newObj)};
  50450. }
  50451. // Give all functions their proper name.
  50452. for (var propName of Object.getOwnPropertyNames(newObj.prototype)) {
  50453. var propVal = newObj.prototype[propName];
  50454. if (typeof propVal === 'function') {
  50455. propVal.displayName = propName;
  50456. }
  50457. }
  50458. return document.registerElement(tagName, newObj);
  50459. };
  50460. /**
  50461. * Wrap some obj methods to call those on `ANode` base prototype.
  50462. *
  50463. * @param {object} obj - Object that contains the methods that will be wrapped.
  50464. * @return {object} An object with the same properties as the input parameter but
  50465. * with some of methods wrapped.
  50466. */
  50467. function wrapANodeMethods (obj) {
  50468. var newObj = {};
  50469. var ANodeMethods = [
  50470. 'attachedCallback',
  50471. 'attributeChangedCallback',
  50472. 'createdCallback'
  50473. ];
  50474. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50475. copyProperties(obj, newObj);
  50476. return newObj;
  50477. }
  50478. /**
  50479. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  50480. *
  50481. * @param {object} obj - The objects that contains the methods that will be wrapped.
  50482. * @return {object} - An object with the same properties as the input parameter but
  50483. * with some of methods wrapped.
  50484. */
  50485. function wrapAEntityMethods (obj) {
  50486. var newObj = {};
  50487. var ANodeMethods = [
  50488. 'attachedCallback',
  50489. 'attributeChangedCallback',
  50490. 'createdCallback'
  50491. ];
  50492. var AEntityMethods = [
  50493. 'attachedCallback',
  50494. 'attributeChangedCallback',
  50495. 'createdCallback',
  50496. 'detachedCallback'
  50497. ];
  50498. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  50499. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  50500. // Copies the remaining properties into the new object.
  50501. copyProperties(obj, newObj);
  50502. return newObj;
  50503. }
  50504. /**
  50505. * Wrap a list a methods to ensure that those in the base prototype are called
  50506. * before the derived one.
  50507. *
  50508. * @param {object} targetObj - Object that will contain the wrapped methods.
  50509. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  50510. * @param {object} derivedObject - Object that inherits from the baseObj.
  50511. * @param {object} baseObj - Object that derivedObj inherits from.
  50512. */
  50513. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  50514. methodList.forEach(function (methodName) {
  50515. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  50516. });
  50517. }
  50518. module.exports.wrapMethods = wrapMethods;
  50519. /**
  50520. * Wrap one method to ensure that the one in the base prototype is called before
  50521. * the one in the derived one.
  50522. *
  50523. * @param {object} obj - Object that will contain the wrapped method.
  50524. * @param {string} methodName - The name of the method that will be wrapped.
  50525. * @param {object} derivedObject - Object that inherits from the baseObj.
  50526. * @param {object} baseObj - Object that derivedObj inherits from.
  50527. */
  50528. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  50529. var derivedMethod = derivedObj[methodName];
  50530. var baseMethod = baseObj[methodName];
  50531. // Derived prototype does not define method, no need to wrap.
  50532. if (!derivedMethod || !baseMethod) { return; }
  50533. // Derived prototype doesn't override the one in the base one, no need to wrap.
  50534. if (derivedMethod === baseMethod) { return; }
  50535. // Wrap to ensure the base method is called before the one in the derived prototype.
  50536. obj[methodName] = {
  50537. value: function wrappedMethod () {
  50538. baseMethod.apply(this, arguments);
  50539. return derivedMethod.apply(this, arguments);
  50540. },
  50541. writable: window.debug
  50542. };
  50543. }
  50544. /**
  50545. * It copies the properties from source to destination object if they don't
  50546. * exist already.
  50547. *
  50548. * @param {object} source - The object where properties are copied from.
  50549. * @param {type} destination - The object where properties are copied to.
  50550. */
  50551. function copyProperties (source, destination) {
  50552. var props = Object.getOwnPropertyNames(source);
  50553. props.forEach(function (prop) {
  50554. var desc;
  50555. if (!destination[prop]) {
  50556. desc = Object.getOwnPropertyDescriptor(source, prop);
  50557. destination[prop] = {value: source[prop], writable: desc.writable};
  50558. }
  50559. });
  50560. }
  50561. ANode = _dereq_('./a-node');
  50562. AEntity = _dereq_('./a-entity');
  50563. },{"./a-entity":122,"./a-node":124,"document-register-element":11}],126:[function(_dereq_,module,exports){
  50564. /* global Node */
  50565. var schema = _dereq_('./schema');
  50566. var scenes = _dereq_('./scene/scenes');
  50567. var systems = _dereq_('./system');
  50568. var utils = _dereq_('../utils/');
  50569. var components = module.exports.components = {}; // Keep track of registered components.
  50570. var parseProperties = schema.parseProperties;
  50571. var parseProperty = schema.parseProperty;
  50572. var processSchema = schema.process;
  50573. var isSingleProp = schema.isSingleProperty;
  50574. var stringifyProperties = schema.stringifyProperties;
  50575. var stringifyProperty = schema.stringifyProperty;
  50576. var styleParser = utils.styleParser;
  50577. var warn = utils.debug('core:component:warn');
  50578. var aframeScript = document.currentScript;
  50579. var upperCaseRegExp = new RegExp('[A-Z]+');
  50580. /**
  50581. * Component class definition.
  50582. *
  50583. * Components configure appearance, modify behavior, or add functionality to
  50584. * entities. The behavior and appearance of an entity can be changed at runtime
  50585. * by adding, removing, or updating components. Entities do not share instances
  50586. * of components.
  50587. *
  50588. * @member {object} el - Reference to the entity element.
  50589. * @member {string} attrValue - Value of the corresponding HTML attribute.
  50590. * @member {object} data - Component data populated by parsing the
  50591. * mapped attribute of the component plus applying defaults and mixins.
  50592. */
  50593. var Component = module.exports.Component = function (el, attrValue, id) {
  50594. var self = this;
  50595. this.el = el;
  50596. this.id = id;
  50597. this.attrName = this.name + (id ? '__' + id : '');
  50598. this.evtDetail = {id: this.id, name: this.name};
  50599. this.initialized = false;
  50600. this.el.components[this.attrName] = this;
  50601. // Store component data from previous update call.
  50602. this.oldData = undefined;
  50603. // Last value passed to updateProperties.
  50604. this.previousAttrValue = undefined;
  50605. this.throttledEmitComponentChanged = utils.throttle(function emitChange () {
  50606. el.emit('componentchanged', self.evtDetail, false);
  50607. }, 200);
  50608. this.updateProperties(attrValue);
  50609. };
  50610. Component.prototype = {
  50611. /**
  50612. * Contains the type schema and defaults for the data values.
  50613. * Data is coerced into the types of the values of the defaults.
  50614. */
  50615. schema: {},
  50616. /**
  50617. * Init handler. Similar to attachedCallback.
  50618. * Called during component initialization and is only run once.
  50619. * Components can use this to set initial state.
  50620. */
  50621. init: function () { /* no-op */ },
  50622. /**
  50623. * Update handler. Similar to attributeChangedCallback.
  50624. * Called whenever component's data changes.
  50625. * Also called on component initialization when the component receives initial data.
  50626. *
  50627. * @param {object} prevData - Previous attributes of the component.
  50628. */
  50629. update: function (prevData) { /* no-op */ },
  50630. updateSchema: undefined,
  50631. /**
  50632. * Tick handler.
  50633. * Called on each tick of the scene render loop.
  50634. * Affected by play and pause.
  50635. *
  50636. * @param {number} time - Scene tick time.
  50637. * @param {number} timeDelta - Difference in current render time and previous render time.
  50638. */
  50639. tick: undefined,
  50640. /**
  50641. * Tock handler.
  50642. * Called on each tock of the scene render loop.
  50643. * Affected by play and pause.
  50644. *
  50645. * @param {number} time - Scene tick time.
  50646. * @param {number} timeDelta - Difference in current render time and previous render time.
  50647. */
  50648. tock: undefined,
  50649. /**
  50650. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  50651. */
  50652. play: function () { /* no-op */ },
  50653. /**
  50654. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  50655. */
  50656. pause: function () { /* no-op */ },
  50657. /**
  50658. * Remove handler. Similar to detachedCallback.
  50659. * Called whenever component is removed from the entity (i.e., removeAttribute).
  50660. * Components can use this to reset behavior on the entity.
  50661. */
  50662. remove: function () { /* no-op */ },
  50663. /**
  50664. * Parses each property based on property type.
  50665. * If component is single-property, then parses the single property value.
  50666. *
  50667. * @param {string} value - HTML attribute value.
  50668. * @param {boolean} silent - Suppress warning messages.
  50669. * @returns {object} Component data.
  50670. */
  50671. parse: function (value, silent) {
  50672. var schema = this.schema;
  50673. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  50674. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  50675. },
  50676. /**
  50677. * Stringify properties if necessary.
  50678. *
  50679. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  50680. * value (e.g., selector, vec3 property types).
  50681. *
  50682. * @param {object} data - Complete component data.
  50683. * @returns {string}
  50684. */
  50685. stringify: function (data) {
  50686. var schema = this.schema;
  50687. if (typeof data === 'string') { return data; }
  50688. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  50689. data = stringifyProperties(data, schema);
  50690. return styleParser.stringify(data);
  50691. },
  50692. /**
  50693. * Update the cache of the pre-parsed attribute value.
  50694. *
  50695. * @param {string} value - New data.
  50696. * @param {boolean } clobber - Whether to wipe out and replace previous data.
  50697. */
  50698. updateCachedAttrValue: function (value, clobber) {
  50699. var attrValue = this.parseAttrValueForCache(value);
  50700. var isSinglePropSchema = isSingleProp(this.schema);
  50701. var property;
  50702. if (value === undefined) { return; }
  50703. // Merge new data with previous `attrValue` if updating and not clobbering.
  50704. if (!isSinglePropSchema && !clobber) {
  50705. this.attrValue = this.attrValue ? cloneData(this.attrValue) : {};
  50706. for (property in attrValue) {
  50707. this.attrValue[property] = attrValue[property];
  50708. }
  50709. return;
  50710. }
  50711. // If single-prop schema or clobber.
  50712. this.attrValue = attrValue;
  50713. },
  50714. /**
  50715. * Given an HTML attribute value parses the string
  50716. * based on the component schema. To avoid double parsings of
  50717. * strings into strings we store the original instead
  50718. * of the parsed one
  50719. *
  50720. * @param {string} value - HTML attribute value
  50721. */
  50722. parseAttrValueForCache: function (value) {
  50723. var parsedValue;
  50724. if (typeof value !== 'string') { return value; }
  50725. if (isSingleProp(this.schema)) {
  50726. parsedValue = this.schema.parse(value);
  50727. /**
  50728. * To avoid bogus double parsings. Cached values will be parsed when building
  50729. * component data. For instance when parsing a src id to its url, we want to cache
  50730. * original string and not the parsed one (#monster -> models/monster.dae)
  50731. * so when building data we parse the expected value.
  50732. */
  50733. if (typeof parsedValue === 'string') { parsedValue = value; }
  50734. } else {
  50735. // Parse using the style parser to avoid double parsing of individual properties.
  50736. parsedValue = styleParser.parse(value);
  50737. }
  50738. return parsedValue;
  50739. },
  50740. /**
  50741. * Write cached attribute data to the entity DOM element.
  50742. *
  50743. * @param {boolean} isDefault - Whether component is a default component. Always flush for
  50744. * default components.
  50745. */
  50746. flushToDOM: function (isDefault) {
  50747. var attrValue = isDefault ? this.data : this.attrValue;
  50748. if (!attrValue) { return; }
  50749. window.HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  50750. this.stringify(attrValue));
  50751. },
  50752. /**
  50753. * Apply new component data if data has changed.
  50754. *
  50755. * @param {string} attrValue - HTML attribute value.
  50756. * If undefined, use the cached attribute value and continue updating properties.
  50757. * @param {boolean} clobber - The previous component data is overwritten by the atrrValue
  50758. */
  50759. updateProperties: function (attrValue, clobber) {
  50760. var el = this.el;
  50761. var isSinglePropSchema;
  50762. var key;
  50763. var skipTypeChecking;
  50764. var oldData = this.oldData;
  50765. // Just cache the attribute if the entity has not loaded
  50766. // Components are not initialized until the entity has loaded
  50767. if (!el.hasLoaded) {
  50768. this.updateCachedAttrValue(attrValue);
  50769. return;
  50770. }
  50771. isSinglePropSchema = isSingleProp(this.schema);
  50772. // Disable type checking if the passed attribute is an object and has not changed.
  50773. skipTypeChecking = attrValue !== null && typeof this.previousAttrValue === 'object' &&
  50774. attrValue === this.previousAttrValue;
  50775. if (skipTypeChecking) {
  50776. for (key in this.attrValue) {
  50777. if (!(key in attrValue)) {
  50778. skipTypeChecking = false;
  50779. break;
  50780. }
  50781. }
  50782. for (key in attrValue) {
  50783. if (!(key in this.attrValue)) {
  50784. skipTypeChecking = false;
  50785. break;
  50786. }
  50787. }
  50788. }
  50789. // Cache previously passed attribute to decide if we skip type checking.
  50790. this.previousAttrValue = attrValue;
  50791. // Cache current attrValue for future updates. Updates `this.attrValue`.
  50792. attrValue = this.parseAttrValueForCache(attrValue);
  50793. this.updateCachedAttrValue(attrValue, clobber);
  50794. if (this.updateSchema) {
  50795. this.updateSchema(this.buildData(this.attrValue, false, true));
  50796. }
  50797. this.data = this.buildData(this.attrValue, clobber, false, skipTypeChecking);
  50798. if (!this.initialized) {
  50799. // Component is being already initialized.
  50800. if (el.initializingComponents[this.name]) { return; }
  50801. // Prevent infinite loop in case of init method setting same component on the entity.
  50802. el.initializingComponents[this.name] = true;
  50803. // Initialize component.
  50804. this.init();
  50805. this.initialized = true;
  50806. delete el.initializingComponents[this.name];
  50807. // For oldData, pass empty object to multiple-prop schemas or object single-prop schema.
  50808. // Pass undefined to rest of types.
  50809. oldData = (!isSinglePropSchema ||
  50810. typeof parseProperty(undefined, this.schema) === 'object') ? {} : undefined;
  50811. // Store current data as previous data for future updates.
  50812. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  50813. this.update(oldData);
  50814. // Play the component if the entity is playing.
  50815. if (el.isPlaying) { this.play(); }
  50816. el.emit('componentinitialized', this.evtDetail, false);
  50817. } else {
  50818. // Don't update if properties haven't changed
  50819. if (utils.deepEqual(this.oldData, this.data)) { return; }
  50820. // Store current data as previous data for future updates.
  50821. this.oldData = extendProperties({}, this.data, isSinglePropSchema);
  50822. // Update component.
  50823. this.update(oldData);
  50824. this.throttledEmitComponentChanged();
  50825. }
  50826. },
  50827. /**
  50828. * Reset value of a property to the property's default value.
  50829. * If single-prop component, reset value to component's default value.
  50830. *
  50831. * @param {string} propertyName - Name of property to reset.
  50832. */
  50833. resetProperty: function (propertyName) {
  50834. if (isSingleProp(this.schema)) {
  50835. this.attrValue = undefined;
  50836. } else {
  50837. if (!(propertyName in this.attrValue)) { return; }
  50838. delete this.attrValue[propertyName];
  50839. }
  50840. this.updateProperties(this.attrValue);
  50841. },
  50842. /**
  50843. * Extend schema of component given a partial schema.
  50844. *
  50845. * Some components might want to mutate their schema based on certain properties.
  50846. * e.g., Material component changes its schema based on `shader` to account for different
  50847. * uniforms
  50848. *
  50849. * @param {object} schemaAddon - Schema chunk that extend base schema.
  50850. */
  50851. extendSchema: function (schemaAddon) {
  50852. // Clone base schema.
  50853. var extendedSchema = utils.extend({}, components[this.name].schema);
  50854. // Extend base schema with new schema chunk.
  50855. utils.extend(extendedSchema, schemaAddon);
  50856. this.schema = processSchema(extendedSchema);
  50857. this.el.emit('schemachanged', {component: this.name});
  50858. },
  50859. /**
  50860. * Builds component data from the current state of the entity, ultimately
  50861. * updating this.data.
  50862. *
  50863. * If the component was detached completely, set data to null.
  50864. *
  50865. * Precedence:
  50866. * 1. Defaults data
  50867. * 2. Mixin data.
  50868. * 3. Attribute data.
  50869. *
  50870. * Finally coerce the data to the types of the defaults.
  50871. *
  50872. * @param {object} newData - Element new data.
  50873. * @param {boolean} clobber - The previous data is completely replaced by the new one.
  50874. * @param {boolean} silent - Suppress warning messages.
  50875. * @param {boolean} skipTypeChecking - Skip type checking and cohercion.
  50876. * @return {object} The component data
  50877. */
  50878. buildData: function (newData, clobber, silent, skipTypeChecking) {
  50879. var componentDefined;
  50880. var data;
  50881. var defaultValue;
  50882. var keys;
  50883. var keysLength;
  50884. var mixinData;
  50885. var schema = this.schema;
  50886. var i;
  50887. var isSinglePropSchema = isSingleProp(schema);
  50888. var mixinEls = this.el.mixinEls;
  50889. var previousData;
  50890. // Whether component has a defined value. For arrays, treat empty as not defined.
  50891. componentDefined = newData && newData.constructor === Array
  50892. ? newData.length
  50893. : newData !== undefined && newData !== null;
  50894. // 1. Default values (lowest precendence).
  50895. if (isSinglePropSchema) {
  50896. // Clone default value if plain object so components don't share the same object
  50897. // that might be modified by the user.
  50898. data = isObjectOrArray(schema.default) ? utils.clone(schema.default) : schema.default;
  50899. } else {
  50900. // Preserve previously set properties if clobber not enabled.
  50901. previousData = !clobber && this.attrValue;
  50902. // Clone previous data to prevent sharing references with attrValue that might be
  50903. // modified by the user.
  50904. data = typeof previousData === 'object' ? cloneData(previousData) : {};
  50905. // Apply defaults.
  50906. for (i = 0, keys = Object.keys(schema), keysLength = keys.length; i < keysLength; i++) {
  50907. defaultValue = schema[keys[i]].default;
  50908. if (data[keys[i]] !== undefined) { continue; }
  50909. // Clone default value if object so components don't share object
  50910. data[keys[i]] = isObjectOrArray(defaultValue) ? utils.clone(defaultValue) : defaultValue;
  50911. }
  50912. }
  50913. // 2. Mixin values.
  50914. for (i = 0; i < mixinEls.length; i++) {
  50915. mixinData = mixinEls[i].getAttribute(this.attrName);
  50916. if (mixinData) {
  50917. data = extendProperties(data, mixinData, isSinglePropSchema);
  50918. }
  50919. }
  50920. // 3. Attribute values (highest precendence).
  50921. if (componentDefined) {
  50922. if (isSinglePropSchema) {
  50923. if (skipTypeChecking === true) { return newData; }
  50924. return parseProperty(newData, schema);
  50925. }
  50926. data = extendProperties(data, newData, isSinglePropSchema);
  50927. } else {
  50928. if (skipTypeChecking === true) { return data; }
  50929. // Parse and coerce using the schema.
  50930. if (isSinglePropSchema) { return parseProperty(data, schema); }
  50931. }
  50932. if (skipTypeChecking === true) { return data; }
  50933. return parseProperties(data, schema, undefined, this.name, silent);
  50934. }
  50935. };
  50936. // For testing.
  50937. if (window.debug) {
  50938. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  50939. }
  50940. /**
  50941. * Registers a component to A-Frame.
  50942. *
  50943. * @param {string} name - Component name.
  50944. * @param {object} definition - Component schema and lifecycle method handlers.
  50945. * @returns {object} Component.
  50946. */
  50947. module.exports.registerComponent = function (name, definition) {
  50948. var NewComponent;
  50949. var proto = {};
  50950. // Warning if component is statically registered after the scene.
  50951. if (document.currentScript && document.currentScript !== aframeScript) {
  50952. scenes.forEach(function checkPosition (sceneEl) {
  50953. // Okay to register component after the scene at runtime.
  50954. if (sceneEl.hasLoaded) { return; }
  50955. // Check that component is declared before the scene.
  50956. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  50957. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  50958. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  50959. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  50960. 'such that the component is available to entities during scene initialization.');
  50961. // For testing.
  50962. if (window.debug) { registrationOrderWarnings[name] = true; }
  50963. });
  50964. }
  50965. if (upperCaseRegExp.test(name) === true) {
  50966. warn('The component name `' + name + '` contains uppercase characters, but ' +
  50967. 'HTML will ignore the capitalization of attribute names. ' +
  50968. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  50969. }
  50970. if (name.indexOf('__') !== -1) {
  50971. throw new Error('The component name `' + name + '` is not allowed. ' +
  50972. 'The sequence __ (double underscore) is reserved to specify an id' +
  50973. ' for multiple components of the same type');
  50974. }
  50975. // Format definition object to prototype object.
  50976. Object.keys(definition).forEach(function (key) {
  50977. proto[key] = {
  50978. value: definition[key],
  50979. writable: true
  50980. };
  50981. });
  50982. if (components[name]) {
  50983. throw new Error('The component `' + name + '` has been already registered. ' +
  50984. 'Check that you are not loading two versions of the same component ' +
  50985. 'or two different components of the same name.');
  50986. }
  50987. NewComponent = function (el, attr, id) {
  50988. Component.call(this, el, attr, id);
  50989. };
  50990. NewComponent.prototype = Object.create(Component.prototype, proto);
  50991. NewComponent.prototype.name = name;
  50992. NewComponent.prototype.constructor = NewComponent;
  50993. NewComponent.prototype.system = systems && systems.systems[name];
  50994. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  50995. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  50996. components[name] = {
  50997. Component: NewComponent,
  50998. dependencies: NewComponent.prototype.dependencies,
  50999. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  51000. multiple: NewComponent.prototype.multiple,
  51001. parse: NewComponent.prototype.parse,
  51002. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  51003. schema: utils.extend(processSchema(NewComponent.prototype.schema, NewComponent.prototype.name)),
  51004. stringify: NewComponent.prototype.stringify,
  51005. type: NewComponent.prototype.type
  51006. };
  51007. return NewComponent;
  51008. };
  51009. /**
  51010. * Clone component data.
  51011. * Clone only the properties that are plain objects while keeping a reference for the rest.
  51012. *
  51013. * @param data - Component data to clone.
  51014. * @returns Cloned data.
  51015. */
  51016. function cloneData (data) {
  51017. var clone = {};
  51018. var parsedProperty;
  51019. var key;
  51020. for (key in data) {
  51021. parsedProperty = data[key];
  51022. clone[key] = isObjectOrArray(parsedProperty) ? utils.clone(parsedProperty) : parsedProperty;
  51023. }
  51024. return clone;
  51025. }
  51026. /**
  51027. * Object extending with checking for single-property schema.
  51028. *
  51029. * @param dest - Destination object or value.
  51030. * @param source - Source object or value
  51031. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  51032. * @returns Overridden object or value.
  51033. */
  51034. function extendProperties (dest, source, isSinglePropSchema) {
  51035. if (isSinglePropSchema && (source === null || typeof source !== 'object')) { return source; }
  51036. return utils.extend(dest, source);
  51037. }
  51038. /**
  51039. * Checks if a component has defined a method that needs to run every frame.
  51040. */
  51041. function hasBehavior (component) {
  51042. return component.tick || component.tock;
  51043. }
  51044. /**
  51045. * Wrapper for user defined pause method
  51046. * Pause component by removing tick behavior and calling user's pause method.
  51047. *
  51048. * @param pauseMethod {function} - user defined pause method
  51049. */
  51050. function wrapPause (pauseMethod) {
  51051. return function pause () {
  51052. var sceneEl = this.el.sceneEl;
  51053. if (!this.isPlaying) { return; }
  51054. pauseMethod.call(this);
  51055. this.isPlaying = false;
  51056. // Remove tick behavior.
  51057. if (!hasBehavior(this)) { return; }
  51058. sceneEl.removeBehavior(this);
  51059. };
  51060. }
  51061. /**
  51062. * Wrapper for user defined play method
  51063. * Play component by adding tick behavior and calling user's play method.
  51064. *
  51065. * @param playMethod {function} - user defined play method
  51066. *
  51067. */
  51068. function wrapPlay (playMethod) {
  51069. return function play () {
  51070. var sceneEl = this.el.sceneEl;
  51071. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  51072. if (!this.initialized || !shouldPlay) { return; }
  51073. playMethod.call(this);
  51074. this.isPlaying = true;
  51075. // Add tick behavior.
  51076. if (!hasBehavior(this)) { return; }
  51077. sceneEl.addBehavior(this);
  51078. };
  51079. }
  51080. function isObjectOrArray (value) {
  51081. return value && (value.constructor === Object || value.constructor === Array);
  51082. }
  51083. },{"../utils/":196,"./scene/scenes":132,"./schema":134,"./system":136}],127:[function(_dereq_,module,exports){
  51084. var schema = _dereq_('./schema');
  51085. var processSchema = schema.process;
  51086. var geometries = module.exports.geometries = {}; // Registered geometries.
  51087. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  51088. var THREE = _dereq_('../lib/three');
  51089. /**
  51090. * Geometry class definition.
  51091. *
  51092. * Geometries extend the geometry component API to create and register geometry types.
  51093. */
  51094. var Geometry = module.exports.Geometry = function () {};
  51095. Geometry.prototype = {
  51096. /**
  51097. * Contains the type schema and defaults for the data values.
  51098. * Data is coerced into the types of the values of the defaults.
  51099. */
  51100. schema: {},
  51101. /**
  51102. * Init handler. Similar to attachedCallback.
  51103. * Called during shader initialization and is only run once.
  51104. */
  51105. init: function (data) {
  51106. this.geometry = new THREE.Geometry();
  51107. return this.geometry;
  51108. },
  51109. /**
  51110. * Update handler. Similar to attributeChangedCallback.
  51111. * Called whenever the associated geometry data changes.
  51112. *
  51113. * @param {object} data - New geometry data.
  51114. */
  51115. update: function (data) { /* no-op */ }
  51116. };
  51117. /**
  51118. * Registers a geometry to A-Frame.
  51119. *
  51120. * @param {string} name - Geometry name.
  51121. * @param {object} definition - Geometry property and methods.
  51122. * @returns {object} Geometry.
  51123. */
  51124. module.exports.registerGeometry = function (name, definition) {
  51125. var NewGeometry;
  51126. var proto = {};
  51127. // Format definition object to prototype object.
  51128. Object.keys(definition).forEach(function expandDefinition (key) {
  51129. proto[key] = {
  51130. value: definition[key],
  51131. writable: true
  51132. };
  51133. });
  51134. if (geometries[name]) {
  51135. throw new Error('The geometry `' + name + '` has been already registered');
  51136. }
  51137. NewGeometry = function () { Geometry.call(this); };
  51138. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  51139. NewGeometry.prototype.name = name;
  51140. NewGeometry.prototype.constructor = NewGeometry;
  51141. geometries[name] = {
  51142. Geometry: NewGeometry,
  51143. schema: processSchema(NewGeometry.prototype.schema)
  51144. };
  51145. geometryNames.push(name);
  51146. return NewGeometry;
  51147. };
  51148. },{"../lib/three":174,"./schema":134}],128:[function(_dereq_,module,exports){
  51149. var coordinates = _dereq_('../utils/coordinates');
  51150. var debug = _dereq_('debug');
  51151. var error = debug('core:propertyTypes:warn');
  51152. var warn = debug('core:propertyTypes:warn');
  51153. var propertyTypes = module.exports.propertyTypes = {};
  51154. var nonCharRegex = /[,> .[\]:]/;
  51155. // Built-in property types.
  51156. registerPropertyType('audio', '', assetParse);
  51157. registerPropertyType('array', [], arrayParse, arrayStringify);
  51158. registerPropertyType('asset', '', assetParse);
  51159. registerPropertyType('boolean', false, boolParse);
  51160. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  51161. registerPropertyType('int', 0, intParse);
  51162. registerPropertyType('number', 0, numberParse);
  51163. registerPropertyType('map', '', assetParse);
  51164. registerPropertyType('model', '', assetParse);
  51165. registerPropertyType('selector', null, selectorParse, selectorStringify);
  51166. registerPropertyType('selectorAll', null, selectorAllParse, selectorAllStringify);
  51167. registerPropertyType('src', '', srcParse);
  51168. registerPropertyType('string', '', defaultParse, defaultStringify);
  51169. registerPropertyType('time', 0, intParse);
  51170. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  51171. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  51172. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 0}, vecParse, coordinates.stringify);
  51173. /**
  51174. * Register a parser for re-use such that when someone uses `type` in the schema,
  51175. * `schema.process` will set the property `parse` and `stringify`.
  51176. *
  51177. * @param {string} type - Type name.
  51178. * @param [defaultValue=null] -
  51179. * Default value to use if component does not define default value.
  51180. * @param {function} [parse=defaultParse] - Parse string function.
  51181. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  51182. */
  51183. function registerPropertyType (type, defaultValue, parse, stringify) {
  51184. if ('type' in propertyTypes) {
  51185. error('Property type ' + type + ' is already registered.');
  51186. return;
  51187. }
  51188. propertyTypes[type] = {
  51189. default: defaultValue,
  51190. parse: parse || defaultParse,
  51191. stringify: stringify || defaultStringify
  51192. };
  51193. }
  51194. module.exports.registerPropertyType = registerPropertyType;
  51195. function arrayParse (value) {
  51196. if (Array.isArray(value)) { return value; }
  51197. if (!value || typeof value !== 'string') { return []; }
  51198. return value.split(',').map(trim);
  51199. function trim (str) { return str.trim(); }
  51200. }
  51201. function arrayStringify (value) {
  51202. return value.join(', ');
  51203. }
  51204. /**
  51205. * For general assets.
  51206. *
  51207. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  51208. * just string.
  51209. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  51210. * just string.
  51211. */
  51212. function assetParse (value) {
  51213. var el;
  51214. var parsedUrl;
  51215. // If an element was provided (e.g. canvas or video), just return it.
  51216. if (typeof value !== 'string') { return value; }
  51217. // Wrapped `url()` in case of data URI.
  51218. parsedUrl = value.match(/\url\((.+)\)/);
  51219. if (parsedUrl) { return parsedUrl[1]; }
  51220. // ID.
  51221. if (value.charAt(0) === '#') {
  51222. el = document.getElementById(value.substring(1));
  51223. if (el) {
  51224. // Pass through media elements. If we have the elements, we don't have to call
  51225. // three.js loaders which would re-request the assets.
  51226. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO' || el.tagName === 'IMG') {
  51227. return el;
  51228. }
  51229. return el.getAttribute('src');
  51230. }
  51231. warn('"' + value + '" asset not found.');
  51232. return;
  51233. }
  51234. // Non-wrapped url().
  51235. return value;
  51236. }
  51237. function defaultParse (value) {
  51238. return value;
  51239. }
  51240. function defaultStringify (value) {
  51241. if (value === null) { return 'null'; }
  51242. return value.toString();
  51243. }
  51244. function boolParse (value) {
  51245. return value !== 'false' && value !== false;
  51246. }
  51247. function intParse (value) {
  51248. return parseInt(value, 10);
  51249. }
  51250. function numberParse (value) {
  51251. return parseFloat(value, 10);
  51252. }
  51253. function selectorParse (value) {
  51254. if (!value) { return null; }
  51255. if (typeof value !== 'string') { return value; }
  51256. if (value[0] === '#' && !nonCharRegex.test(value)) {
  51257. // When selecting element by ID only, use getElementById for better performance.
  51258. // Don't match like #myId .child.
  51259. return document.getElementById(value.substring(1));
  51260. }
  51261. return document.querySelector(value);
  51262. }
  51263. function selectorAllParse (value) {
  51264. if (!value) { return null; }
  51265. if (typeof value !== 'string') { return value; }
  51266. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  51267. }
  51268. function selectorStringify (value) {
  51269. if (value.getAttribute) {
  51270. return '#' + value.getAttribute('id');
  51271. }
  51272. return defaultStringify(value);
  51273. }
  51274. function selectorAllStringify (value) {
  51275. if (value instanceof Array) {
  51276. return value.map(function (element) {
  51277. return '#' + element.getAttribute('id');
  51278. }).join(', ');
  51279. }
  51280. return defaultStringify(value);
  51281. }
  51282. function srcParse (value) {
  51283. warn('`src` property type is deprecated. Use `asset` instead.');
  51284. return assetParse(value);
  51285. }
  51286. function vecParse (value) {
  51287. return coordinates.parse(value, this.default);
  51288. }
  51289. /**
  51290. * Validate the default values in a schema to match their type.
  51291. *
  51292. * @param {string} type - Property type name.
  51293. * @param defaultVal - Property type default value.
  51294. * @returns {boolean} Whether default value is accurate given the type.
  51295. */
  51296. function isValidDefaultValue (type, defaultVal) {
  51297. if (type === 'audio' && typeof defaultVal !== 'string') { return false; }
  51298. if (type === 'array' && !Array.isArray(defaultVal)) { return false; }
  51299. if (type === 'asset' && typeof defaultVal !== 'string') { return false; }
  51300. if (type === 'boolean' && typeof defaultVal !== 'boolean') { return false; }
  51301. if (type === 'color' && typeof defaultVal !== 'string') { return false; }
  51302. if (type === 'int' && typeof defaultVal !== 'number') { return false; }
  51303. if (type === 'number' && typeof defaultVal !== 'number') { return false; }
  51304. if (type === 'map' && typeof defaultVal !== 'string') { return false; }
  51305. if (type === 'model' && typeof defaultVal !== 'string') { return false; }
  51306. if (type === 'selector' && typeof defaultVal !== 'string' &&
  51307. defaultVal !== null) { return false; }
  51308. if (type === 'selectorAll' && typeof defaultVal !== 'string' &&
  51309. defaultVal !== null) { return false; }
  51310. if (type === 'src' && typeof defaultVal !== 'string') { return false; }
  51311. if (type === 'string' && typeof defaultVal !== 'string') { return false; }
  51312. if (type === 'time' && typeof defaultVal !== 'number') { return false; }
  51313. if (type === 'vec2') { return isValidDefaultCoordinate(defaultVal, 2); }
  51314. if (type === 'vec3') { return isValidDefaultCoordinate(defaultVal, 3); }
  51315. if (type === 'vec4') { return isValidDefaultCoordinate(defaultVal, 4); }
  51316. return true;
  51317. }
  51318. module.exports.isValidDefaultValue = isValidDefaultValue;
  51319. /**
  51320. * Checks if default coordinates are valid.
  51321. *
  51322. * @param possibleCoordinates
  51323. * @param {number} dimensions - 2 for 2D Vector, 3 for 3D vector.
  51324. * @returns {boolean} Whether coordinates are parsed correctly.
  51325. */
  51326. function isValidDefaultCoordinate (possibleCoordinates, dimensions) {
  51327. if (possibleCoordinates === null) { return true; }
  51328. if (typeof possibleCoordinates !== 'object') { return false; }
  51329. if (Object.keys(possibleCoordinates).length !== dimensions) {
  51330. return false;
  51331. } else {
  51332. var x = possibleCoordinates.x;
  51333. var y = possibleCoordinates.y;
  51334. var z = possibleCoordinates.z;
  51335. var w = possibleCoordinates.w;
  51336. if (typeof x !== 'number' || typeof y !== 'number') { return false; }
  51337. if (dimensions > 2 && typeof z !== 'number') { return false; }
  51338. if (dimensions > 3 && typeof w !== 'number') { return false; }
  51339. }
  51340. return true;
  51341. }
  51342. module.exports.isValidDefaultCoordinate = isValidDefaultCoordinate;
  51343. },{"../utils/coordinates":191,"debug":8}],129:[function(_dereq_,module,exports){
  51344. /* global Promise, screen */
  51345. var initMetaTags = _dereq_('./metaTags').inject;
  51346. var initWakelock = _dereq_('./wakelock');
  51347. var re = _dereq_('../a-register-element');
  51348. var scenes = _dereq_('./scenes');
  51349. var systems = _dereq_('../system').systems;
  51350. var THREE = _dereq_('../../lib/three');
  51351. var TWEEN = _dereq_('@tweenjs/tween.js');
  51352. var utils = _dereq_('../../utils/');
  51353. // Require after.
  51354. var AEntity = _dereq_('../a-entity');
  51355. var ANode = _dereq_('../a-node');
  51356. var initPostMessageAPI = _dereq_('./postMessage');
  51357. var bind = utils.bind;
  51358. var isIOS = utils.device.isIOS();
  51359. var isMobile = utils.device.isMobile();
  51360. var registerElement = re.registerElement;
  51361. var warn = utils.debug('core:a-scene:warn');
  51362. /**
  51363. * Scene element, holds all entities.
  51364. *
  51365. * @member {array} behaviors - Component instances that have registered themselves to be
  51366. updated on every tick.
  51367. * @member {object} camera - three.js Camera object.
  51368. * @member {object} canvas
  51369. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  51370. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  51371. * @member {object} object3D - Root three.js Scene object.
  51372. * @member {object} renderer
  51373. * @member {bool} renderStarted
  51374. * @member {object} systems - Registered instantiated systems.
  51375. * @member {number} time
  51376. */
  51377. module.exports.AScene = registerElement('a-scene', {
  51378. prototype: Object.create(AEntity.prototype, {
  51379. defaultComponents: {
  51380. value: {
  51381. 'inspector': '',
  51382. 'keyboard-shortcuts': '',
  51383. 'screenshot': '',
  51384. 'vr-mode-ui': ''
  51385. }
  51386. },
  51387. createdCallback: {
  51388. value: function () {
  51389. this.isIOS = isIOS;
  51390. this.isMobile = isMobile;
  51391. this.isScene = true;
  51392. this.object3D = new THREE.Scene();
  51393. this.render = bind(this.render, this);
  51394. this.systems = {};
  51395. this.systemNames = [];
  51396. this.time = 0;
  51397. this.init();
  51398. }
  51399. },
  51400. init: {
  51401. value: function () {
  51402. this.behaviors = {tick: [], tock: []};
  51403. this.hasLoaded = false;
  51404. this.isPlaying = false;
  51405. this.originalHTML = this.innerHTML;
  51406. this.renderTarget = null;
  51407. setupCanvas(this);
  51408. this.setupRenderer();
  51409. this.resize();
  51410. this.addFullScreenStyles();
  51411. initPostMessageAPI(this);
  51412. },
  51413. writable: true
  51414. },
  51415. addFullScreenStyles: {
  51416. value: function () {
  51417. var htmlEl = document.documentElement;
  51418. htmlEl.classList.add('a-html');
  51419. document.body.classList.add('a-body');
  51420. this.classList.add('fullscreen');
  51421. }
  51422. },
  51423. removeFullScreenStyles: {
  51424. value: function () {
  51425. var htmlEl = document.documentElement;
  51426. htmlEl.classList.remove('a-html');
  51427. document.body.classList.remove('a-body');
  51428. this.classList.remove('fullscreen');
  51429. }
  51430. },
  51431. attachedCallback: {
  51432. value: function () {
  51433. var resize;
  51434. var self = this;
  51435. initMetaTags(this);
  51436. initWakelock(this);
  51437. this.initSystems();
  51438. resize = bind(this.resize, this);
  51439. window.addEventListener('load', resize);
  51440. window.addEventListener('resize', function () {
  51441. // Workaround for a Webkit bug (https://bugs.webkit.org/show_bug.cgi?id=170595)
  51442. // where the window does not contain the correct viewport size
  51443. // after an orientation change. The window size is correct if the operation
  51444. // is postponed a few milliseconds.
  51445. // self.resize can be called directly once the bug above is fixed.
  51446. if (this.isIOS) {
  51447. setTimeout(resize, 100);
  51448. } else {
  51449. resize();
  51450. }
  51451. });
  51452. this.play();
  51453. // Add to scene index.
  51454. scenes.push(this);
  51455. // Handler to exit VR (e.g., Oculus Browser back button).
  51456. this.onVRPresentChangeBound = bind(this.onVRPresentChange, this);
  51457. window.addEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  51458. // bind functions
  51459. this.enterVRBound = function () { self.enterVR(); };
  51460. this.exitVRBound = function () { self.exitVR(); };
  51461. this.exitVRTrueBound = function () { self.exitVR(true); };
  51462. this.pointerRestrictedBound = function () { self.pointerRestricted(); };
  51463. this.pointerUnrestrictedBound = function () { self.pointerUnrestricted(); };
  51464. // Enter VR on `vrdisplayactivate` (e.g. putting on Rift headset).
  51465. window.addEventListener('vrdisplayactivate', this.enterVRBound);
  51466. // Exit VR on `vrdisplaydeactivate` (e.g. taking off Rift headset).
  51467. window.addEventListener('vrdisplaydeactivate', this.exitVRBound);
  51468. // Exit VR on `vrdisplaydisconnect` (e.g. unplugging Rift headset).
  51469. window.addEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  51470. // Register for mouse restricted events while in VR
  51471. // (e.g. mouse no longer available on desktop 2D view)
  51472. window.addEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  51473. // Register for mouse unrestricted events while in VR
  51474. // (e.g. mouse once again available on desktop 2D view)
  51475. window.addEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  51476. },
  51477. writable: window.debug
  51478. },
  51479. /**
  51480. * Initialize all systems.
  51481. */
  51482. initSystems: {
  51483. value: function () {
  51484. Object.keys(systems).forEach(bind(this.initSystem, this));
  51485. }
  51486. },
  51487. /**
  51488. * Initialize a system.
  51489. */
  51490. initSystem: {
  51491. value: function (name) {
  51492. if (this.systems[name]) { return; }
  51493. this.systems[name] = new systems[name](this);
  51494. this.systemNames.push(name);
  51495. }
  51496. },
  51497. /**
  51498. * Shut down scene on detach.
  51499. */
  51500. detachedCallback: {
  51501. value: function () {
  51502. // Remove from scene index.
  51503. var sceneIndex = scenes.indexOf(this);
  51504. scenes.splice(sceneIndex, 1);
  51505. window.removeEventListener('vrdisplaypresentchange', this.onVRPresentChangeBound);
  51506. window.removeEventListener('vrdisplayactivate', this.enterVRBound);
  51507. window.removeEventListener('vrdisplaydeactivate', this.exitVRBound);
  51508. window.removeEventListener('vrdisplayconnect', this.enterVRBound);
  51509. window.removeEventListener('vrdisplaydisconnect', this.exitVRTrueBound);
  51510. window.removeEventListener('vrdisplaypointerrestricted', this.pointerRestrictedBound);
  51511. window.removeEventListener('vrdisplaypointerunrestricted', this.pointerUnrestrictedBound);
  51512. }
  51513. },
  51514. /**
  51515. * Add ticks and tocks.
  51516. *
  51517. * @param {object} behavior - A component.
  51518. */
  51519. addBehavior: {
  51520. value: function (behavior) {
  51521. var behaviorArr;
  51522. var behaviors = this.behaviors;
  51523. var behaviorType;
  51524. // Check if behavior has tick and/or tock and add the behavior to the appropriate list.
  51525. for (behaviorType in behaviors) {
  51526. if (!behavior[behaviorType]) { continue; }
  51527. behaviorArr = this.behaviors[behaviorType];
  51528. if (behaviorArr.indexOf(behavior) === -1) {
  51529. behaviorArr.push(behavior);
  51530. }
  51531. }
  51532. }
  51533. },
  51534. /**
  51535. * For tests.
  51536. */
  51537. getPointerLockElement: {
  51538. value: function () {
  51539. return document.pointerLockElement;
  51540. },
  51541. writable: window.debug
  51542. },
  51543. /**
  51544. * For tests.
  51545. */
  51546. checkHeadsetConnected: {
  51547. value: utils.device.checkHeadsetConnected,
  51548. writable: window.debug
  51549. },
  51550. /**
  51551. * Call `requestPresent` if WebVR or WebVR polyfill.
  51552. * Call `requestFullscreen` on desktop.
  51553. * Handle events, states, fullscreen styles.
  51554. *
  51555. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  51556. * manually calling requestPresent via WebVR API directly).
  51557. * @returns {Promise}
  51558. */
  51559. enterVR: {
  51560. value: function (fromExternal) {
  51561. var self = this;
  51562. var vrDisplay;
  51563. var vrManager = self.renderer.vr;
  51564. // Don't enter VR if already in VR.
  51565. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  51566. // Enter VR via WebVR API.
  51567. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  51568. vrDisplay = utils.device.getVRDisplay();
  51569. vrManager.setDevice(vrDisplay);
  51570. vrManager.enabled = true;
  51571. vrManager.setPoseTarget(this.camera.el.object3D);
  51572. return vrDisplay.requestPresent([{source: this.canvas}])
  51573. .then(enterVRSuccess, enterVRFailure);
  51574. }
  51575. enterVRSuccess();
  51576. return Promise.resolve();
  51577. function enterVRSuccess () {
  51578. self.addState('vr-mode');
  51579. self.emit('enter-vr', {target: self});
  51580. // Lock to landscape orientation on mobile.
  51581. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  51582. screen.orientation.lock('landscape');
  51583. }
  51584. self.addFullScreenStyles();
  51585. // On mobile, the polyfill handles fullscreen.
  51586. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  51587. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  51588. // connected.
  51589. if (!self.isMobile && !self.checkHeadsetConnected()) {
  51590. requestFullscreen(self.canvas);
  51591. }
  51592. self.resize();
  51593. }
  51594. function enterVRFailure (err) {
  51595. if (err && err.message) {
  51596. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  51597. } else {
  51598. throw new Error('Failed to enter VR mode (`requestPresent`).');
  51599. }
  51600. }
  51601. },
  51602. writable: true
  51603. },
  51604. /**
  51605. * Call `exitPresent` if WebVR or WebVR polyfill.
  51606. * Handle events, states, fullscreen styles.
  51607. *
  51608. * @param {bool} fromExternal - Whether exiting VR due to an external event (e.g.,
  51609. * Oculus Browser GearVR back button).
  51610. * @returns {Promise}
  51611. */
  51612. exitVR: {
  51613. value: function (fromExternal) {
  51614. var self = this;
  51615. var vrDisplay;
  51616. // Don't exit VR if not in VR.
  51617. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  51618. exitFullscreen();
  51619. // Handle exiting VR if not yet already and in a headset or polyfill.
  51620. if (!fromExternal && (this.checkHeadsetConnected() || this.isMobile)) {
  51621. this.renderer.vr.enabled = false;
  51622. vrDisplay = utils.device.getVRDisplay();
  51623. return vrDisplay.exitPresent().then(exitVRSuccess, exitVRFailure);
  51624. }
  51625. // Handle exiting VR in all other cases (2D fullscreen, external exit VR event).
  51626. exitVRSuccess();
  51627. return Promise.resolve();
  51628. function exitVRSuccess () {
  51629. self.removeState('vr-mode');
  51630. // Lock to landscape orientation on mobile.
  51631. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  51632. screen.orientation.unlock();
  51633. }
  51634. // Exiting VR in embedded mode, no longer need fullscreen styles.
  51635. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  51636. self.resize();
  51637. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(this.canvas); }
  51638. self.emit('exit-vr', {target: self});
  51639. }
  51640. function exitVRFailure (err) {
  51641. if (err && err.message) {
  51642. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  51643. } else {
  51644. throw new Error('Failed to exit VR mode (`exitPresent`).');
  51645. }
  51646. }
  51647. },
  51648. writable: true
  51649. },
  51650. pointerRestricted: {
  51651. value: function () {
  51652. if (this.canvas) {
  51653. var pointerLockElement = this.getPointerLockElement();
  51654. if (pointerLockElement && pointerLockElement !== this.canvas && document.exitPointerLock) {
  51655. // Recreate pointer lock on the canvas, if taken on another element.
  51656. document.exitPointerLock();
  51657. }
  51658. if (this.canvas.requestPointerLock) {
  51659. this.canvas.requestPointerLock();
  51660. }
  51661. }
  51662. }
  51663. },
  51664. pointerUnrestricted: {
  51665. value: function () {
  51666. var pointerLockElement = this.getPointerLockElement();
  51667. if (pointerLockElement && pointerLockElement === this.canvas && document.exitPointerLock) {
  51668. document.exitPointerLock();
  51669. }
  51670. }
  51671. },
  51672. /**
  51673. * Handle `vrdisplaypresentchange` event for exiting VR through other means than
  51674. * `<ESC>` key. For example, GearVR back button on Oculus Browser.
  51675. */
  51676. onVRPresentChange: {
  51677. value: function (evt) {
  51678. // Polyfill places display inside the detail property
  51679. var display = evt.display || evt.detail.display;
  51680. // Entering VR.
  51681. if (display.isPresenting) {
  51682. this.enterVR(true);
  51683. return;
  51684. }
  51685. // Exiting VR.
  51686. this.exitVR(true);
  51687. }
  51688. },
  51689. /**
  51690. * Wraps Entity.getAttribute to take into account for systems.
  51691. * If system exists, then return system data rather than possible component data.
  51692. */
  51693. getAttribute: {
  51694. value: function (attr) {
  51695. var system = this.systems[attr];
  51696. if (system) { return system.data; }
  51697. return AEntity.prototype.getAttribute.call(this, attr);
  51698. }
  51699. },
  51700. /**
  51701. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  51702. * what `getAttribute` is now. Now legacy code.
  51703. */
  51704. getComputedAttribute: {
  51705. value: function (attr) {
  51706. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  51707. this.getAttribute(attr);
  51708. }
  51709. },
  51710. /**
  51711. * Wraps Entity.getDOMAttribute to take into account for systems.
  51712. * If system exists, then return system data rather than possible component data.
  51713. */
  51714. getDOMAttribute: {
  51715. value: function (attr) {
  51716. var system = this.systems[attr];
  51717. if (system) { return system.data; }
  51718. return AEntity.prototype.getDOMAttribute.call(this, attr);
  51719. }
  51720. },
  51721. /**
  51722. * Wrap Entity.setAttribute to take into account for systems.
  51723. * If system exists, then skip component initialization checks and do a normal
  51724. * setAttribute.
  51725. */
  51726. setAttribute: {
  51727. value: function (attr, value, componentPropValue) {
  51728. var system = this.systems[attr];
  51729. if (system) {
  51730. ANode.prototype.setAttribute.call(this, attr, value);
  51731. system.updateProperties(value);
  51732. return;
  51733. }
  51734. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  51735. }
  51736. },
  51737. /**
  51738. * @param {object} behavior - A component.
  51739. */
  51740. removeBehavior: {
  51741. value: function (behavior) {
  51742. var behaviorArr;
  51743. var behaviorType;
  51744. var behaviors = this.behaviors;
  51745. var index;
  51746. // Check if behavior has tick and/or tock and remove the behavior from the appropriate array.
  51747. for (behaviorType in behaviors) {
  51748. if (!behavior[behaviorType]) { continue; }
  51749. behaviorArr = this.behaviors[behaviorType];
  51750. index = behaviorArr.indexOf(behavior);
  51751. if (index !== -1) { behaviorArr.splice(index, 1); }
  51752. }
  51753. }
  51754. },
  51755. resize: {
  51756. value: function () {
  51757. var camera = this.camera;
  51758. var canvas = this.canvas;
  51759. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  51760. var size;
  51761. var vrDevice;
  51762. var isVRPresenting;
  51763. vrDevice = this.renderer.vr.getDevice();
  51764. isVRPresenting = this.renderer.vr.enabled && vrDevice && vrDevice.isPresenting;
  51765. // Do not update renderer, if a camera or a canvas have not been injected.
  51766. // In VR mode, three handles canvas resize based on the dimensions returned by
  51767. // the getEyeParameters function of the WebVR API. These dimensions are independent of
  51768. // the window size, therefore should not be overwritten with the window's width and height,
  51769. // except when in fullscreen mode.
  51770. if (!camera || !canvas || (this.is('vr-mode') && (this.isMobile || isVRPresenting))) { return; }
  51771. // Update camera.
  51772. size = getCanvasSize(canvas, embedded);
  51773. camera.aspect = size.width / size.height;
  51774. camera.updateProjectionMatrix();
  51775. // Notify renderer of size change.
  51776. this.renderer.setSize(size.width, size.height, false);
  51777. },
  51778. writable: true
  51779. },
  51780. setupRenderer: {
  51781. value: function () {
  51782. var renderer;
  51783. renderer = this.renderer = new THREE.WebGLRenderer({
  51784. canvas: this.canvas,
  51785. antialias: shouldAntiAlias(this),
  51786. alpha: true
  51787. });
  51788. renderer.setPixelRatio(window.devicePixelRatio);
  51789. renderer.sortObjects = false;
  51790. },
  51791. writable: window.debug
  51792. },
  51793. /**
  51794. * Handler attached to elements to help scene know when to kick off.
  51795. * Scene waits for all entities to load.
  51796. */
  51797. play: {
  51798. value: function () {
  51799. var self = this;
  51800. if (this.renderStarted) {
  51801. AEntity.prototype.play.call(this);
  51802. return;
  51803. }
  51804. this.addEventListener('loaded', function () {
  51805. AEntity.prototype.play.call(this); // .play() *before* render.
  51806. // Wait for camera if necessary before rendering.
  51807. if (this.camera) {
  51808. startRender(this);
  51809. return;
  51810. }
  51811. this.addEventListener('camera-set-active', function () { startRender(this); });
  51812. function startRender (sceneEl) {
  51813. if (sceneEl.renderStarted) { return; }
  51814. sceneEl.resize();
  51815. // Kick off render loop.
  51816. if (sceneEl.renderer) {
  51817. if (window.performance) {
  51818. window.performance.mark('render-started');
  51819. }
  51820. sceneEl.clock = new THREE.Clock();
  51821. sceneEl.render();
  51822. sceneEl.renderStarted = true;
  51823. sceneEl.emit('renderstart');
  51824. }
  51825. }
  51826. });
  51827. // setTimeout to wait for all nodes to attach and run their callbacks.
  51828. setTimeout(function () {
  51829. AEntity.prototype.load.call(self);
  51830. });
  51831. }
  51832. },
  51833. /**
  51834. * Wrap `updateComponent` to not initialize the component if the component has a system
  51835. * (aframevr/aframe#2365).
  51836. */
  51837. updateComponent: {
  51838. value: function (componentName) {
  51839. if (componentName in systems) { return; }
  51840. AEntity.prototype.updateComponent.apply(this, arguments);
  51841. }
  51842. },
  51843. /**
  51844. * Behavior-updater meant to be called from scene render.
  51845. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  51846. * needing to render.
  51847. */
  51848. tick: {
  51849. value: function (time, timeDelta) {
  51850. var i;
  51851. var systems = this.systems;
  51852. // Animations.
  51853. TWEEN.update();
  51854. // Components.
  51855. for (i = 0; i < this.behaviors.tick.length; i++) {
  51856. if (!this.behaviors.tick[i].el.isPlaying) { continue; }
  51857. this.behaviors.tick[i].tick(time, timeDelta);
  51858. }
  51859. // Systems.
  51860. for (i = 0; i < this.systemNames.length; i++) {
  51861. if (!systems[this.systemNames[i]].tick) { continue; }
  51862. systems[this.systemNames[i]].tick(time, timeDelta);
  51863. }
  51864. }
  51865. },
  51866. /**
  51867. * Behavior-updater meant to be called after scene render for post processing purposes.
  51868. * Abstracted to a different function to facilitate unit testing (`scene.tock()`) without
  51869. * needing to render.
  51870. */
  51871. tock: {
  51872. value: function (time, timeDelta) {
  51873. var i;
  51874. var systems = this.systems;
  51875. // Components.
  51876. for (i = 0; i < this.behaviors.tock.length; i++) {
  51877. if (!this.behaviors.tock[i].el.isPlaying) { continue; }
  51878. this.behaviors.tock[i].tock(time, timeDelta);
  51879. }
  51880. // Systems.
  51881. for (i = 0; i < this.systemNames.length; i++) {
  51882. if (!systems[this.systemNames[i]].tock) { continue; }
  51883. systems[this.systemNames[i]].tock(time, timeDelta);
  51884. }
  51885. }
  51886. },
  51887. /**
  51888. * The render loop.
  51889. *
  51890. * Updates animations.
  51891. * Updates behaviors.
  51892. * Renders with request animation frame.
  51893. */
  51894. render: {
  51895. value: function () {
  51896. var delta = this.clock.getDelta() * 1000;
  51897. var renderer = this.renderer;
  51898. this.time = this.clock.elapsedTime * 1000;
  51899. if (this.isPlaying) { this.tick(this.time, delta); }
  51900. renderer.animate(this.render);
  51901. renderer.render(this.object3D, this.camera, this.renderTarget);
  51902. if (this.isPlaying) { this.tock(this.time, delta); }
  51903. },
  51904. writable: true
  51905. }
  51906. })
  51907. });
  51908. /**
  51909. * Return the canvas size where the scene will be rendered
  51910. * It will be always the window size except when the scene
  51911. * is embedded. The parent size will be returned in that case
  51912. *
  51913. * @param {object} canvasEl - the canvas element
  51914. * @param {boolean} embedded - Is the scene embedded?
  51915. */
  51916. function getCanvasSize (canvasEl, embedded) {
  51917. if (embedded) {
  51918. return {
  51919. height: canvasEl.parentElement.offsetHeight,
  51920. width: canvasEl.parentElement.offsetWidth
  51921. };
  51922. }
  51923. return {
  51924. height: window.innerHeight,
  51925. width: window.innerWidth
  51926. };
  51927. }
  51928. function requestFullscreen (canvas) {
  51929. var requestFullscreen =
  51930. canvas.requestFullscreen ||
  51931. canvas.webkitRequestFullscreen ||
  51932. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  51933. canvas.msRequestFullscreen;
  51934. requestFullscreen.apply(canvas);
  51935. }
  51936. function exitFullscreen () {
  51937. if (document.exitFullscreen) {
  51938. document.exitFullscreen();
  51939. } else if (document.mozCancelFullScreen) {
  51940. document.mozCancelFullScreen();
  51941. } else if (document.webkitExitFullscreen) {
  51942. document.webkitExitFullscreen();
  51943. }
  51944. }
  51945. /**
  51946. * Determines if renderer anti-aliasing should be enabled.
  51947. * Enabled by default if has native WebVR or is desktop.
  51948. *
  51949. * @returns {bool}
  51950. */
  51951. function shouldAntiAlias (sceneEl) {
  51952. // Explicitly set.
  51953. if (sceneEl.getAttribute('antialias') !== null) {
  51954. return sceneEl.getAttribute('antialias') === 'true';
  51955. }
  51956. // Default not AA for mobile.
  51957. return !sceneEl.isMobile;
  51958. }
  51959. module.exports.shouldAntiAlias = shouldAntiAlias; // For testing.
  51960. function setupCanvas (sceneEl) {
  51961. var canvasEl;
  51962. canvasEl = document.createElement('canvas');
  51963. canvasEl.classList.add('a-canvas');
  51964. // Mark canvas as provided/injected by A-Frame.
  51965. canvasEl.dataset.aframeCanvas = true;
  51966. sceneEl.appendChild(canvasEl);
  51967. document.addEventListener('fullscreenchange', onFullScreenChange);
  51968. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  51969. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  51970. // Prevent overscroll on mobile.
  51971. canvasEl.addEventListener('touchmove', function (event) { event.preventDefault(); });
  51972. // Set canvas on scene.
  51973. sceneEl.canvas = canvasEl;
  51974. sceneEl.emit('render-target-loaded', {target: canvasEl});
  51975. // For unknown reasons a synchronous resize does not work on desktop when
  51976. // entering/exiting fullscreen.
  51977. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  51978. function onFullScreenChange () {
  51979. var fullscreenEl =
  51980. document.fullscreenElement ||
  51981. document.mozFullScreenElement ||
  51982. document.webkitFullscreenElement;
  51983. // No fullscren element === exit fullscreen
  51984. if (!fullscreenEl) { sceneEl.exitVR(); }
  51985. document.activeElement.blur();
  51986. document.body.focus();
  51987. }
  51988. }
  51989. module.exports.setupCanvas = setupCanvas; // For testing.
  51990. },{"../../lib/three":174,"../../utils/":196,"../a-entity":122,"../a-node":124,"../a-register-element":125,"../system":136,"./metaTags":130,"./postMessage":131,"./scenes":132,"./wakelock":133,"@tweenjs/tween.js":1}],130:[function(_dereq_,module,exports){
  51991. var constants = _dereq_('../../constants/');
  51992. var extend = _dereq_('../../utils').extend;
  51993. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  51994. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  51995. // W3C-standardised meta tags.
  51996. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  51997. Meta({name: 'theme-color', content: 'black'})
  51998. ];
  51999. var MOBILE_IOS_HEAD_TAGS = [
  52000. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  52001. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  52002. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  52003. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  52004. ];
  52005. function Meta (attrs) {
  52006. return {
  52007. tagName: 'meta',
  52008. attributes: attrs,
  52009. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  52010. };
  52011. }
  52012. function Link (attrs) {
  52013. return {
  52014. tagName: 'link',
  52015. attributes: attrs,
  52016. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  52017. };
  52018. }
  52019. /**
  52020. * Injects the necessary metatags in the document for mobile support:
  52021. * 1. Prevent the user to zoom in the document.
  52022. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  52023. * values and the canvas is properly scaled.
  52024. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  52025. * iOS.
  52026. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  52027. *
  52028. * @param {object} scene - Scene element
  52029. * @returns {Array}
  52030. */
  52031. module.exports.inject = function injectHeadTags (scene) {
  52032. var headEl = document.head;
  52033. var headScriptEl = headEl.querySelector('script');
  52034. var tag;
  52035. var headTags = [];
  52036. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  52037. if (scene.isIOS) {
  52038. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  52039. }
  52040. return headTags;
  52041. function createAndInjectTag (tagObj) {
  52042. if (!tagObj || tagObj.exists()) { return; }
  52043. tag = createTag(tagObj);
  52044. if (!tag) { return; }
  52045. if (headScriptEl) {
  52046. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  52047. } else {
  52048. headEl.appendChild(tag);
  52049. }
  52050. headTags.push(tag);
  52051. }
  52052. };
  52053. function createTag (tagObj) {
  52054. if (!tagObj || !tagObj.tagName) { return; }
  52055. var meta = document.createElement(tagObj.tagName);
  52056. meta.setAttribute(constants.AFRAME_INJECTED, '');
  52057. return extend(meta, tagObj.attributes);
  52058. }
  52059. },{"../../constants/":117,"../../utils":196}],131:[function(_dereq_,module,exports){
  52060. var bind = _dereq_('../../utils/bind');
  52061. var isIframed = _dereq_('../../utils/').isIframed;
  52062. /**
  52063. * Provides a post message API for scenes contained
  52064. * in an iframe.
  52065. */
  52066. module.exports = function initPostMessageAPI (scene) {
  52067. // Handles fullscreen behavior when inside an iframe.
  52068. if (!isIframed()) { return; }
  52069. // postMessage API handler
  52070. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  52071. };
  52072. function postMessageAPIHandler (event) {
  52073. var scene = this;
  52074. if (!event.data) { return; }
  52075. switch (event.data.type) {
  52076. case 'vr': {
  52077. switch (event.data.data) {
  52078. case 'enter':
  52079. scene.enterVR();
  52080. break;
  52081. case 'exit':
  52082. scene.exitVR();
  52083. break;
  52084. }
  52085. }
  52086. }
  52087. }
  52088. },{"../../utils/":196,"../../utils/bind":190}],132:[function(_dereq_,module,exports){
  52089. /*
  52090. Scene index for keeping track of created scenes.
  52091. */
  52092. module.exports = [];
  52093. },{}],133:[function(_dereq_,module,exports){
  52094. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  52095. module.exports = function initWakelock (scene) {
  52096. if (!scene.isMobile) { return; }
  52097. var wakelock = scene.wakelock = new Wakelock();
  52098. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  52099. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  52100. };
  52101. },{"../../../vendor/wakelock/wakelock":205}],134:[function(_dereq_,module,exports){
  52102. var utils = _dereq_('../utils/');
  52103. var PropertyTypes = _dereq_('./propertyTypes');
  52104. var debug = utils.debug;
  52105. var isValidDefaultValue = PropertyTypes.isValidDefaultValue;
  52106. var propertyTypes = PropertyTypes.propertyTypes;
  52107. var warn = debug('core:schema:warn');
  52108. /**
  52109. * A schema is classified as a schema for a single property if:
  52110. * - `type` is defined on the schema as a string.
  52111. * - OR `default` is defined on the schema, as a reserved keyword.
  52112. * - OR schema is empty.
  52113. */
  52114. function isSingleProperty (schema) {
  52115. if ('type' in schema) {
  52116. return typeof schema.type === 'string';
  52117. }
  52118. return 'default' in schema;
  52119. }
  52120. module.exports.isSingleProperty = isSingleProperty;
  52121. /**
  52122. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  52123. *
  52124. * @param {object} schema
  52125. * @param {string} componentName
  52126. * @returns {object} Schema.
  52127. */
  52128. module.exports.process = function (schema, componentName) {
  52129. var propName;
  52130. // For single property schema, run processPropDefinition over the whole schema.
  52131. if (isSingleProperty(schema)) {
  52132. return processPropertyDefinition(schema, componentName);
  52133. }
  52134. // For multi-property schema, run processPropDefinition over each property definition.
  52135. for (propName in schema) {
  52136. schema[propName] = processPropertyDefinition(schema[propName], componentName);
  52137. }
  52138. return schema;
  52139. };
  52140. /**
  52141. * Inject default value, parser, stringifier for single property.
  52142. *
  52143. * @param {object} propDefinition
  52144. * @param {string} componentName
  52145. */
  52146. function processPropertyDefinition (propDefinition, componentName) {
  52147. var defaultVal = propDefinition.default;
  52148. var isCustomType;
  52149. var propType;
  52150. var typeName = propDefinition.type;
  52151. // Type inference.
  52152. if (!propDefinition.type) {
  52153. if (defaultVal !== undefined &&
  52154. (typeof defaultVal === 'boolean' || typeof defaultVal === 'number')) {
  52155. // Type inference.
  52156. typeName = typeof defaultVal;
  52157. } else if (Array.isArray(defaultVal)) {
  52158. typeName = 'array';
  52159. } else {
  52160. // Fall back to string.
  52161. typeName = 'string';
  52162. }
  52163. } else if (propDefinition.type === 'bool') {
  52164. typeName = 'boolean';
  52165. } else if (propDefinition.type === 'float') {
  52166. typeName = 'number';
  52167. }
  52168. propType = propertyTypes[typeName];
  52169. if (!propType) {
  52170. warn('Unknown property type for component `' + componentName + '`: ' + typeName);
  52171. }
  52172. // Fill in parse and stringify using property types.
  52173. isCustomType = !!propDefinition.parse;
  52174. propDefinition.parse = propDefinition.parse || propType.parse;
  52175. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  52176. // Fill in type name.
  52177. propDefinition.type = typeName;
  52178. // Check that default value exists.
  52179. if ('default' in propDefinition) {
  52180. // Check that default values are valid.
  52181. if (!isCustomType && !isValidDefaultValue(typeName, defaultVal)) {
  52182. warn('Default value `' + defaultVal + '` does not match type `' + typeName +
  52183. '` in component `' + componentName + '`');
  52184. }
  52185. } else {
  52186. // Fill in default value.
  52187. propDefinition.default = propType.default;
  52188. }
  52189. return propDefinition;
  52190. }
  52191. module.exports.processPropertyDefinition = processPropertyDefinition;
  52192. /**
  52193. * Parse propData using schema. Use default values if not existing in propData.
  52194. *
  52195. * @param {object} propData - Unparsed properties.
  52196. * @param {object} schema - Property types definition.
  52197. * @param {boolean} getPartialData - Whether to return full component data or just the data
  52198. * with keys in `propData`.
  52199. * @param {string } componentName - Name of the component, used for the property warning.
  52200. * @param {boolean} silent - Suppress warning messages.
  52201. */
  52202. module.exports.parseProperties = (function () {
  52203. var propNames = [];
  52204. return function (propData, schema, getPartialData, componentName, silent) {
  52205. var i;
  52206. var propName;
  52207. var propDefinition;
  52208. var propValue;
  52209. propNames.length = 0;
  52210. for (propName in (getPartialData ? propData : schema)) { propNames.push(propName); }
  52211. if (propData === null || typeof propData !== 'object') { return propData; }
  52212. // Validation errors.
  52213. for (propName in propData) {
  52214. if (!schema[propName] && !silent) {
  52215. warn('Unknown property `' + propName +
  52216. '` for component/system `' + componentName + '`.');
  52217. }
  52218. }
  52219. for (i = 0; i < propNames.length; i++) {
  52220. propName = propNames[i];
  52221. propDefinition = schema[propName];
  52222. propValue = propData[propName];
  52223. if (!(schema[propName])) { return; }
  52224. propData[propName] = parseProperty(propValue, propDefinition);
  52225. }
  52226. return propData;
  52227. };
  52228. })();
  52229. /**
  52230. * Deserialize a single property.
  52231. */
  52232. function parseProperty (value, propDefinition) {
  52233. // Use default value if value is falsy.
  52234. if (value === undefined || value === null || value === '') {
  52235. value = propDefinition.default;
  52236. if (Array.isArray(value)) { value = value.slice(); }
  52237. }
  52238. // Invoke property type parser.
  52239. return propDefinition.parse(value, propDefinition.default);
  52240. }
  52241. module.exports.parseProperty = parseProperty;
  52242. /**
  52243. * Serialize a group of properties.
  52244. */
  52245. module.exports.stringifyProperties = function (propData, schema) {
  52246. var propName;
  52247. var propDefinition;
  52248. var propValue;
  52249. var stringifiedData = {};
  52250. var value;
  52251. for (propName in propData) {
  52252. propDefinition = schema[propName];
  52253. propValue = propData[propName];
  52254. value = propValue;
  52255. if (typeof value === 'object') {
  52256. value = stringifyProperty(propValue, propDefinition);
  52257. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  52258. }
  52259. stringifiedData[propName] = value;
  52260. }
  52261. return stringifiedData;
  52262. };
  52263. /**
  52264. * Serialize a single property.
  52265. */
  52266. function stringifyProperty (value, propDefinition) {
  52267. // This function stringifies but it's used in a context where
  52268. // there's always second stringification pass. By returning the original
  52269. // value when it's not an object we save one unnecessary call
  52270. // to JSON.stringify.
  52271. if (typeof value !== 'object') { return value; }
  52272. // if there's no schema for the property we use standar JSON stringify
  52273. if (!propDefinition || value === null) { return JSON.stringify(value); }
  52274. return propDefinition.stringify(value);
  52275. }
  52276. module.exports.stringifyProperty = stringifyProperty;
  52277. },{"../utils/":196,"./propertyTypes":128}],135:[function(_dereq_,module,exports){
  52278. var schema = _dereq_('./schema');
  52279. var processSchema = schema.process;
  52280. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  52281. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  52282. var THREE = _dereq_('../lib/three');
  52283. var utils = _dereq_('../utils');
  52284. // A-Frame properties to three.js uniform types.
  52285. var propertyToThreeMapping = {
  52286. array: 'v3',
  52287. color: 'v3',
  52288. int: 'i',
  52289. number: 'f',
  52290. map: 't',
  52291. time: 'f',
  52292. vec2: 'v2',
  52293. vec3: 'v3',
  52294. vec4: 'v4'
  52295. };
  52296. /**
  52297. * Shader class definition.
  52298. *
  52299. * Shaders extend the material component API so you can create your own library
  52300. * of customized materials
  52301. *
  52302. */
  52303. var Shader = module.exports.Shader = function () {};
  52304. Shader.prototype = {
  52305. /**
  52306. * Contains the type schema and defaults for the data values.
  52307. * Data is coerced into the types of the values of the defaults.
  52308. */
  52309. schema: {},
  52310. vertexShader:
  52311. 'void main() {' +
  52312. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  52313. '}',
  52314. fragmentShader:
  52315. 'void main() {' +
  52316. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  52317. '}',
  52318. /**
  52319. * Init handler. Similar to attachedCallback.
  52320. * Called during shader initialization and is only run once.
  52321. */
  52322. init: function (data) {
  52323. this.attributes = this.initVariables(data, 'attribute');
  52324. this.uniforms = this.initVariables(data, 'uniform');
  52325. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  52326. // attributes: this.attributes,
  52327. uniforms: this.uniforms,
  52328. vertexShader: this.vertexShader,
  52329. fragmentShader: this.fragmentShader
  52330. });
  52331. return this.material;
  52332. },
  52333. initVariables: function (data, type) {
  52334. var variables = {};
  52335. var schema = this.schema;
  52336. Object.keys(schema).forEach(function processSchema (key) {
  52337. if (schema[key].is !== type) { return; }
  52338. var varType = propertyToThreeMapping[schema[key].type];
  52339. variables[key] = {
  52340. type: varType,
  52341. value: undefined // Let updateVariables handle setting these.
  52342. };
  52343. });
  52344. return variables;
  52345. },
  52346. /**
  52347. * Update handler. Similar to attributeChangedCallback.
  52348. * Called whenever the associated material data changes.
  52349. *
  52350. * @param {object} data - New material data.
  52351. */
  52352. update: function (data) {
  52353. this.updateVariables(data, 'attribute');
  52354. this.updateVariables(data, 'uniform');
  52355. },
  52356. updateVariables: function (data, type) {
  52357. var self = this;
  52358. var variables = type === 'uniform' ? this.uniforms : this.attributes;
  52359. var schema = this.schema;
  52360. Object.keys(data).forEach(function processData (key) {
  52361. var materialKey;
  52362. if (!schema[key] || schema[key].is !== type) { return; }
  52363. if (schema[key].type === 'map') {
  52364. // If data unchanged, get out early.
  52365. if (!variables[key] || variables[key].value === data[key]) { return; }
  52366. // Special handling is needed for textures.
  52367. materialKey = '_texture_' + key;
  52368. // We can't actually set the variable correctly until we've loaded the texture.
  52369. self.el.addEventListener('materialtextureloaded', function () {
  52370. variables[key].value = self.material[materialKey];
  52371. variables[key].needsUpdate = true;
  52372. });
  52373. // Kick off the texture update now that handler is added.
  52374. utils.material.updateMapMaterialFromData(materialKey, key, self, data);
  52375. return;
  52376. }
  52377. variables[key].value = self.parseValue(schema[key].type, data[key]);
  52378. variables[key].needsUpdate = true;
  52379. });
  52380. },
  52381. parseValue: function (type, value) {
  52382. var color;
  52383. switch (type) {
  52384. case 'vec2': {
  52385. return new THREE.Vector2(value.x, value.y);
  52386. }
  52387. case 'vec3': {
  52388. return new THREE.Vector3(value.x, value.y, value.z);
  52389. }
  52390. case 'vec4': {
  52391. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  52392. }
  52393. case 'color': {
  52394. color = new THREE.Color(value);
  52395. return new THREE.Vector3(color.r, color.g, color.b);
  52396. }
  52397. case 'map': {
  52398. return THREE.ImageUtils.loadTexture(value);
  52399. }
  52400. default: {
  52401. return value;
  52402. }
  52403. }
  52404. }
  52405. };
  52406. /**
  52407. * Registers a shader to A-Frame.
  52408. *
  52409. * @param {string} name - shader name.
  52410. * @param {object} definition - shader property and methods.
  52411. * @returns {object} Shader.
  52412. */
  52413. module.exports.registerShader = function (name, definition) {
  52414. var NewShader;
  52415. var proto = {};
  52416. // Format definition object to prototype object.
  52417. Object.keys(definition).forEach(function (key) {
  52418. proto[key] = {
  52419. value: definition[key],
  52420. writable: true
  52421. };
  52422. });
  52423. if (shaders[name]) {
  52424. throw new Error('The shader ' + name + ' has been already registered');
  52425. }
  52426. NewShader = function () { Shader.call(this); };
  52427. NewShader.prototype = Object.create(Shader.prototype, proto);
  52428. NewShader.prototype.name = name;
  52429. NewShader.prototype.constructor = NewShader;
  52430. shaders[name] = {
  52431. Shader: NewShader,
  52432. schema: processSchema(NewShader.prototype.schema)
  52433. };
  52434. shaderNames.push(name);
  52435. return NewShader;
  52436. };
  52437. },{"../lib/three":174,"../utils":196,"./schema":134}],136:[function(_dereq_,module,exports){
  52438. var components = _dereq_('./component');
  52439. var schema = _dereq_('./schema');
  52440. var utils = _dereq_('../utils/');
  52441. var parseProperties = schema.parseProperties;
  52442. var parseProperty = schema.parseProperty;
  52443. var processSchema = schema.process;
  52444. var isSingleProp = schema.isSingleProperty;
  52445. var styleParser = utils.styleParser;
  52446. var systems = module.exports.systems = {}; // Keep track of registered systems.
  52447. /**
  52448. * System class definition.
  52449. *
  52450. * Systems provide global scope and services to a group of instantiated components of the
  52451. * same class. They can also help abstract logic away from components such that components
  52452. * only have to worry about data.
  52453. *
  52454. * For example, a physics component that creates a physics world that oversees
  52455. * all entities with a physics or rigid body component.
  52456. *
  52457. * TODO: Have the System prototype reuse the Component prototype. Most code is copied
  52458. * and some pieces are missing from the Component facilities (e.g., attribute caching,
  52459. * setAttribute behavior).
  52460. *
  52461. * @member {string} name - Name that system is registered under.
  52462. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  52463. */
  52464. var System = module.exports.System = function (sceneEl) {
  52465. var component = components && components.components[this.name];
  52466. // Set reference to scene.
  52467. this.el = sceneEl;
  52468. this.sceneEl = sceneEl;
  52469. // Set reference to matching component (if exists).
  52470. if (component) { component.Component.prototype.system = this; }
  52471. // Process system configuration.
  52472. this.buildData();
  52473. this.init();
  52474. this.update({});
  52475. };
  52476. System.prototype = {
  52477. /**
  52478. * Schema to configure system.
  52479. */
  52480. schema: {},
  52481. /**
  52482. * Init handler. Called during scene initialization and is only run once.
  52483. * Systems can use this to set initial state.
  52484. */
  52485. init: function () { /* no-op */ },
  52486. /**
  52487. * Update handler. Called during scene attribute updates.
  52488. * Systems can use this to dynamically update their state.
  52489. */
  52490. update: function (oldData) { /* no-op */ },
  52491. /**
  52492. * Build data and call update handler.
  52493. *
  52494. * @private
  52495. */
  52496. updateProperties: function (rawData) {
  52497. var oldData = this.data;
  52498. if (!Object.keys(schema).length) { return; }
  52499. this.buildData(rawData);
  52500. this.update(oldData);
  52501. },
  52502. /**
  52503. * Parse data.
  52504. */
  52505. buildData: function (rawData) {
  52506. var schema = this.schema;
  52507. if (!Object.keys(schema).length) { return; }
  52508. rawData = rawData || window.HTMLElement.prototype.getAttribute.call(this.sceneEl, this.name);
  52509. if (isSingleProp(schema)) {
  52510. this.data = parseProperty(rawData, schema);
  52511. } else {
  52512. this.data = parseProperties(styleParser.parse(rawData) || {}, schema);
  52513. }
  52514. },
  52515. /**
  52516. * Tick handler.
  52517. * Called on each tick of the scene render loop.
  52518. * Affected by play and pause.
  52519. *
  52520. * @param {number} time - Scene tick time.
  52521. * @param {number} timeDelta - Difference in current render time and previous render time.
  52522. */
  52523. tick: undefined,
  52524. /**
  52525. * Tock handler.
  52526. * Called on each tock of the scene render loop.
  52527. * Affected by play and pause.
  52528. *
  52529. * @param {number} time - Scene tick time.
  52530. * @param {number} timeDelta - Difference in current render time and previous render time.
  52531. */
  52532. tock: undefined,
  52533. /**
  52534. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  52535. */
  52536. play: function () { /* no-op */ },
  52537. /**
  52538. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  52539. */
  52540. pause: function () { /* no-op */ }
  52541. };
  52542. /**
  52543. * Registers a system to A-Frame.
  52544. *
  52545. * @param {string} name - Component name.
  52546. * @param {object} definition - Component property and methods.
  52547. * @returns {object} Component.
  52548. */
  52549. module.exports.registerSystem = function (name, definition) {
  52550. var i;
  52551. var NewSystem;
  52552. var proto = {};
  52553. var scenes = utils.findAllScenes(document);
  52554. // Format definition object to prototype object.
  52555. Object.keys(definition).forEach(function (key) {
  52556. proto[key] = {
  52557. value: definition[key],
  52558. writable: true
  52559. };
  52560. });
  52561. if (systems[name]) {
  52562. throw new Error('The system `' + name + '` has been already registered. ' +
  52563. 'Check that you are not loading two versions of the same system ' +
  52564. 'or two different systems of the same name.');
  52565. }
  52566. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  52567. NewSystem.prototype = Object.create(System.prototype, proto);
  52568. NewSystem.prototype.name = name;
  52569. NewSystem.prototype.constructor = NewSystem;
  52570. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  52571. systems[name] = NewSystem;
  52572. // Initialize systems for existing scenes
  52573. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  52574. };
  52575. },{"../utils/":196,"./component":126,"./schema":134}],137:[function(_dereq_,module,exports){
  52576. _dereq_('./pivot');
  52577. },{"./pivot":138}],138:[function(_dereq_,module,exports){
  52578. var registerComponent = _dereq_('../../core/component').registerComponent;
  52579. var THREE = _dereq_('../../lib/three');
  52580. var originalPosition = new THREE.Vector3();
  52581. var originalRotation = new THREE.Vector3();
  52582. /**
  52583. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  52584. */
  52585. registerComponent('pivot', {
  52586. dependencies: ['position'],
  52587. schema: {type: 'vec3'},
  52588. init: function () {
  52589. var data = this.data;
  52590. var el = this.el;
  52591. var originalParent = el.object3D.parent;
  52592. var originalGroup = el.object3D;
  52593. var outerGroup = new THREE.Group();
  52594. originalPosition.copy(originalGroup.position);
  52595. originalRotation.copy(originalGroup.rotation);
  52596. // Detach current group from parent.
  52597. originalParent.remove(originalGroup);
  52598. outerGroup.add(originalGroup);
  52599. // Set new group as the outer group.
  52600. originalParent.add(outerGroup);
  52601. // Set outer group as new object3D.
  52602. el.object3D = outerGroup;
  52603. // Apply pivot to original group.
  52604. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  52605. // Offset the pivot so that world position not affected.
  52606. // And restore position onto outer group.
  52607. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  52608. data.z + originalPosition.z);
  52609. // Transfer rotation to outer group.
  52610. outerGroup.rotation.copy(originalGroup.rotation);
  52611. originalGroup.rotation.set(0, 0, 0);
  52612. }
  52613. });
  52614. },{"../../core/component":126,"../../lib/three":174}],139:[function(_dereq_,module,exports){
  52615. /**
  52616. * Common mesh defaults, mappings, and transforms.
  52617. */
  52618. var components = _dereq_('../../core/component').components;
  52619. var shaders = _dereq_('../../core/shader').shaders;
  52620. var utils = _dereq_('../../utils/');
  52621. var materialMappings = {};
  52622. Object.keys(components.material.schema).forEach(addMapping);
  52623. Object.keys(shaders.standard.schema).forEach(addMapping);
  52624. function addMapping (prop) {
  52625. // To hyphenated.
  52626. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52627. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  52628. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  52629. materialMappings[htmlAttrName] = 'material.' + prop;
  52630. }
  52631. module.exports = function getMeshMixin () {
  52632. return {
  52633. defaultComponents: {material: {}},
  52634. mappings: utils.extend({}, materialMappings)
  52635. };
  52636. };
  52637. },{"../../core/component":126,"../../core/shader":135,"../../utils/":196}],140:[function(_dereq_,module,exports){
  52638. _dereq_('./primitives/a-camera');
  52639. _dereq_('./primitives/a-collada-model');
  52640. _dereq_('./primitives/a-cursor');
  52641. _dereq_('./primitives/a-curvedimage');
  52642. _dereq_('./primitives/a-gltf-model');
  52643. _dereq_('./primitives/a-image');
  52644. _dereq_('./primitives/a-light');
  52645. _dereq_('./primitives/a-link');
  52646. _dereq_('./primitives/a-obj-model');
  52647. _dereq_('./primitives/a-sky');
  52648. _dereq_('./primitives/a-sound');
  52649. _dereq_('./primitives/a-text');
  52650. _dereq_('./primitives/a-video');
  52651. _dereq_('./primitives/a-videosphere');
  52652. _dereq_('./primitives/meshPrimitives');
  52653. },{"./primitives/a-camera":142,"./primitives/a-collada-model":143,"./primitives/a-cursor":144,"./primitives/a-curvedimage":145,"./primitives/a-gltf-model":146,"./primitives/a-image":147,"./primitives/a-light":148,"./primitives/a-link":149,"./primitives/a-obj-model":150,"./primitives/a-sky":151,"./primitives/a-sound":152,"./primitives/a-text":153,"./primitives/a-video":154,"./primitives/a-videosphere":155,"./primitives/meshPrimitives":156}],141:[function(_dereq_,module,exports){
  52654. var AEntity = _dereq_('../../core/a-entity');
  52655. var components = _dereq_('../../core/component').components;
  52656. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  52657. var utils = _dereq_('../../utils/');
  52658. var debug = utils.debug;
  52659. var setComponentProperty = utils.entity.setComponentProperty;
  52660. var log = debug('extras:primitives:debug');
  52661. var warn = debug('extras:primitives:warn');
  52662. var primitives = module.exports.primitives = {};
  52663. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  52664. name = name.toLowerCase();
  52665. log('Registering <%s>', name);
  52666. // Deprecation warning for defaultAttributes usage.
  52667. if (definition.defaultAttributes) {
  52668. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  52669. }
  52670. var primitive = registerElement(name, {
  52671. prototype: Object.create(AEntity.prototype, {
  52672. defaultComponentsFromPrimitive: {
  52673. value: definition.defaultComponents || definition.defaultAttributes || {}
  52674. },
  52675. deprecated: {value: definition.deprecated || null},
  52676. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  52677. mappings: {value: definition.mappings || {}},
  52678. createdCallback: {
  52679. value: function () {
  52680. if (definition.deprecated) { console.warn(definition.deprecated); }
  52681. this.resolveMappingCollisions();
  52682. }
  52683. },
  52684. /**
  52685. * If a mapping collides with a registered component name
  52686. * it renames the mapping to componentname-property
  52687. */
  52688. resolveMappingCollisions: {
  52689. value: function () {
  52690. var mappings = this.mappings;
  52691. var self = this;
  52692. Object.keys(mappings).forEach(function resolveCollision (key) {
  52693. var newAttribute;
  52694. if (key !== key.toLowerCase()) { warn('Mapping keys should be specified in lower case. The mapping key ' + key + ' may not be recognized'); }
  52695. if (components[key]) {
  52696. newAttribute = mappings[key].replace('.', '-');
  52697. mappings[newAttribute] = mappings[key];
  52698. delete mappings[key];
  52699. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  52700. 'The attribute ' + key + ' has the same name as a registered component and' +
  52701. ' has been renamed to ' + newAttribute);
  52702. }
  52703. });
  52704. }
  52705. },
  52706. getExtraComponents: {
  52707. value: function () {
  52708. var attr;
  52709. var data;
  52710. var i;
  52711. var mapping;
  52712. var mixins;
  52713. var path;
  52714. var self = this;
  52715. // Gather component data from default components.
  52716. data = utils.clone(this.defaultComponentsFromPrimitive);
  52717. // Factor in mixins to overwrite default components.
  52718. mixins = this.getAttribute('mixin');
  52719. if (mixins) {
  52720. mixins = mixins.trim().split(' ');
  52721. mixins.forEach(function applyMixin (mixinId) {
  52722. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  52723. Object.keys(mixinComponents).forEach(function setComponent (name) {
  52724. data[name] = extend(data[name], mixinComponents[name]);
  52725. });
  52726. });
  52727. }
  52728. // Gather component data from mappings.
  52729. for (i = 0; i < this.attributes.length; i++) {
  52730. attr = this.attributes[i];
  52731. mapping = this.mappings[attr.name];
  52732. if (mapping) {
  52733. path = utils.entity.getComponentPropertyPath(mapping);
  52734. if (path.constructor === Array) {
  52735. data[path[0]] = data[path[0]] || {};
  52736. data[path[0]][path[1]] = attr.value.trim();
  52737. } else {
  52738. data[path] = attr.value.trim();
  52739. }
  52740. continue;
  52741. }
  52742. }
  52743. return data;
  52744. /**
  52745. * For the base to be extensible, both objects must be pure JavaScript objects.
  52746. * The function assumes that base is undefined, or null or a pure object.
  52747. */
  52748. function extend (base, extension) {
  52749. if (isUndefined(base)) {
  52750. return copy(extension);
  52751. }
  52752. if (isUndefined(extension)) {
  52753. return copy(base);
  52754. }
  52755. if (isPureObject(base) && isPureObject(extension)) {
  52756. return utils.extendDeep(base, extension);
  52757. }
  52758. return copy(extension);
  52759. }
  52760. function isUndefined (value) {
  52761. return typeof value === 'undefined';
  52762. }
  52763. function copy (value) {
  52764. if (isPureObject(value)) {
  52765. return utils.extendDeep({}, value);
  52766. }
  52767. return value;
  52768. }
  52769. function isPureObject (value) {
  52770. return value !== null && value.constructor === Object;
  52771. }
  52772. }
  52773. },
  52774. /**
  52775. * Sync to attribute to component property whenever mapped attribute changes.
  52776. * If attribute is mapped to a component property, set the component property using
  52777. * the attribute value.
  52778. */
  52779. attributeChangedCallback: {
  52780. value: function (attr, oldVal, value) {
  52781. var componentName = this.mappings[attr];
  52782. if (attr in this.deprecatedMappings) {
  52783. console.warn(this.deprecatedMappings[attr]);
  52784. }
  52785. if (!attr || !componentName) { return; }
  52786. // Set value.
  52787. setComponentProperty(this, componentName, value);
  52788. }
  52789. }
  52790. })
  52791. });
  52792. // Store.
  52793. primitives[name] = primitive;
  52794. return primitive;
  52795. };
  52796. /**
  52797. * Add component mappings using schema.
  52798. */
  52799. function addComponentMapping (componentName, mappings) {
  52800. var schema = components[componentName].schema;
  52801. Object.keys(schema).map(function (prop) {
  52802. // Hyphenate where there is camelCase.
  52803. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  52804. // If there is a mapping collision, prefix with component name and hyphen.
  52805. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  52806. mappings[attrName] = componentName + '.' + prop;
  52807. });
  52808. }
  52809. /**
  52810. * Helper to define a primitive, building mappings using a component schema.
  52811. */
  52812. function definePrimitive (tagName, defaultComponents, mappings) {
  52813. // If no initial mappings provided, start from empty map.
  52814. mappings = mappings || {};
  52815. // From the default components, add mapping automagically.
  52816. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  52817. addComponentMapping(componentName, mappings);
  52818. });
  52819. // Register the primitive.
  52820. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  52821. defaultComponents: defaultComponents,
  52822. mappings: mappings
  52823. }));
  52824. }
  52825. module.exports.definePrimitive = definePrimitive;
  52826. },{"../../core/a-entity":122,"../../core/a-register-element":125,"../../core/component":126,"../../utils/":196}],142:[function(_dereq_,module,exports){
  52827. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52828. registerPrimitive('a-camera', {
  52829. defaultComponents: {
  52830. 'camera': {},
  52831. 'look-controls': {},
  52832. 'wasd-controls': {}
  52833. },
  52834. mappings: {
  52835. active: 'camera.active',
  52836. far: 'camera.far',
  52837. fov: 'camera.fov',
  52838. 'look-controls-enabled': 'look-controls.enabled',
  52839. near: 'camera.near',
  52840. 'wasd-controls-enabled': 'wasd-controls.enabled',
  52841. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  52842. zoom: 'camera.zoom'
  52843. }
  52844. });
  52845. },{"../primitives":141}],143:[function(_dereq_,module,exports){
  52846. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52847. registerPrimitive('a-collada-model', {
  52848. mappings: {
  52849. src: 'collada-model'
  52850. }
  52851. });
  52852. },{"../primitives":141}],144:[function(_dereq_,module,exports){
  52853. var getMeshMixin = _dereq_('../getMeshMixin');
  52854. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52855. var utils = _dereq_('../../../utils/');
  52856. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  52857. defaultComponents: {
  52858. cursor: {},
  52859. geometry: {
  52860. primitive: 'ring',
  52861. radiusOuter: 0.016,
  52862. radiusInner: 0.01,
  52863. segmentsTheta: 32
  52864. },
  52865. material: {
  52866. color: '#000',
  52867. shader: 'flat',
  52868. opacity: 0.8
  52869. },
  52870. position: {
  52871. x: 0,
  52872. y: 0,
  52873. z: -1
  52874. }
  52875. },
  52876. mappings: {
  52877. far: 'raycaster.far',
  52878. fuse: 'cursor.fuse',
  52879. 'fuse-timeout': 'cursor.fuseTimeout',
  52880. interval: 'raycaster.interval',
  52881. objects: 'raycaster.objects'
  52882. }
  52883. }));
  52884. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],145:[function(_dereq_,module,exports){
  52885. var getMeshMixin = _dereq_('../getMeshMixin');
  52886. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52887. var utils = _dereq_('../../../utils/');
  52888. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  52889. defaultComponents: {
  52890. geometry: {
  52891. height: 1,
  52892. primitive: 'cylinder',
  52893. radius: 2,
  52894. segmentsRadial: 48,
  52895. thetaLength: 270,
  52896. openEnded: true,
  52897. thetaStart: 0
  52898. },
  52899. material: {
  52900. color: '#FFF',
  52901. shader: 'flat',
  52902. side: 'double',
  52903. transparent: true,
  52904. repeat: '-1 1'
  52905. }
  52906. },
  52907. mappings: {
  52908. height: 'geometry.height',
  52909. 'open-ended': 'geometry.openEnded',
  52910. radius: 'geometry.radius',
  52911. segments: 'geometry.segmentsRadial',
  52912. start: 'geometry.thetaStart',
  52913. 'theta-length': 'geometry.thetaLength',
  52914. 'theta-start': 'geometry.thetaStart',
  52915. 'width': 'geometry.thetaLength'
  52916. }
  52917. }));
  52918. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],146:[function(_dereq_,module,exports){
  52919. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52920. registerPrimitive('a-gltf-model', {
  52921. mappings: {
  52922. src: 'gltf-model'
  52923. }
  52924. });
  52925. },{"../primitives":141}],147:[function(_dereq_,module,exports){
  52926. var getMeshMixin = _dereq_('../getMeshMixin');
  52927. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52928. var utils = _dereq_('../../../utils/');
  52929. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  52930. defaultComponents: {
  52931. geometry: {
  52932. primitive: 'plane'
  52933. },
  52934. material: {
  52935. color: '#FFF',
  52936. shader: 'flat',
  52937. side: 'double',
  52938. transparent: true
  52939. }
  52940. },
  52941. mappings: {
  52942. height: 'geometry.height',
  52943. width: 'geometry.width'
  52944. }
  52945. }));
  52946. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],148:[function(_dereq_,module,exports){
  52947. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52948. registerPrimitive('a-light', {
  52949. defaultComponents: {
  52950. light: {}
  52951. },
  52952. mappings: {
  52953. angle: 'light.angle',
  52954. color: 'light.color',
  52955. 'ground-color': 'light.groundColor',
  52956. decay: 'light.decay',
  52957. distance: 'light.distance',
  52958. intensity: 'light.intensity',
  52959. penumbra: 'light.penumbra',
  52960. type: 'light.type',
  52961. target: 'light.target'
  52962. }
  52963. });
  52964. },{"../primitives":141}],149:[function(_dereq_,module,exports){
  52965. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52966. registerPrimitive('a-link', {
  52967. defaultComponents: {},
  52968. mappings: {
  52969. href: 'link.href',
  52970. image: 'link.image',
  52971. title: 'link.title'
  52972. }
  52973. });
  52974. },{"../primitives":141}],150:[function(_dereq_,module,exports){
  52975. var meshMixin = _dereq_('../getMeshMixin')();
  52976. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52977. var utils = _dereq_('../../../utils/');
  52978. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  52979. defaultComponents: {
  52980. 'obj-model': {}
  52981. },
  52982. mappings: {
  52983. src: 'obj-model.obj',
  52984. mtl: 'obj-model.mtl'
  52985. }
  52986. }));
  52987. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],151:[function(_dereq_,module,exports){
  52988. var getMeshMixin = _dereq_('../getMeshMixin');
  52989. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  52990. var utils = _dereq_('../../../utils/');
  52991. var meshPrimitives = _dereq_('./meshPrimitives');
  52992. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  52993. defaultComponents: {
  52994. geometry: {
  52995. primitive: 'sphere',
  52996. radius: 5000,
  52997. segmentsWidth: 64,
  52998. segmentsHeight: 32
  52999. },
  53000. material: {
  53001. color: '#FFF',
  53002. shader: 'flat',
  53003. npot: true
  53004. },
  53005. scale: '-1 1 1'
  53006. },
  53007. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  53008. }));
  53009. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141,"./meshPrimitives":156}],152:[function(_dereq_,module,exports){
  53010. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53011. registerPrimitive('a-sound', {
  53012. defaultComponents: {
  53013. sound: {}
  53014. },
  53015. mappings: {
  53016. src: 'sound.src',
  53017. on: 'sound.on',
  53018. autoplay: 'sound.autoplay',
  53019. loop: 'sound.loop',
  53020. volume: 'sound.volume'
  53021. }
  53022. });
  53023. },{"../primitives":141}],153:[function(_dereq_,module,exports){
  53024. // <a-text> using `definePrimitive` helper.
  53025. var definePrimitive = _dereq_('../primitives').definePrimitive;
  53026. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  53027. },{"../primitives":141}],154:[function(_dereq_,module,exports){
  53028. var getMeshMixin = _dereq_('../getMeshMixin');
  53029. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53030. var utils = _dereq_('../../../utils/');
  53031. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  53032. defaultComponents: {
  53033. geometry: {
  53034. primitive: 'plane'
  53035. },
  53036. material: {
  53037. color: '#FFF',
  53038. shader: 'flat',
  53039. side: 'double',
  53040. transparent: true
  53041. }
  53042. },
  53043. mappings: {
  53044. height: 'geometry.height',
  53045. width: 'geometry.width'
  53046. }
  53047. }));
  53048. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],155:[function(_dereq_,module,exports){
  53049. var getMeshMixin = _dereq_('../getMeshMixin');
  53050. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53051. var utils = _dereq_('../../../utils/');
  53052. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  53053. defaultComponents: {
  53054. geometry: {
  53055. primitive: 'sphere',
  53056. radius: 5000,
  53057. segmentsWidth: 64,
  53058. segmentsHeight: 32
  53059. },
  53060. material: {
  53061. color: '#FFF',
  53062. shader: 'flat',
  53063. npot: true
  53064. },
  53065. scale: '-1 1 1'
  53066. },
  53067. mappings: {
  53068. radius: 'geometry.radius',
  53069. 'segments-height': 'geometry.segmentsHeight',
  53070. 'segments-width': 'geometry.segmentsWidth'
  53071. }
  53072. }));
  53073. },{"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],156:[function(_dereq_,module,exports){
  53074. /**
  53075. * Automated mesh primitive registration.
  53076. */
  53077. var getMeshMixin = _dereq_('../getMeshMixin');
  53078. var geometries = _dereq_('../../../core/geometry').geometries;
  53079. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  53080. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  53081. var utils = _dereq_('../../../utils/');
  53082. // For testing.
  53083. var meshPrimitives = module.exports = {};
  53084. // Generate primitive for each geometry type.
  53085. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  53086. var geometry = geometries[geometryName];
  53087. var geometryHyphened = unCamelCase(geometryName);
  53088. // Generate mappings.
  53089. var mappings = {};
  53090. Object.keys(geometry.schema).forEach(function createMapping (property) {
  53091. mappings[unCamelCase(property)] = 'geometry.' + property;
  53092. });
  53093. // Register.
  53094. var tagName = 'a-' + geometryHyphened;
  53095. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  53096. defaultComponents: {geometry: {primitive: geometryName}},
  53097. mappings: mappings
  53098. }));
  53099. meshPrimitives[tagName] = primitive;
  53100. });
  53101. /**
  53102. * camelCase to hyphened-string.
  53103. */
  53104. function unCamelCase (str) {
  53105. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  53106. }
  53107. },{"../../../core/geometry":127,"../../../utils/":196,"../getMeshMixin":139,"../primitives":141}],157:[function(_dereq_,module,exports){
  53108. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53109. var THREE = _dereq_('../lib/three');
  53110. registerGeometry('box', {
  53111. schema: {
  53112. depth: {default: 1, min: 0},
  53113. height: {default: 1, min: 0},
  53114. width: {default: 1, min: 0},
  53115. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53116. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  53117. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  53118. },
  53119. init: function (data) {
  53120. this.geometry = new THREE.BoxGeometry(
  53121. data.width, data.height, data.depth,
  53122. data.segmentsWidth, data.segmentsHeight, data.segmentsDepth);
  53123. }
  53124. });
  53125. },{"../core/geometry":127,"../lib/three":174}],158:[function(_dereq_,module,exports){
  53126. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53127. var THREE = _dereq_('../lib/three');
  53128. var degToRad = THREE.Math.degToRad;
  53129. registerGeometry('circle', {
  53130. schema: {
  53131. radius: {default: 1, min: 0},
  53132. segments: {default: 32, min: 3, type: 'int'},
  53133. thetaLength: {default: 360, min: 0},
  53134. thetaStart: {default: 0}
  53135. },
  53136. init: function (data) {
  53137. this.geometry = new THREE.CircleGeometry(
  53138. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53139. }
  53140. });
  53141. },{"../core/geometry":127,"../lib/three":174}],159:[function(_dereq_,module,exports){
  53142. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53143. var THREE = _dereq_('../lib/three');
  53144. var degToRad = THREE.Math.degToRad;
  53145. registerGeometry('cone', {
  53146. schema: {
  53147. height: {default: 1, min: 0},
  53148. openEnded: {default: false},
  53149. radiusBottom: {default: 1, min: 0},
  53150. radiusTop: {default: 0.01, min: 0},
  53151. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53152. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53153. thetaLength: {default: 360, min: 0},
  53154. thetaStart: {default: 0}
  53155. },
  53156. init: function (data) {
  53157. this.geometry = new THREE.CylinderGeometry(
  53158. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  53159. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  53160. degToRad(data.thetaLength));
  53161. }
  53162. });
  53163. },{"../core/geometry":127,"../lib/three":174}],160:[function(_dereq_,module,exports){
  53164. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53165. var THREE = _dereq_('../lib/three');
  53166. var degToRad = THREE.Math.degToRad;
  53167. registerGeometry('cylinder', {
  53168. schema: {
  53169. height: {default: 1, min: 0},
  53170. openEnded: {default: false},
  53171. radius: {default: 1, min: 0},
  53172. segmentsHeight: {default: 18, min: 1, type: 'int'},
  53173. segmentsRadial: {default: 36, min: 3, type: 'int'},
  53174. thetaLength: {default: 360, min: 0},
  53175. thetaStart: {default: 0}
  53176. },
  53177. init: function (data) {
  53178. this.geometry = new THREE.CylinderGeometry(
  53179. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  53180. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  53181. }
  53182. });
  53183. },{"../core/geometry":127,"../lib/three":174}],161:[function(_dereq_,module,exports){
  53184. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53185. var THREE = _dereq_('../lib/three');
  53186. registerGeometry('dodecahedron', {
  53187. schema: {
  53188. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53189. radius: {default: 1, min: 0}
  53190. },
  53191. init: function (data) {
  53192. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  53193. }
  53194. });
  53195. },{"../core/geometry":127,"../lib/three":174}],162:[function(_dereq_,module,exports){
  53196. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53197. var THREE = _dereq_('../lib/three');
  53198. registerGeometry('icosahedron', {
  53199. schema: {
  53200. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53201. radius: {default: 1, min: 0}
  53202. },
  53203. init: function (data) {
  53204. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  53205. }
  53206. });
  53207. },{"../core/geometry":127,"../lib/three":174}],163:[function(_dereq_,module,exports){
  53208. _dereq_('./box.js');
  53209. _dereq_('./circle.js');
  53210. _dereq_('./cone.js');
  53211. _dereq_('./cylinder.js');
  53212. _dereq_('./dodecahedron.js');
  53213. _dereq_('./icosahedron.js');
  53214. _dereq_('./octahedron.js');
  53215. _dereq_('./plane.js');
  53216. _dereq_('./ring.js');
  53217. _dereq_('./sphere.js');
  53218. _dereq_('./tetrahedron.js');
  53219. _dereq_('./torus.js');
  53220. _dereq_('./torusKnot.js');
  53221. _dereq_('./triangle.js');
  53222. },{"./box.js":157,"./circle.js":158,"./cone.js":159,"./cylinder.js":160,"./dodecahedron.js":161,"./icosahedron.js":162,"./octahedron.js":164,"./plane.js":165,"./ring.js":166,"./sphere.js":167,"./tetrahedron.js":168,"./torus.js":169,"./torusKnot.js":170,"./triangle.js":171}],164:[function(_dereq_,module,exports){
  53223. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53224. var THREE = _dereq_('../lib/three');
  53225. registerGeometry('octahedron', {
  53226. schema: {
  53227. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53228. radius: {default: 1, min: 0}
  53229. },
  53230. init: function (data) {
  53231. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  53232. }
  53233. });
  53234. },{"../core/geometry":127,"../lib/three":174}],165:[function(_dereq_,module,exports){
  53235. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53236. var THREE = _dereq_('../lib/three');
  53237. registerGeometry('plane', {
  53238. schema: {
  53239. height: {default: 1, min: 0},
  53240. width: {default: 1, min: 0},
  53241. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  53242. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  53243. },
  53244. init: function (data) {
  53245. this.geometry = new THREE.PlaneGeometry(data.width, data.height, data.segmentsWidth, data.segmentsHeight);
  53246. }
  53247. });
  53248. },{"../core/geometry":127,"../lib/three":174}],166:[function(_dereq_,module,exports){
  53249. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53250. var THREE = _dereq_('../lib/three');
  53251. var degToRad = THREE.Math.degToRad;
  53252. registerGeometry('ring', {
  53253. schema: {
  53254. radiusInner: {default: 0.8, min: 0},
  53255. radiusOuter: {default: 1.2, min: 0},
  53256. segmentsPhi: {default: 10, min: 1, type: 'int'},
  53257. segmentsTheta: {default: 32, min: 3, type: 'int'},
  53258. thetaLength: {default: 360, min: 0},
  53259. thetaStart: {default: 0}
  53260. },
  53261. init: function (data) {
  53262. this.geometry = new THREE.RingGeometry(
  53263. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  53264. degToRad(data.thetaStart), degToRad(data.thetaLength));
  53265. }
  53266. });
  53267. },{"../core/geometry":127,"../lib/three":174}],167:[function(_dereq_,module,exports){
  53268. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53269. var THREE = _dereq_('../lib/three');
  53270. var degToRad = THREE.Math.degToRad;
  53271. registerGeometry('sphere', {
  53272. schema: {
  53273. radius: {default: 1, min: 0},
  53274. phiLength: {default: 360},
  53275. phiStart: {default: 0, min: 0},
  53276. thetaLength: {default: 180, min: 0},
  53277. thetaStart: {default: 0},
  53278. segmentsHeight: {default: 18, min: 2, type: 'int'},
  53279. segmentsWidth: {default: 36, min: 3, type: 'int'}
  53280. },
  53281. init: function (data) {
  53282. this.geometry = new THREE.SphereGeometry(
  53283. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  53284. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  53285. }
  53286. });
  53287. },{"../core/geometry":127,"../lib/three":174}],168:[function(_dereq_,module,exports){
  53288. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53289. var THREE = _dereq_('../lib/three');
  53290. registerGeometry('tetrahedron', {
  53291. schema: {
  53292. detail: {default: 0, min: 0, max: 5, type: 'int'},
  53293. radius: {default: 1, min: 0}
  53294. },
  53295. init: function (data) {
  53296. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  53297. }
  53298. });
  53299. },{"../core/geometry":127,"../lib/three":174}],169:[function(_dereq_,module,exports){
  53300. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53301. var THREE = _dereq_('../lib/three');
  53302. var degToRad = THREE.Math.degToRad;
  53303. registerGeometry('torus', {
  53304. schema: {
  53305. arc: {default: 360},
  53306. radius: {default: 1, min: 0},
  53307. radiusTubular: {default: 0.2, min: 0},
  53308. segmentsRadial: {default: 36, min: 2, type: 'int'},
  53309. segmentsTubular: {default: 32, min: 3, type: 'int'}
  53310. },
  53311. init: function (data) {
  53312. this.geometry = new THREE.TorusGeometry(
  53313. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  53314. degToRad(data.arc));
  53315. }
  53316. });
  53317. },{"../core/geometry":127,"../lib/three":174}],170:[function(_dereq_,module,exports){
  53318. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53319. var THREE = _dereq_('../lib/three');
  53320. registerGeometry('torusKnot', {
  53321. schema: {
  53322. p: {default: 2, min: 1},
  53323. q: {default: 3, min: 1},
  53324. radius: {default: 1, min: 0},
  53325. radiusTubular: {default: 0.2, min: 0},
  53326. segmentsRadial: {default: 8, min: 3, type: 'int'},
  53327. segmentsTubular: {default: 100, min: 3, type: 'int'}
  53328. },
  53329. init: function (data) {
  53330. this.geometry = new THREE.TorusKnotGeometry(
  53331. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  53332. data.p, data.q);
  53333. }
  53334. });
  53335. },{"../core/geometry":127,"../lib/three":174}],171:[function(_dereq_,module,exports){
  53336. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  53337. var THREE = _dereq_('../lib/three');
  53338. var quaternion = new THREE.Quaternion();
  53339. var rotateVector = new THREE.Vector3(0, 0, 1);
  53340. var uvMinVector = new THREE.Vector2();
  53341. var uvMaxVector = new THREE.Vector2();
  53342. var uvScaleVector = new THREE.Vector2();
  53343. registerGeometry('triangle', {
  53344. schema: {
  53345. vertexA: {type: 'vec3', default: {x: 0, y: 0.5, z: 0}},
  53346. vertexB: {type: 'vec3', default: {x: -0.5, y: -0.5, z: 0}},
  53347. vertexC: {type: 'vec3', default: {x: 0.5, y: -0.5, z: 0}}
  53348. },
  53349. init: function (data) {
  53350. var geometry;
  53351. var normal;
  53352. var triangle;
  53353. var uvA;
  53354. var uvB;
  53355. var uvC;
  53356. triangle = new THREE.Triangle();
  53357. triangle.a.set(data.vertexA.x, data.vertexA.y, data.vertexA.z);
  53358. triangle.b.set(data.vertexB.x, data.vertexB.y, data.vertexB.z);
  53359. triangle.c.set(data.vertexC.x, data.vertexC.y, data.vertexC.z);
  53360. normal = triangle.normal();
  53361. // Rotate the 3D triangle to be parallel to XY plane.
  53362. quaternion.setFromUnitVectors(normal, rotateVector);
  53363. uvA = triangle.a.clone().applyQuaternion(quaternion);
  53364. uvB = triangle.b.clone().applyQuaternion(quaternion);
  53365. uvC = triangle.c.clone().applyQuaternion(quaternion);
  53366. // Compute UVs.
  53367. // Normalize x/y values of UV so they are within 0 to 1.
  53368. uvMinVector.set(Math.min(uvA.x, uvB.x, uvC.x), Math.min(uvA.y, uvB.y, uvC.y));
  53369. uvMaxVector.set(Math.max(uvA.x, uvB.x, uvC.x), Math.max(uvA.y, uvB.y, uvC.y));
  53370. uvScaleVector.set(0, 0).subVectors(uvMaxVector, uvMinVector);
  53371. uvA = new THREE.Vector2().subVectors(uvA, uvMinVector).divide(uvScaleVector);
  53372. uvB = new THREE.Vector2().subVectors(uvB, uvMinVector).divide(uvScaleVector);
  53373. uvC = new THREE.Vector2().subVectors(uvC, uvMinVector).divide(uvScaleVector);
  53374. geometry = this.geometry = new THREE.Geometry();
  53375. geometry.vertices.push(triangle.a);
  53376. geometry.vertices.push(triangle.b);
  53377. geometry.vertices.push(triangle.c);
  53378. geometry.faces.push(new THREE.Face3(0, 1, 2, normal));
  53379. geometry.faceVertexUvs[0] = [[uvA, uvB, uvC]];
  53380. }
  53381. });
  53382. },{"../core/geometry":127,"../lib/three":174}],172:[function(_dereq_,module,exports){
  53383. // Check before the polyfill runs.
  53384. window.hasNativeWebVRImplementation = !!window.navigator.getVRDisplays || !!window.navigator.getVRDevices;
  53385. window.WebVRConfig = window.WebVRConfig || {
  53386. BUFFER_SCALE: 1,
  53387. CARDBOARD_UI_DISABLED: true,
  53388. ROTATE_INSTRUCTIONS_DISABLED: true,
  53389. TOUCH_PANNER_DISABLED: true,
  53390. MOUSE_KEYBOARD_CONTROLS_DISABLED: true
  53391. };
  53392. // WebVR polyfill
  53393. _dereq_('webvr-polyfill');
  53394. var utils = _dereq_('./utils/');
  53395. var debug = utils.debug;
  53396. var error = debug('A-Frame:error');
  53397. var warn = debug('A-Frame:warn');
  53398. if (window.document.currentScript && window.document.currentScript.parentNode !==
  53399. window.document.head && !window.debug) {
  53400. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  53401. 'ensure everything for A-Frame is properly registered before they are used from ' +
  53402. 'HTML.');
  53403. }
  53404. // Error if not using a server.
  53405. if (window.location.protocol === 'file:') {
  53406. error(
  53407. 'This HTML file is currently being served via the file:// protocol. ' +
  53408. 'Assets, textures, and models WILL NOT WORK due to cross-origin policy! ' +
  53409. 'Please use a local or hosted server: ' +
  53410. 'https://aframe.io/docs/0.5.0/introduction/getting-started.html#using-a-local-server.');
  53411. }
  53412. // Polyfill `Promise`.
  53413. window.Promise = window.Promise || _dereq_('promise-polyfill');
  53414. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  53415. // Only for iOS on versions older than 10.
  53416. if (utils.device.isIOSOlderThan10(window.navigator.userAgent)) {
  53417. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  53418. }
  53419. _dereq_('present'); // Polyfill `performance.now()`.
  53420. // CSS.
  53421. if (utils.device.isBrowserEnvironment) {
  53422. _dereq_('./style/aframe.css');
  53423. _dereq_('./style/rStats.css');
  53424. }
  53425. // Required before `AEntity` so that all components are registered.
  53426. var AScene = _dereq_('./core/scene/a-scene').AScene;
  53427. var components = _dereq_('./core/component').components;
  53428. var registerComponent = _dereq_('./core/component').registerComponent;
  53429. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  53430. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  53431. var registerShader = _dereq_('./core/shader').registerShader;
  53432. var registerSystem = _dereq_('./core/system').registerSystem;
  53433. var shaders = _dereq_('./core/shader').shaders;
  53434. var systems = _dereq_('./core/system').systems;
  53435. // Exports THREE to window so three.js can be used without alteration.
  53436. var THREE = window.THREE = _dereq_('./lib/three');
  53437. var TWEEN = window.TWEEN = _dereq_('@tweenjs/tween.js');
  53438. var pkg = _dereq_('../package');
  53439. _dereq_('./components/index'); // Register standard components.
  53440. _dereq_('./geometries/index'); // Register standard geometries.
  53441. _dereq_('./shaders/index'); // Register standard shaders.
  53442. _dereq_('./systems/index'); // Register standard systems.
  53443. var ANode = _dereq_('./core/a-node');
  53444. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  53445. _dereq_('./core/a-animation');
  53446. _dereq_('./core/a-assets');
  53447. _dereq_('./core/a-cubemap');
  53448. _dereq_('./core/a-mixin');
  53449. // Extras.
  53450. _dereq_('./extras/components/');
  53451. _dereq_('./extras/primitives/');
  53452. console.log('A-Frame Version: 0.7.0 (Date 2018-01-24, Commit #2d651b7)');
  53453. console.log('three Version:', pkg.dependencies['three']);
  53454. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  53455. module.exports = window.AFRAME = {
  53456. AComponent: _dereq_('./core/component').Component,
  53457. AEntity: AEntity,
  53458. ANode: ANode,
  53459. AScene: AScene,
  53460. components: components,
  53461. geometries: _dereq_('./core/geometry').geometries,
  53462. registerComponent: registerComponent,
  53463. registerElement: _dereq_('./core/a-register-element').registerElement,
  53464. registerGeometry: registerGeometry,
  53465. registerPrimitive: registerPrimitive,
  53466. registerShader: registerShader,
  53467. registerSystem: registerSystem,
  53468. primitives: {
  53469. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  53470. primitives: _dereq_('./extras/primitives/primitives').primitives
  53471. },
  53472. scenes: _dereq_('./core/scene/scenes'),
  53473. schema: _dereq_('./core/schema'),
  53474. shaders: shaders,
  53475. systems: systems,
  53476. THREE: THREE,
  53477. TWEEN: TWEEN,
  53478. utils: utils,
  53479. version: pkg.version
  53480. };
  53481. },{"../package":76,"./components/index":85,"./core/a-animation":119,"./core/a-assets":120,"./core/a-cubemap":121,"./core/a-entity":122,"./core/a-mixin":123,"./core/a-node":124,"./core/a-register-element":125,"./core/component":126,"./core/geometry":127,"./core/scene/a-scene":129,"./core/scene/scenes":132,"./core/schema":134,"./core/shader":135,"./core/system":136,"./extras/components/":137,"./extras/primitives/":140,"./extras/primitives/getMeshMixin":139,"./extras/primitives/primitives":141,"./geometries/index":163,"./lib/three":174,"./shaders/index":176,"./style/aframe.css":181,"./style/rStats.css":182,"./systems/index":185,"./utils/":196,"@tweenjs/tween.js":1,"present":32,"promise-polyfill":34,"webvr-polyfill":61}],173:[function(_dereq_,module,exports){
  53482. window.aframeStats = function (scene) {
  53483. var _rS = null;
  53484. var _scene = scene;
  53485. var _values = {
  53486. te: {
  53487. caption: 'Entities'
  53488. },
  53489. lt: {
  53490. caption: 'Load Time'
  53491. }
  53492. };
  53493. var _groups = [ {
  53494. caption: 'A-Frame',
  53495. values: [ 'te', 'lt' ]
  53496. } ];
  53497. function _update () {
  53498. _rS('te').set(getEntityCount());
  53499. if (window.performance.getEntriesByName) {
  53500. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  53501. }
  53502. }
  53503. function getEntityCount () {
  53504. var elements = _scene.querySelectorAll('*');
  53505. Array.prototype.slice.call(elements).filter(function (el) {
  53506. return el.isEntity;
  53507. });
  53508. return elements.length;
  53509. }
  53510. function _start () {}
  53511. function _end () {}
  53512. function _attach (r) {
  53513. _rS = r;
  53514. }
  53515. return {
  53516. update: _update,
  53517. start: _start,
  53518. end: _end,
  53519. attach: _attach,
  53520. values: _values,
  53521. groups: _groups,
  53522. fractions: []
  53523. };
  53524. };
  53525. if (typeof module === 'object') {
  53526. module.exports = {
  53527. aframeStats: window.aframeStats
  53528. };
  53529. }
  53530. },{}],174:[function(_dereq_,module,exports){
  53531. (function (global){
  53532. var THREE = global.THREE = _dereq_('three');
  53533. // Allow cross-origin images to be loaded.
  53534. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  53535. // Must be on `THREE.TextureLoader`.
  53536. if (THREE.TextureLoader) {
  53537. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  53538. }
  53539. // This is for images loaded from the model loaders.
  53540. if (THREE.ImageLoader) {
  53541. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  53542. }
  53543. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  53544. if (THREE.Cache) {
  53545. THREE.Cache.enabled = true;
  53546. }
  53547. // TODO: Eventually include these only if they are needed by a component.
  53548. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  53549. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  53550. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  53551. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  53552. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  53553. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  53554. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  53555. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  53556. module.exports = THREE;
  53557. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  53558. },{"three":41,"three/examples/js/loaders/ColladaLoader":42,"three/examples/js/loaders/GLTFLoader":43,"three/examples/js/loaders/MTLLoader":44,"three/examples/js/loaders/OBJLoader":45}],175:[function(_dereq_,module,exports){
  53559. var registerShader = _dereq_('../core/shader').registerShader;
  53560. var THREE = _dereq_('../lib/three');
  53561. var utils = _dereq_('../utils/');
  53562. /**
  53563. * Flat shader using THREE.MeshBasicMaterial.
  53564. */
  53565. module.exports.Shader = registerShader('flat', {
  53566. schema: {
  53567. color: {type: 'color'},
  53568. fog: {default: true},
  53569. height: {default: 256},
  53570. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53571. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53572. src: {type: 'map'},
  53573. width: {default: 512},
  53574. wireframe: {default: false},
  53575. wireframeLinewidth: {default: 2}
  53576. },
  53577. /**
  53578. * Initializes the shader.
  53579. * Adds a reference from the scene to this entity as the camera.
  53580. */
  53581. init: function (data) {
  53582. this.textureSrc = null;
  53583. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  53584. utils.material.updateMap(this, data);
  53585. },
  53586. update: function (data) {
  53587. this.updateMaterial(data);
  53588. utils.material.updateMap(this, data);
  53589. },
  53590. /**
  53591. * Updating existing material.
  53592. *
  53593. * @param {object} data - Material component data.
  53594. */
  53595. updateMaterial: function (data) {
  53596. var material = this.material;
  53597. data = getMaterialData(data);
  53598. Object.keys(data).forEach(function (key) {
  53599. material[key] = data[key];
  53600. });
  53601. }
  53602. });
  53603. /**
  53604. * Builds and normalize material data, normalizing stuff along the way.
  53605. *
  53606. * @param {object} data - Material data.
  53607. * @returns {object} data - Processed material data.
  53608. */
  53609. function getMaterialData (data) {
  53610. return {
  53611. fog: data.fog,
  53612. color: new THREE.Color(data.color),
  53613. wireframe: data.wireframe,
  53614. wireframeLinewidth: data.wireframeLinewidth
  53615. };
  53616. }
  53617. },{"../core/shader":135,"../lib/three":174,"../utils/":196}],176:[function(_dereq_,module,exports){
  53618. _dereq_('./flat');
  53619. _dereq_('./standard');
  53620. _dereq_('./sdf');
  53621. _dereq_('./msdf');
  53622. _dereq_('./ios10hls');
  53623. },{"./flat":175,"./ios10hls":177,"./msdf":178,"./sdf":179,"./standard":180}],177:[function(_dereq_,module,exports){
  53624. var registerShader = _dereq_('../core/shader').registerShader;
  53625. /**
  53626. * Custom shader for iOS 10 HTTP Live Streaming (HLS).
  53627. * For more information on HLS, see https://datatracker.ietf.org/doc/draft-pantos-http-live-streaming/
  53628. */
  53629. module.exports.Shader = registerShader('ios10hls', {
  53630. schema: {
  53631. src: {type: 'map', is: 'uniform'},
  53632. opacity: {type: 'number', is: 'uniform', default: 1}
  53633. },
  53634. vertexShader: [
  53635. 'varying vec2 vUV;',
  53636. 'void main(void) {',
  53637. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53638. ' vUV = uv;',
  53639. '}'
  53640. ].join('\n'),
  53641. fragmentShader: [
  53642. 'uniform sampler2D src;',
  53643. 'uniform float opacity;',
  53644. 'varying vec2 vUV;',
  53645. 'void main() {',
  53646. ' vec2 offset = vec2(0, 0);',
  53647. ' vec2 repeat = vec2(1, 1);',
  53648. ' vec4 color = texture2D(src, vec2(vUV.x / repeat.x + offset.x, (1.0 - vUV.y) / repeat.y + offset.y)).bgra;',
  53649. ' gl_FragColor = vec4(color.rgb, opacity);',
  53650. '}'
  53651. ].join('\n')
  53652. });
  53653. },{"../core/shader":135}],178:[function(_dereq_,module,exports){
  53654. var registerShader = _dereq_('../core/shader').registerShader;
  53655. /**
  53656. * Multi-channel signed distance field.
  53657. * Used by text component.
  53658. */
  53659. module.exports.Shader = registerShader('msdf', {
  53660. schema: {
  53661. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53662. color: {type: 'color', is: 'uniform', default: 'white'},
  53663. map: {type: 'map', is: 'uniform'},
  53664. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53665. },
  53666. raw: true,
  53667. vertexShader: [
  53668. 'attribute vec2 uv;',
  53669. 'attribute vec3 position;',
  53670. 'uniform mat4 projectionMatrix;',
  53671. 'uniform mat4 modelViewMatrix;',
  53672. 'varying vec2 vUV;',
  53673. 'void main(void) {',
  53674. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53675. ' vUV = uv;',
  53676. '}'
  53677. ].join('\n'),
  53678. fragmentShader: [
  53679. '#ifdef GL_OES_standard_derivatives',
  53680. '#extension GL_OES_standard_derivatives: enable',
  53681. '#endif',
  53682. 'precision highp float;',
  53683. // FIXME: Experimentally determined constants.
  53684. '#define BIG_ENOUGH 0.001',
  53685. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53686. '#define ALL_SMOOTH 0.4',
  53687. '#define ALL_ROUGH 0.02',
  53688. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53689. 'uniform sampler2D map;',
  53690. 'uniform vec3 color;',
  53691. 'uniform float opacity;',
  53692. 'uniform float alphaTest;',
  53693. 'varying vec2 vUV;',
  53694. 'float median(float r, float g, float b) {',
  53695. ' return max(min(r, g), min(max(r, g), b));',
  53696. '}',
  53697. 'void main() {',
  53698. ' vec3 sample = 1.0 - texture2D(map, vUV).rgb;',
  53699. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  53700. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  53701. ' float dscale = 0.353505;',
  53702. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  53703. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53704. // When texel is too small, blend raw alpha value rather than supersampling.
  53705. // FIXME: Experimentally determined constant.
  53706. ' if (isBigEnough > BIG_ENOUGH) {',
  53707. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53708. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  53709. ' }',
  53710. // When texel is big enough, do standard alpha test.
  53711. // FIXME: Experimentally determined constant.
  53712. // Looks much better if we *don't* do this, but do we get Z fighting?
  53713. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53714. // Else, do modified alpha test.
  53715. // FIXME: Experimentally determined constant.
  53716. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53717. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  53718. '}'
  53719. ].join('\n')
  53720. });
  53721. },{"../core/shader":135}],179:[function(_dereq_,module,exports){
  53722. var registerShader = _dereq_('../core/shader').registerShader;
  53723. /**
  53724. * Signed distance field.
  53725. * Used by text component.
  53726. */
  53727. module.exports.Shader = registerShader('sdf', {
  53728. schema: {
  53729. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  53730. color: {type: 'color', is: 'uniform', default: 'white'},
  53731. map: {type: 'map', is: 'uniform'},
  53732. opacity: {type: 'number', is: 'uniform', default: 1.0}
  53733. },
  53734. raw: true,
  53735. vertexShader: [
  53736. 'attribute vec2 uv;',
  53737. 'attribute vec3 position;',
  53738. 'uniform mat4 projectionMatrix;',
  53739. 'uniform mat4 modelViewMatrix;',
  53740. 'varying vec2 vUV;',
  53741. 'void main(void) {',
  53742. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  53743. ' vUV = uv;',
  53744. '}'
  53745. ].join('\n'),
  53746. fragmentShader: [
  53747. '#ifdef GL_OES_standard_derivatives',
  53748. '#extension GL_OES_standard_derivatives: enable',
  53749. '#endif',
  53750. 'precision highp float;',
  53751. // FIXME: experimentally determined constants
  53752. '#define BIG_ENOUGH 0.001',
  53753. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  53754. '#define ALL_SMOOTH 0.4',
  53755. '#define ALL_ROUGH 0.02',
  53756. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  53757. 'uniform sampler2D map;',
  53758. 'uniform vec3 color;',
  53759. 'uniform float opacity;',
  53760. 'uniform float alphaTest;',
  53761. 'varying vec2 vUV;',
  53762. '#ifdef GL_OES_standard_derivatives',
  53763. 'float contour(float width, float value) {',
  53764. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  53765. '}',
  53766. '#else',
  53767. 'float aastep(float value, float afwidth) {',
  53768. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  53769. '}',
  53770. '#endif',
  53771. 'void main() {',
  53772. '#ifdef GL_OES_standard_derivatives',
  53773. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  53774. ' vec2 uv = vUV;',
  53775. ' vec4 texColor = texture2D(map, uv);',
  53776. ' float dist = texColor.a;',
  53777. ' float width = fwidth(dist);',
  53778. ' float alpha = contour(dist, width);',
  53779. ' float dscale = 0.353505;',
  53780. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  53781. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  53782. // when texel is too small, blend raw alpha value rather than supersampling etc.
  53783. // FIXME: experimentally determined constant
  53784. ' if (isBigEnough > BIG_ENOUGH) {',
  53785. ' float ratio = BIG_ENOUGH / isBigEnough;',
  53786. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  53787. ' }',
  53788. // otherwise do weighted supersampling
  53789. // FIXME: why this weighting?
  53790. ' else if (isBigEnough <= BIG_ENOUGH) {',
  53791. ' vec4 box = vec4 (uv - duv, uv + duv);',
  53792. ' alpha = (alpha + 0.5 * (',
  53793. ' contour(texture2D(map, box.xy).a, width)',
  53794. ' + contour(texture2D(map, box.zw).a, width)',
  53795. ' + contour(texture2D(map, box.xw).a, width)',
  53796. ' + contour(texture2D(map, box.zy).a, width)',
  53797. ' )) / 3.0;',
  53798. ' }',
  53799. // when texel is big enough, do standard alpha test
  53800. // FIXME: experimentally determined constant
  53801. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  53802. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  53803. // else do modified alpha test
  53804. // FIXME: experimentally determined constant
  53805. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  53806. '#else',
  53807. ' vec4 texColor = texture2D(map, vUV);',
  53808. ' float value = texColor.a;',
  53809. // when we don't have derivatives, use approximations
  53810. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53811. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  53812. ' float alpha = aastep(value, afwidth);',
  53813. // use gl_FragCoord.w to guess when we should blend
  53814. // FIXME: if we understood font pixel dimensions, this could probably be improved
  53815. ' 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);',
  53816. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  53817. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  53818. ' if (ratio < 1.0)',
  53819. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  53820. '#endif',
  53821. ' gl_FragColor = vec4(color, opacity * alpha);',
  53822. '}'
  53823. ].join('\n')
  53824. });
  53825. },{"../core/shader":135}],180:[function(_dereq_,module,exports){
  53826. var registerShader = _dereq_('../core/shader').registerShader;
  53827. var THREE = _dereq_('../lib/three');
  53828. var utils = _dereq_('../utils/');
  53829. var CubeLoader = new THREE.CubeTextureLoader();
  53830. var texturePromises = {};
  53831. /**
  53832. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  53833. */
  53834. module.exports.Shader = registerShader('standard', {
  53835. schema: {
  53836. ambientOcclusionMap: {type: 'map'},
  53837. ambientOcclusionMapIntensity: {default: 1},
  53838. ambientOcclusionTextureOffset: {type: 'vec2'},
  53839. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53840. color: {type: 'color'},
  53841. displacementMap: {type: 'map'},
  53842. displacementScale: {default: 1},
  53843. displacementBias: {default: 0.5},
  53844. displacementTextureOffset: {type: 'vec2'},
  53845. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53846. emissive: {type: 'color', default: '#000'},
  53847. emissiveIntensity: {default: 1},
  53848. envMap: {default: ''},
  53849. fog: {default: true},
  53850. height: {default: 256},
  53851. metalness: {default: 0.0, min: 0.0, max: 1.0},
  53852. metalnessMap: {type: 'map'},
  53853. metalnessTextureOffset: {type: 'vec2'},
  53854. metalnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53855. normalMap: {type: 'map'},
  53856. normalScale: {type: 'vec2', default: {x: 1, y: 1}},
  53857. normalTextureOffset: {type: 'vec2'},
  53858. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53859. offset: {type: 'vec2', default: {x: 0, y: 0}},
  53860. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  53861. roughness: {default: 0.5, min: 0.0, max: 1.0},
  53862. roughnessMap: {type: 'map'},
  53863. roughnessTextureOffset: {type: 'vec2'},
  53864. roughnessTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  53865. sphericalEnvMap: {type: 'map'},
  53866. src: {type: 'map'},
  53867. width: {default: 512},
  53868. wireframe: {default: false},
  53869. wireframeLinewidth: {default: 2}
  53870. },
  53871. /**
  53872. * Initializes the shader.
  53873. * Adds a reference from the scene to this entity as the camera.
  53874. */
  53875. init: function (data) {
  53876. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  53877. utils.material.updateMap(this, data);
  53878. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53879. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53880. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53881. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53882. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53883. this.updateEnvMap(data);
  53884. },
  53885. update: function (data) {
  53886. this.updateMaterial(data);
  53887. utils.material.updateMap(this, data);
  53888. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  53889. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  53890. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  53891. if (data.metalnessMap) { utils.material.updateDistortionMap('metalness', this, data); }
  53892. if (data.roughnessMap) { utils.material.updateDistortionMap('roughness', this, data); }
  53893. this.updateEnvMap(data);
  53894. },
  53895. /**
  53896. * Updating existing material.
  53897. *
  53898. * @param {object} data - Material component data.
  53899. * @returns {object} Material.
  53900. */
  53901. updateMaterial: function (data) {
  53902. var material = this.material;
  53903. data = getMaterialData(data);
  53904. Object.keys(data).forEach(function (key) {
  53905. material[key] = data[key];
  53906. });
  53907. },
  53908. /**
  53909. * Handle environment cubemap. Textures are cached in texturePromises.
  53910. */
  53911. updateEnvMap: function (data) {
  53912. var self = this;
  53913. var material = this.material;
  53914. var envMap = data.envMap;
  53915. var sphericalEnvMap = data.sphericalEnvMap;
  53916. // No envMap defined or already loading.
  53917. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  53918. material.envMap = null;
  53919. material.needsUpdate = true;
  53920. return;
  53921. }
  53922. this.isLoadingEnvMap = true;
  53923. // if a spherical env map is defined then use it.
  53924. if (sphericalEnvMap) {
  53925. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  53926. self.isLoadingEnvMap = false;
  53927. texture.mapping = THREE.SphericalReflectionMapping;
  53928. material.envMap = texture;
  53929. utils.material.handleTextureEvents(self.el, texture);
  53930. material.needsUpdate = true;
  53931. });
  53932. return;
  53933. }
  53934. // Another material is already loading this texture. Wait on promise.
  53935. if (texturePromises[envMap]) {
  53936. texturePromises[envMap].then(function (cube) {
  53937. self.isLoadingEnvMap = false;
  53938. material.envMap = cube;
  53939. utils.material.handleTextureEvents(self.el, cube);
  53940. material.needsUpdate = true;
  53941. });
  53942. return;
  53943. }
  53944. // Material is first to load this texture. Load and resolve texture.
  53945. texturePromises[envMap] = new Promise(function (resolve) {
  53946. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  53947. CubeLoader.load(urls, function (cube) {
  53948. // Texture loaded.
  53949. self.isLoadingEnvMap = false;
  53950. material.envMap = cube;
  53951. utils.material.handleTextureEvents(self.el, cube);
  53952. resolve(cube);
  53953. });
  53954. });
  53955. });
  53956. }
  53957. });
  53958. /**
  53959. * Builds and normalize material data, normalizing stuff along the way.
  53960. *
  53961. * @param {object} data - Material data.
  53962. * @returns {object} data - Processed material data.
  53963. */
  53964. function getMaterialData (data) {
  53965. var newData = {
  53966. color: new THREE.Color(data.color),
  53967. emissive: new THREE.Color(data.emissive),
  53968. emissiveIntensity: data.emissiveIntensity,
  53969. fog: data.fog,
  53970. metalness: data.metalness,
  53971. roughness: data.roughness,
  53972. wireframe: data.wireframe,
  53973. wireframeLinewidth: data.wireframeLinewidth
  53974. };
  53975. if (data.normalMap) { newData.normalScale = data.normalScale; }
  53976. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  53977. if (data.displacementMap) {
  53978. newData.displacementScale = data.displacementScale;
  53979. newData.displacementBias = data.displacementBias;
  53980. }
  53981. return newData;
  53982. }
  53983. },{"../core/shader":135,"../lib/three":174,"../utils/":196}],181:[function(_dereq_,module,exports){
  53984. var css = ".a-html{bottom:0;left:0;position:fixed;right:0;top:0;--caca: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}// Class is removed when doing <a-scene embedded>. a-scene.fullscreen .a-canvas{width:100%!important;height:100%!important;top:0!important;left:0!important;right:0!important;bottom:0!important;z-index:999999!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;
  53985. },{"browserify-css":5}],182:[function(_dereq_,module,exports){
  53986. 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;
  53987. },{"browserify-css":5}],183:[function(_dereq_,module,exports){
  53988. var bind = _dereq_('../utils/bind');
  53989. var constants = _dereq_('../constants/');
  53990. var registerSystem = _dereq_('../core/system').registerSystem;
  53991. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  53992. /**
  53993. * Camera system. Manages which camera is active among multiple cameras in scene.
  53994. *
  53995. * @member {object} activeCameraEl - Active camera entity.
  53996. */
  53997. module.exports.System = registerSystem('camera', {
  53998. init: function () {
  53999. this.activeCameraEl = null;
  54000. // Wait for all entities to fully load before checking for existence of camera.
  54001. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  54002. // will do so asynchronously.
  54003. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultCamera, this));
  54004. },
  54005. /**
  54006. * Create a default camera if user has not added one during the initial scene traversal.
  54007. *
  54008. * Default camera offset height is at average eye level (~1.6m).
  54009. */
  54010. setupDefaultCamera: function () {
  54011. var sceneEl = this.sceneEl;
  54012. var defaultCameraEl;
  54013. var cameraRigEl;
  54014. // Camera already defined or the one defined it is an spectator one.
  54015. if (sceneEl.camera && !sceneEl.camera.el.getAttribute('camera').spectator) {
  54016. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  54017. return;
  54018. }
  54019. // Set up camera rig.
  54020. cameraRigEl = document.createElement('a-entity');
  54021. cameraRigEl.setAttribute('position', {
  54022. x: 0,
  54023. y: constants.DEFAULT_CAMERA_HEIGHT,
  54024. z: 0
  54025. });
  54026. // Set up default camera.
  54027. defaultCameraEl = document.createElement('a-entity');
  54028. defaultCameraEl.setAttribute('camera', {active: true});
  54029. defaultCameraEl.setAttribute('wasd-controls', '');
  54030. defaultCameraEl.setAttribute('look-controls', '');
  54031. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  54032. cameraRigEl.setAttribute(DEFAULT_CAMERA_ATTR, '');
  54033. cameraRigEl.appendChild(defaultCameraEl);
  54034. sceneEl.appendChild(cameraRigEl);
  54035. sceneEl.addEventListener('enter-vr', this.removeDefaultOffset);
  54036. sceneEl.addEventListener('exit-vr', this.addDefaultOffset);
  54037. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  54038. },
  54039. /**
  54040. * Set a different active camera.
  54041. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  54042. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  54043. * the new camera.
  54044. */
  54045. disableActiveCamera: function () {
  54046. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  54047. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  54048. newActiveCameraEl.setAttribute('camera', 'active', true);
  54049. },
  54050. /**
  54051. * Set active camera to be used by renderer.
  54052. * Removes the default camera (if present).
  54053. * Disables all other cameras in the scene.
  54054. *
  54055. * @param {Element} newCameraEl - Entity with camera component.
  54056. */
  54057. setActiveCamera: function (newCameraEl) {
  54058. var cameraEl;
  54059. var cameraEls;
  54060. var i;
  54061. var newCamera;
  54062. var previousCamera = this.activeCameraEl;
  54063. var sceneEl = this.sceneEl;
  54064. // Same camera.
  54065. newCamera = newCameraEl.getObject3D('camera');
  54066. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  54067. // Grab the default camera.
  54068. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54069. var defaultCameraEl = defaultCameraWrapper &&
  54070. defaultCameraWrapper.querySelector('[camera]');
  54071. // Remove default camera if new camera is not the default camera.
  54072. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  54073. // Make new camera active.
  54074. this.activeCameraEl = newCameraEl;
  54075. this.activeCameraEl.play();
  54076. sceneEl.camera = newCamera;
  54077. // Disable current camera
  54078. if (previousCamera) {
  54079. previousCamera.setAttribute('camera', 'active', false);
  54080. }
  54081. // Disable other cameras in the scene
  54082. cameraEls = sceneEl.querySelectorAll('[camera]');
  54083. for (i = 0; i < cameraEls.length; i++) {
  54084. cameraEl = cameraEls[i];
  54085. if (!cameraEl.isEntity || newCameraEl === cameraEl) { continue; }
  54086. cameraEl.setAttribute('camera', 'active', false);
  54087. cameraEl.pause();
  54088. }
  54089. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  54090. },
  54091. /**
  54092. * Set spectator camera to render the scene on a 2D display.
  54093. *
  54094. * @param {Element} newCameraEl - Entity with camera component.
  54095. */
  54096. setSpectatorCamera: function (newCameraEl) {
  54097. var newCamera;
  54098. var previousCamera = this.spectatorCameraEl;
  54099. var sceneEl = this.sceneEl;
  54100. var spectatorCameraEl;
  54101. // Same camera.
  54102. newCamera = newCameraEl.getObject3D('camera');
  54103. if (!newCamera || newCameraEl === this.spectatorCameraEl) { return; }
  54104. // Disable current camera
  54105. if (previousCamera) {
  54106. previousCamera.setAttribute('camera', 'spectator', false);
  54107. }
  54108. spectatorCameraEl = this.spectatorCameraEl = newCameraEl;
  54109. spectatorCameraEl.setAttribute('camera', 'active', false);
  54110. spectatorCameraEl.play();
  54111. sceneEl.emit('camera-set-spectator', {cameraEl: newCameraEl});
  54112. },
  54113. /**
  54114. * Disables current spectator camera.
  54115. */
  54116. disableSpectatorCamera: function () {
  54117. this.spectatorCameraEl = undefined;
  54118. },
  54119. tock: function () {
  54120. var spectatorCamera;
  54121. var sceneEl = this.sceneEl;
  54122. var isVREnabled = sceneEl.renderer.vr.enabled;
  54123. if (!this.spectatorCameraEl || sceneEl.isMobile) { return; }
  54124. spectatorCamera = this.spectatorCameraEl.components.camera.camera;
  54125. sceneEl.renderer.vr.enabled = false;
  54126. sceneEl.renderer.render(sceneEl.object3D, spectatorCamera);
  54127. sceneEl.renderer.vr.enabled = isVREnabled;
  54128. }
  54129. });
  54130. /**
  54131. * Remove injected default camera from scene, if present.
  54132. *
  54133. * @param {Element} sceneEl
  54134. */
  54135. function removeDefaultCamera (sceneEl) {
  54136. var defaultCamera;
  54137. var camera = sceneEl.camera;
  54138. if (!camera) { return; }
  54139. // Remove default camera if present.
  54140. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  54141. if (!defaultCamera) { return; }
  54142. sceneEl.removeChild(defaultCamera);
  54143. }
  54144. },{"../constants/":117,"../core/system":136,"../utils/bind":190}],184:[function(_dereq_,module,exports){
  54145. var geometries = _dereq_('../core/geometry').geometries;
  54146. var registerSystem = _dereq_('../core/system').registerSystem;
  54147. var THREE = _dereq_('../lib/three');
  54148. /**
  54149. * System for geometry component.
  54150. * Handle geometry caching.
  54151. *
  54152. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  54153. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  54154. * know whether to dispose on removal.
  54155. */
  54156. module.exports.System = registerSystem('geometry', {
  54157. init: function () {
  54158. this.cache = {};
  54159. this.cacheCount = {};
  54160. },
  54161. /**
  54162. * Reset cache. Mainly for testing.
  54163. */
  54164. clearCache: function () {
  54165. this.cache = {};
  54166. this.cacheCount = {};
  54167. },
  54168. /**
  54169. * Attempt to retrieve from cache.
  54170. *
  54171. * @returns {Object|null} A geometry if it exists, else null.
  54172. */
  54173. getOrCreateGeometry: function (data) {
  54174. var cache = this.cache;
  54175. var cachedGeometry;
  54176. var hash;
  54177. // Skip all caching logic.
  54178. if (data.skipCache) { return createGeometry(data); }
  54179. // Try to retrieve from cache first.
  54180. hash = this.hash(data);
  54181. cachedGeometry = cache[hash];
  54182. incrementCacheCount(this.cacheCount, hash);
  54183. if (cachedGeometry) { return cachedGeometry; }
  54184. // Create geometry.
  54185. cachedGeometry = createGeometry(data);
  54186. // Cache and return geometry.
  54187. cache[hash] = cachedGeometry;
  54188. return cachedGeometry;
  54189. },
  54190. /**
  54191. * Let system know that an entity is no longer using a geometry.
  54192. */
  54193. unuseGeometry: function (data) {
  54194. var cache = this.cache;
  54195. var cacheCount = this.cacheCount;
  54196. var geometry;
  54197. var hash;
  54198. if (data.skipCache) { return; }
  54199. hash = this.hash(data);
  54200. if (!cache[hash]) { return; }
  54201. decrementCacheCount(cacheCount, hash);
  54202. // Another entity is still using this geometry. No need to do anything.
  54203. if (cacheCount[hash] > 0) { return; }
  54204. // No more entities are using this geometry. Dispose.
  54205. geometry = cache[hash];
  54206. geometry.dispose();
  54207. delete cache[hash];
  54208. delete cacheCount[hash];
  54209. },
  54210. /**
  54211. * Use JSON.stringify to turn component data into hash.
  54212. * Should be deterministic within a single browser engine.
  54213. * If not, then look into json-stable-stringify.
  54214. */
  54215. hash: function (data) {
  54216. return JSON.stringify(data);
  54217. }
  54218. });
  54219. /**
  54220. * Create geometry using component data.
  54221. *
  54222. * @param {object} data - Component data.
  54223. * @returns {object} Geometry.
  54224. */
  54225. function createGeometry (data) {
  54226. var geometryType = data.primitive;
  54227. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  54228. var geometryInstance = new GeometryClass();
  54229. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  54230. geometryInstance.init(data);
  54231. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  54232. }
  54233. /**
  54234. * Decreate count of entity using a geometry.
  54235. */
  54236. function decrementCacheCount (cacheCount, hash) {
  54237. cacheCount[hash]--;
  54238. }
  54239. /**
  54240. * Increase count of entity using a geometry.
  54241. */
  54242. function incrementCacheCount (cacheCount, hash) {
  54243. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  54244. }
  54245. /**
  54246. * Transform geometry to BufferGeometry if `doBuffer`.
  54247. *
  54248. * @param {object} geometry
  54249. * @param {boolean} doBuffer
  54250. * @returns {object} Geometry.
  54251. */
  54252. function toBufferGeometry (geometry, doBuffer) {
  54253. var bufferGeometry;
  54254. if (!doBuffer) { return geometry; }
  54255. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  54256. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  54257. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  54258. return bufferGeometry;
  54259. }
  54260. },{"../core/geometry":127,"../core/system":136,"../lib/three":174}],185:[function(_dereq_,module,exports){
  54261. _dereq_('./camera');
  54262. _dereq_('./geometry');
  54263. _dereq_('./light');
  54264. _dereq_('./material');
  54265. _dereq_('./shadow');
  54266. _dereq_('./tracked-controls');
  54267. },{"./camera":183,"./geometry":184,"./light":186,"./material":187,"./shadow":188,"./tracked-controls":189}],186:[function(_dereq_,module,exports){
  54268. var registerSystem = _dereq_('../core/system').registerSystem;
  54269. var bind = _dereq_('../utils/bind');
  54270. var constants = _dereq_('../constants/');
  54271. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  54272. /**
  54273. * Light system.
  54274. *
  54275. * Prescribes default lighting if not specified (one ambient, one directional).
  54276. * Removes default lighting from the scene when a new light is added.
  54277. *
  54278. * @param {bool} defaultLights - Whether default lighting are defined.
  54279. * @param {bool} userDefinedLights - Whether user lighting is defined.
  54280. */
  54281. module.exports.System = registerSystem('light', {
  54282. schema: {
  54283. defaultLightsEnabled: {default: true}
  54284. },
  54285. init: function () {
  54286. this.defaultLights = false;
  54287. this.userDefinedLights = false;
  54288. // Wait for all entities to fully load before checking for existence of lights.
  54289. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  54290. // will do so asynchronously.
  54291. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  54292. },
  54293. /**
  54294. * Notify scene that light has been added and to remove the default.
  54295. *
  54296. * @param {object} el - element holding the light component.
  54297. */
  54298. registerLight: function (el) {
  54299. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  54300. // User added a light, remove default lights through DOM.
  54301. this.removeDefaultLights();
  54302. this.userDefinedLights = true;
  54303. }
  54304. },
  54305. removeDefaultLights: function () {
  54306. var defaultLights;
  54307. var sceneEl = this.sceneEl;
  54308. if (!this.defaultLights) { return; }
  54309. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  54310. for (var i = 0; i < defaultLights.length; i++) {
  54311. sceneEl.removeChild(defaultLights[i]);
  54312. }
  54313. this.defaultLights = false;
  54314. },
  54315. /**
  54316. * Prescibe default lights to the scene.
  54317. * Does so by injecting markup such that this state is not invisible.
  54318. * These lights are removed if the user adds any lights.
  54319. */
  54320. setupDefaultLights: function () {
  54321. var sceneEl = this.sceneEl;
  54322. var ambientLight;
  54323. var directionalLight;
  54324. if (this.userDefinedLights || this.defaultLights || !this.data.defaultLightsEnabled) {
  54325. return;
  54326. }
  54327. ambientLight = document.createElement('a-entity');
  54328. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  54329. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54330. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  54331. sceneEl.appendChild(ambientLight);
  54332. directionalLight = document.createElement('a-entity');
  54333. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6, castShadow: true});
  54334. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  54335. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  54336. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  54337. sceneEl.appendChild(directionalLight);
  54338. this.defaultLights = true;
  54339. }
  54340. });
  54341. },{"../constants/":117,"../core/system":136,"../utils/bind":190}],187:[function(_dereq_,module,exports){
  54342. var registerSystem = _dereq_('../core/system').registerSystem;
  54343. var THREE = _dereq_('../lib/three');
  54344. var utils = _dereq_('../utils/');
  54345. var isHLS = _dereq_('../utils/material').isHLS;
  54346. var bind = utils.bind;
  54347. var debug = utils.debug;
  54348. var error = debug('components:texture:error');
  54349. var TextureLoader = new THREE.TextureLoader();
  54350. var warn = debug('components:texture:warn');
  54351. TextureLoader.setCrossOrigin('anonymous');
  54352. /**
  54353. * System for material component.
  54354. * Handle material registration, updates (for fog), and texture caching.
  54355. *
  54356. * @member {object} materials - Registered materials.
  54357. * @member {object} textureCounts - Number of times each texture is used. Tracked
  54358. * separately from textureCache, because the cache (1) is populated in
  54359. * multiple places, and (2) may be cleared at any time.
  54360. * @member {object} textureCache - Texture cache for:
  54361. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  54362. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  54363. */
  54364. module.exports.System = registerSystem('material', {
  54365. init: function () {
  54366. this.materials = {};
  54367. this.textureCounts = {};
  54368. this.textureCache = {};
  54369. this.sceneEl.addEventListener(
  54370. 'materialtextureloaded',
  54371. bind(this.onMaterialTextureLoaded, this)
  54372. );
  54373. },
  54374. clearTextureCache: function () {
  54375. this.textureCache = {};
  54376. },
  54377. /**
  54378. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  54379. *
  54380. * @param {string, or element} src - Texture URL or element.
  54381. * @param {string} data - Relevant texture data used for caching.
  54382. * @param {function} cb - Callback to pass texture to.
  54383. */
  54384. loadTexture: function (src, data, cb) {
  54385. var self = this;
  54386. // Canvas.
  54387. if (src.tagName === 'CANVAS') {
  54388. this.loadCanvas(src, data, cb);
  54389. return;
  54390. }
  54391. // Video element.
  54392. if (src.tagName === 'VIDEO') {
  54393. if (!src.src && !src.srcObject && !src.childElementCount) {
  54394. warn('Video element was defined with neither `source` elements nor `src` / `srcObject` attributes.');
  54395. }
  54396. this.loadVideo(src, data, cb);
  54397. return;
  54398. }
  54399. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  54400. function loadImageCb (src) { self.loadImage(src, data, cb); }
  54401. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  54402. },
  54403. /**
  54404. * High-level function for loading image textures (THREE.Texture).
  54405. *
  54406. * @param {Element|string} src - Texture source.
  54407. * @param {object} data - Texture data.
  54408. * @param {function} cb - Callback to pass texture to.
  54409. */
  54410. loadImage: function (src, data, handleImageTextureLoaded) {
  54411. var hash = this.hash(data);
  54412. var textureCache = this.textureCache;
  54413. // Texture already being loaded or already loaded. Wait on promise.
  54414. if (textureCache[hash]) {
  54415. textureCache[hash].then(handleImageTextureLoaded);
  54416. return;
  54417. }
  54418. // Texture not yet being loaded. Start loading it.
  54419. textureCache[hash] = loadImageTexture(src, data);
  54420. textureCache[hash].then(handleImageTextureLoaded);
  54421. },
  54422. /**
  54423. * High-level function for loading canvas textures (THREE.Texture).
  54424. *
  54425. * @param {Element|string} src - Texture source.
  54426. * @param {object} data - Texture data.
  54427. * @param {function} cb - Callback to pass texture to.
  54428. */
  54429. loadCanvas: function (src, data, cb) {
  54430. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  54431. src.readyState = 2;
  54432. src.HAVE_CURRENT_DATA = 2;
  54433. this.loadVideo(src, data, cb);
  54434. },
  54435. /**
  54436. * Load video texture (THREE.VideoTexture).
  54437. * Which is just an image texture that RAFs + needsUpdate.
  54438. * Note that creating a video texture is synchronous unlike loading an image texture.
  54439. * Made asynchronous to be consistent with image textures.
  54440. *
  54441. * @param {Element|string} src - Texture source.
  54442. * @param {object} data - Texture data.
  54443. * @param {function} cb - Callback to pass texture to.
  54444. */
  54445. loadVideo: function (src, data, cb) {
  54446. var hash;
  54447. var texture;
  54448. var textureCache = this.textureCache;
  54449. var videoEl;
  54450. var videoTextureResult;
  54451. function handleVideoTextureLoaded (result) {
  54452. result.texture.needsUpdate = true;
  54453. cb(result.texture, result.videoEl);
  54454. }
  54455. // Video element provided.
  54456. if (typeof src !== 'string') {
  54457. // Check cache before creating texture.
  54458. videoEl = src;
  54459. hash = this.hashVideo(data, videoEl);
  54460. if (textureCache[hash]) {
  54461. textureCache[hash].then(handleVideoTextureLoaded);
  54462. return;
  54463. }
  54464. // If not in cache, fix up the attributes then start to create the texture.
  54465. fixVideoAttributes(videoEl);
  54466. }
  54467. // Only URL provided. Use video element to create texture.
  54468. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  54469. // Generated video element already cached. Use that.
  54470. hash = this.hashVideo(data, videoEl);
  54471. if (textureCache[hash]) {
  54472. textureCache[hash].then(handleVideoTextureLoaded);
  54473. return;
  54474. }
  54475. // Create new video texture.
  54476. texture = new THREE.VideoTexture(videoEl);
  54477. texture.minFilter = THREE.LinearFilter;
  54478. setTextureProperties(texture, data);
  54479. // If iOS and video is HLS, do some hacks.
  54480. if (this.sceneEl.isIOS &&
  54481. isHLS(videoEl.src || videoEl.getAttribute('src'),
  54482. videoEl.type || videoEl.getAttribute('type'))) {
  54483. // Actually BGRA. Tell shader to correct later.
  54484. texture.format = THREE.RGBAFormat;
  54485. texture.needsCorrectionBGRA = true;
  54486. // Apparently needed for HLS. Tell shader to correct later.
  54487. texture.flipY = false;
  54488. texture.needsCorrectionFlipY = true;
  54489. }
  54490. // Cache as promise to be consistent with image texture caching.
  54491. videoTextureResult = {texture: texture, videoEl: videoEl};
  54492. textureCache[hash] = Promise.resolve(videoTextureResult);
  54493. handleVideoTextureLoaded(videoTextureResult);
  54494. },
  54495. /**
  54496. * Create a hash of the material properties for texture cache key.
  54497. */
  54498. hash: function (data) {
  54499. if (data.src.tagName) {
  54500. // Since `data.src` can be an element, parse out the string if necessary for the hash.
  54501. data = utils.extendDeep({}, data);
  54502. data.src = data.src.src;
  54503. }
  54504. return JSON.stringify(data);
  54505. },
  54506. hashVideo: function (data, videoEl) {
  54507. return calculateVideoCacheHash(data, videoEl);
  54508. },
  54509. /**
  54510. * Keep track of material in case an update trigger is needed (e.g., fog).
  54511. *
  54512. * @param {object} material
  54513. */
  54514. registerMaterial: function (material) {
  54515. this.materials[material.uuid] = material;
  54516. },
  54517. /**
  54518. * Stop tracking material, and dispose of any textures not being used by
  54519. * another material component.
  54520. *
  54521. * @param {object} material
  54522. */
  54523. unregisterMaterial: function (material) {
  54524. delete this.materials[material.uuid];
  54525. // If any textures on this material are no longer in use, dispose of them.
  54526. var textureCounts = this.textureCounts;
  54527. Object.keys(material)
  54528. .filter(function (propName) {
  54529. return material[propName] && material[propName].isTexture;
  54530. })
  54531. .forEach(function (mapName) {
  54532. textureCounts[material[mapName].uuid]--;
  54533. if (textureCounts[material[mapName].uuid] <= 0) {
  54534. material[mapName].dispose();
  54535. }
  54536. });
  54537. },
  54538. /**
  54539. * Trigger update to all registered materials.
  54540. */
  54541. updateMaterials: function (material) {
  54542. var materials = this.materials;
  54543. Object.keys(materials).forEach(function (uuid) {
  54544. materials[uuid].needsUpdate = true;
  54545. });
  54546. },
  54547. /**
  54548. * Track textures used by material components, so that they can be safely
  54549. * disposed when no longer in use. Textures must be registered here, and not
  54550. * through registerMaterial(), because textures may not be attached at the
  54551. * time the material is registered.
  54552. *
  54553. * @param {Event} e
  54554. */
  54555. onMaterialTextureLoaded: function (e) {
  54556. if (!this.textureCounts[e.detail.texture.uuid]) {
  54557. this.textureCounts[e.detail.texture.uuid] = 0;
  54558. }
  54559. this.textureCounts[e.detail.texture.uuid]++;
  54560. }
  54561. });
  54562. /**
  54563. * Calculates consistent hash from a video element using its attributes.
  54564. * If the video element has an ID, use that.
  54565. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  54566. *
  54567. * @param data {object} - Texture data such as repeat.
  54568. * @param videoEl {Element} - Video element.
  54569. * @returns {string}
  54570. */
  54571. function calculateVideoCacheHash (data, videoEl) {
  54572. var i;
  54573. var id = videoEl.getAttribute('id');
  54574. var hash;
  54575. var videoAttributes;
  54576. if (id) { return id; }
  54577. // Calculate hash using sorted video attributes.
  54578. hash = '';
  54579. videoAttributes = data || {};
  54580. for (i = 0; i < videoEl.attributes.length; i++) {
  54581. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  54582. }
  54583. Object.keys(videoAttributes).sort().forEach(function (name) {
  54584. hash += name + ':' + videoAttributes[name] + ';';
  54585. });
  54586. return hash;
  54587. }
  54588. /**
  54589. * Load image texture.
  54590. *
  54591. * @private
  54592. * @param {string|object} src - An <img> element or url to an image file.
  54593. * @param {object} data - Data to set texture properties like `repeat`.
  54594. * @returns {Promise} Resolves once texture is loaded.
  54595. */
  54596. function loadImageTexture (src, data) {
  54597. return new Promise(doLoadImageTexture);
  54598. function doLoadImageTexture (resolve, reject) {
  54599. var isEl = typeof src !== 'string';
  54600. function resolveTexture (texture) {
  54601. setTextureProperties(texture, data);
  54602. texture.needsUpdate = true;
  54603. resolve(texture);
  54604. }
  54605. // Create texture from an element.
  54606. if (isEl) {
  54607. resolveTexture(new THREE.Texture(src));
  54608. return;
  54609. }
  54610. // Request and load texture from src string. THREE will create underlying element.
  54611. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  54612. TextureLoader.load(
  54613. src,
  54614. resolveTexture,
  54615. function () { /* no-op */ },
  54616. function (xhr) {
  54617. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  54618. xhr.statusText);
  54619. }
  54620. );
  54621. }
  54622. }
  54623. /**
  54624. * Set texture properties such as repeat and offset.
  54625. *
  54626. * @param {object} data - With keys like `repeat`.
  54627. */
  54628. function setTextureProperties (texture, data) {
  54629. var offset = data.offset || {x: 0, y: 0};
  54630. var repeat = data.repeat || {x: 1, y: 1};
  54631. var npot = data.npot || false;
  54632. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  54633. // and filters must not use mipmaps (i.e. Nearest or Linear).
  54634. if (npot) {
  54635. texture.wrapS = THREE.ClampToEdgeWrapping;
  54636. texture.wrapT = THREE.ClampToEdgeWrapping;
  54637. texture.magFilter = THREE.LinearFilter;
  54638. texture.minFilter = THREE.LinearFilter;
  54639. }
  54640. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  54641. if (repeat.x !== 1 || repeat.y !== 1) {
  54642. texture.wrapS = THREE.RepeatWrapping;
  54643. texture.wrapT = THREE.RepeatWrapping;
  54644. texture.repeat.set(repeat.x, repeat.y);
  54645. }
  54646. // Don't bother setting offset if it is 0/0.
  54647. if (offset.x !== 0 || offset.y !== 0) {
  54648. texture.offset.set(offset.x, offset.y);
  54649. }
  54650. }
  54651. /**
  54652. * Create video element to be used as a texture.
  54653. *
  54654. * @param {string} src - Url to a video file.
  54655. * @param {number} width - Width of the video.
  54656. * @param {number} height - Height of the video.
  54657. * @returns {Element} Video element.
  54658. */
  54659. function createVideoEl (src, width, height) {
  54660. var videoEl = document.createElement('video');
  54661. videoEl.width = width;
  54662. videoEl.height = height;
  54663. // Support inline videos for iOS webviews.
  54664. videoEl.setAttribute('playsinline', '');
  54665. videoEl.setAttribute('webkit-playsinline', '');
  54666. videoEl.autoplay = true;
  54667. videoEl.loop = true;
  54668. videoEl.crossOrigin = 'anonymous';
  54669. videoEl.addEventListener('error', function () {
  54670. warn('`$s` is not a valid video', src);
  54671. }, true);
  54672. videoEl.src = src;
  54673. return videoEl;
  54674. }
  54675. /**
  54676. * Fixes a video element's attributes to prevent developers from accidentally passing the
  54677. * wrong attribute values to commonly misused video attributes.
  54678. *
  54679. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  54680. * as booleans. Existence of those attributes will mean truthy.
  54681. *
  54682. * For example, translates <video loop="false"> to <video>.
  54683. *
  54684. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  54685. * @param {Element} videoEl - Video element.
  54686. * @returns {Element} Video element with the correct properties updated.
  54687. */
  54688. function fixVideoAttributes (videoEl) {
  54689. videoEl.autoplay = videoEl.hasAttribute('autoplay') && videoEl.getAttribute('autoplay') !== 'false';
  54690. videoEl.controls = videoEl.hasAttribute('controls') && videoEl.getAttribute('controls') !== 'false';
  54691. if (videoEl.getAttribute('loop') === 'false') {
  54692. videoEl.removeAttribute('loop');
  54693. }
  54694. if (videoEl.getAttribute('preload') === 'false') {
  54695. videoEl.preload = 'none';
  54696. }
  54697. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  54698. // To support inline videos in iOS webviews.
  54699. videoEl.setAttribute('playsinline', '');
  54700. videoEl.setAttribute('webkit-playsinline', '');
  54701. return videoEl;
  54702. }
  54703. },{"../core/system":136,"../lib/three":174,"../utils/":196,"../utils/material":197}],188:[function(_dereq_,module,exports){
  54704. var registerSystem = _dereq_('../core/system').registerSystem;
  54705. var THREE = _dereq_('../lib/three');
  54706. var SHADOW_MAP_TYPE_MAP = {
  54707. basic: THREE.BasicShadowMap,
  54708. pcf: THREE.PCFShadowMap,
  54709. pcfsoft: THREE.PCFSoftShadowMap
  54710. };
  54711. /**
  54712. * Shadow system.
  54713. *
  54714. * Enabled automatically when one or more shadow components are added to the scene, the system sets
  54715. * options on the WebGLRenderer for configuring shadow appearance.
  54716. */
  54717. module.exports.System = registerSystem('shadow', {
  54718. schema: {
  54719. autoUpdate: {default: true},
  54720. renderReverseSided: {default: true},
  54721. renderSingleSided: {default: true},
  54722. type: {default: 'pcf', oneOf: ['basic', 'pcf', 'pcfsoft']}
  54723. },
  54724. init: function () {
  54725. var sceneEl = this.sceneEl;
  54726. var data = this.data;
  54727. this.shadowMapEnabled = false;
  54728. if (!sceneEl.renderer) { return; } // For tests.
  54729. sceneEl.renderer.shadowMap.type = SHADOW_MAP_TYPE_MAP[data.type];
  54730. sceneEl.renderer.shadowMap.renderReverseSided = data.renderReverseSided;
  54731. sceneEl.renderer.shadowMap.renderSingleSided = data.renderSingleSided;
  54732. sceneEl.renderer.shadowMap.autoUpdate = data.autoUpdate;
  54733. this.setShadowMapEnabled(this.shadowMapEnabled);
  54734. },
  54735. /**
  54736. * Enables/disables the renderer shadow map.
  54737. * @param {boolean} enabled
  54738. */
  54739. setShadowMapEnabled: function (enabled) {
  54740. var renderer = this.sceneEl.renderer;
  54741. this.shadowMapEnabled = enabled;
  54742. if (renderer) {
  54743. renderer.shadowMap.enabled = enabled;
  54744. }
  54745. }
  54746. });
  54747. },{"../core/system":136,"../lib/three":174}],189:[function(_dereq_,module,exports){
  54748. var registerSystem = _dereq_('../core/system').registerSystem;
  54749. var utils = _dereq_('../utils');
  54750. /**
  54751. * Tracked controls system.
  54752. * Maintain list with available tracked controllers.
  54753. */
  54754. module.exports.System = registerSystem('tracked-controls', {
  54755. init: function () {
  54756. var self = this;
  54757. this.controllers = [];
  54758. this.updateControllerList(navigator.getGamepads && navigator.getGamepads());
  54759. this.throttledUpdateControllerList = utils.throttle(this.updateControllerList, 500, this);
  54760. if (!navigator.getVRDisplays) { return; }
  54761. this.sceneEl.addEventListener('enter-vr', function () {
  54762. navigator.getVRDisplays().then(function (displays) {
  54763. if (displays.length) { self.vrDisplay = displays[0]; }
  54764. });
  54765. });
  54766. },
  54767. tick: function () {
  54768. var gamepads;
  54769. // Call getGamepads for Chrome.
  54770. gamepads = navigator.getGamepads && navigator.getGamepads();
  54771. this.throttledUpdateControllerList(gamepads);
  54772. },
  54773. /**
  54774. * Update controller list.
  54775. */
  54776. updateControllerList: function (gamepads) {
  54777. var controllers = this.controllers;
  54778. var gamepad;
  54779. var i;
  54780. var prevCount;
  54781. if (!gamepads) { return; }
  54782. prevCount = controllers.length;
  54783. controllers.length = 0;
  54784. for (i = 0; i < gamepads.length; ++i) {
  54785. gamepad = gamepads[i];
  54786. if (gamepad && gamepad.pose) {
  54787. controllers.push(gamepad);
  54788. }
  54789. }
  54790. if (controllers.length !== prevCount) {
  54791. this.el.emit('controllersupdated', undefined, false);
  54792. }
  54793. }
  54794. });
  54795. },{"../core/system":136,"../utils":196}],190:[function(_dereq_,module,exports){
  54796. /**
  54797. * Faster version of Function.prototype.bind
  54798. * @param {Function} fn - Function to wrap.
  54799. * @param {Object} ctx - What to bind as context.
  54800. * @param {...*} arguments - Arguments to pass through.
  54801. */
  54802. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  54803. return (function (prependedArgs) {
  54804. return function bound () {
  54805. // Concat the bound function arguments with those passed to original bind
  54806. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  54807. return fn.apply(ctx, args);
  54808. };
  54809. })(Array.prototype.slice.call(arguments, 2));
  54810. };
  54811. },{}],191:[function(_dereq_,module,exports){
  54812. /* global THREE */
  54813. var debug = _dereq_('./debug');
  54814. var extend = _dereq_('object-assign');
  54815. var warn = debug('utils:coordinates:warn');
  54816. // Coordinate string regex. Handles negative, positive, and decimals.
  54817. var regex = /^\s*((-?\d*\.{0,1}\d+(e-?\d+)?)\s+){2,3}(-?\d*\.{0,1}\d+(e-?\d+)?)\s*$/;
  54818. module.exports.regex = regex;
  54819. /**
  54820. * Parses coordinates from an "x y z" string.
  54821. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  54822. *
  54823. * @param {string} val - An "x y z" string.
  54824. * @param {string} defaults - fallback value.
  54825. * @returns {object} An object with keys [x, y, z].
  54826. */
  54827. function parse (value, defaultVec) {
  54828. var coordinate;
  54829. var vec;
  54830. if (value && value instanceof Object) {
  54831. if (defaultVec) {
  54832. value.x = value.x === undefined ? defaultVec.x : value.x;
  54833. value.y = value.y === undefined ? defaultVec.y : value.y;
  54834. value.z = value.z === undefined ? defaultVec.z : value.z;
  54835. value.w = value.w === undefined ? defaultVec.w : value.w;
  54836. }
  54837. return vecParseFloat(value);
  54838. }
  54839. if (value === null || value === undefined) {
  54840. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  54841. }
  54842. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  54843. vec = {};
  54844. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  54845. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  54846. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  54847. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  54848. return vecParseFloat(vec);
  54849. }
  54850. module.exports.parse = parse;
  54851. /**
  54852. * Stringify coordinates from an object with keys [x y z].
  54853. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  54854. *
  54855. * @param {object|string} data - An object with keys [x y z].
  54856. * @returns {string} An "x y z" string.
  54857. */
  54858. function stringify (data) {
  54859. if (typeof data !== 'object') { return data; }
  54860. return [data.x, data.y, data.z, data.w].join(' ').trim();
  54861. }
  54862. module.exports.stringify = stringify;
  54863. /**
  54864. * @returns {bool}
  54865. */
  54866. function isCoordinates (value) {
  54867. return regex.test(value);
  54868. }
  54869. module.exports.isCoordinates = isCoordinates;
  54870. module.exports.isCoordinate = function (value) {
  54871. warn('`AFRAME.utils.isCoordinate` has been renamed to `AFRAME.utils.isCoordinates`');
  54872. return isCoordinates(value);
  54873. };
  54874. function vecParseFloat (vec) {
  54875. var key;
  54876. for (key in vec) {
  54877. if (vec[key] === undefined) {
  54878. delete vec[key];
  54879. continue;
  54880. }
  54881. if (vec[key].constructor === String) {
  54882. vec[key] = parseFloat(vec[key], 10);
  54883. }
  54884. }
  54885. return vec;
  54886. }
  54887. /**
  54888. * Convert {x, y, z} object to three.js Vector3.
  54889. */
  54890. module.exports.toVector3 = function (vec3) {
  54891. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  54892. };
  54893. },{"./debug":192,"object-assign":26}],192:[function(_dereq_,module,exports){
  54894. (function (process){
  54895. var debugLib = _dereq_('debug');
  54896. var extend = _dereq_('object-assign');
  54897. var settings = {
  54898. colors: {
  54899. debug: 'gray',
  54900. error: 'red',
  54901. info: 'gray',
  54902. warn: 'orange'
  54903. }
  54904. };
  54905. /**
  54906. * Monkeypatches `debug` so we can colorize error/warning messages.
  54907. *
  54908. * (See issue: https://github.com/visionmedia/debug/issues/137)
  54909. */
  54910. var debug = function (namespace) {
  54911. var d = debugLib(namespace);
  54912. d.color = getDebugNamespaceColor(namespace);
  54913. return d;
  54914. };
  54915. extend(debug, debugLib);
  54916. /**
  54917. * Returns the type of the namespace (e.g., `error`, `warn`).
  54918. *
  54919. * @param {String} namespace
  54920. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54921. * @returns {String} The type of the namespace (e.g., `warn`).
  54922. * @api private
  54923. */
  54924. function getDebugNamespaceType (namespace) {
  54925. var chunks = namespace.split(':');
  54926. return chunks[chunks.length - 1]; // Return the last one
  54927. }
  54928. /**
  54929. * Returns the color of the namespace (e.g., `orange`).
  54930. *
  54931. * @param {String} namespace
  54932. * The debug logger's namespace (e.g., `components:geometry:warn`).
  54933. * @returns {String} The color of the namespace (e.g., `orange`).
  54934. * @api private
  54935. */
  54936. function getDebugNamespaceColor (namespace) {
  54937. var type = getDebugNamespaceType(namespace);
  54938. var color = settings.colors && settings.colors[type];
  54939. return color || null;
  54940. }
  54941. /**
  54942. * Returns `localStorage` if possible.
  54943. *
  54944. * This is necessary because Safari throws when a user disables
  54945. * cookies or `localStorage` and you attempt to access it.
  54946. *
  54947. * @returns {localStorage}
  54948. * @api private
  54949. */
  54950. function storage () {
  54951. try {
  54952. return window.localStorage;
  54953. } catch (e) {
  54954. }
  54955. }
  54956. /**
  54957. * To enable console logging, type this in the Console of your Dev Tools:
  54958. *
  54959. * localStorage.logs = 1
  54960. *
  54961. * To disable console logging:
  54962. *
  54963. * localStorage.logs = 0
  54964. *
  54965. */
  54966. var ls = storage();
  54967. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  54968. debug.enable('*');
  54969. } else {
  54970. debug.enable('*:error,*:info,*:warn');
  54971. }
  54972. if (process.browser) { window.logs = debug; }
  54973. module.exports = debug;
  54974. }).call(this,_dereq_('_process'))
  54975. },{"_process":33,"debug":8,"object-assign":26}],193:[function(_dereq_,module,exports){
  54976. (function (process){
  54977. var vrDisplay;
  54978. var polyfilledVRDisplay;
  54979. var POLYFILL_VRDISPLAY_ID = 'Cardboard VRDisplay (webvr-polyfill)';
  54980. if (navigator.getVRDisplays) {
  54981. navigator.getVRDisplays().then(function (displays) {
  54982. vrDisplay = displays.length && displays[0];
  54983. polyfilledVRDisplay = vrDisplay.displayName === POLYFILL_VRDISPLAY_ID;
  54984. });
  54985. }
  54986. function getVRDisplay () { return vrDisplay; }
  54987. module.exports.getVRDisplay = getVRDisplay;
  54988. /**
  54989. * Determine if a headset is connected by checking if a vrDisplay is available.
  54990. */
  54991. function checkHeadsetConnected () { return !!getVRDisplay(); }
  54992. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  54993. /**
  54994. * Check for positional tracking.
  54995. */
  54996. function checkHasPositionalTracking () {
  54997. var vrDisplay = getVRDisplay();
  54998. if (isMobile() || isGearVR()) { return false; }
  54999. return vrDisplay && vrDisplay.capabilities.hasPosition;
  55000. }
  55001. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  55002. /**
  55003. * Checks if browser is mobile.
  55004. * @return {Boolean} True if mobile browser detected.
  55005. */
  55006. var isMobile = (function () {
  55007. var _isMobile = false;
  55008. (function (a) {
  55009. // eslint-disable-next-line no-useless-escape
  55010. 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))) {
  55011. _isMobile = true;
  55012. }
  55013. if (isIOS() || isTablet() || isR7()) {
  55014. _isMobile = true;
  55015. }
  55016. })(window.navigator.userAgent || window.navigator.vendor || window.opera);
  55017. return function () { return _isMobile; };
  55018. })();
  55019. module.exports.isMobile = isMobile;
  55020. /**
  55021. * Detect tablet devices.
  55022. * @param {string} mockUserAgent - Allow passing a mock user agent for testing.
  55023. */
  55024. function isTablet (mockUserAgent) {
  55025. var userAgent = mockUserAgent || window.navigator.userAgent;
  55026. return /ipad|Nexus (7|9)|xoom|sch-i800|playbook|tablet|kindle/i.test(userAgent);
  55027. }
  55028. module.exports.isTablet = isTablet;
  55029. function isIOS () {
  55030. return /iPad|iPhone|iPod/.test(window.navigator.platform);
  55031. }
  55032. module.exports.isIOS = isIOS;
  55033. function isGearVR () {
  55034. return /SamsungBrowser.+Mobile VR/i.test(window.navigator.userAgent);
  55035. }
  55036. module.exports.isGearVR = isGearVR;
  55037. function isR7 () {
  55038. return /R7 Build/.test(window.navigator.userAgent);
  55039. }
  55040. module.exports.isR7 = isR7;
  55041. /**
  55042. * Checks mobile device orientation.
  55043. * @return {Boolean} True if landscape orientation.
  55044. */
  55045. module.exports.isLandscape = function () {
  55046. var orientation = window.orientation;
  55047. if (isR7()) { orientation += 90; }
  55048. return orientation === 90 || orientation === -90;
  55049. };
  55050. /**
  55051. * Check if device is iOS and older than version 10.
  55052. */
  55053. module.exports.isIOSOlderThan10 = function (userAgent) {
  55054. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  55055. };
  55056. /**
  55057. * Check if running in a browser or spoofed browser (bundler).
  55058. * We need to check a node api that isn't mocked on either side.
  55059. * `require` and `module.exports` are mocked in browser by bundlers.
  55060. * `window` is mocked in node.
  55061. * `process` is also mocked by browserify, but has custom properties.
  55062. */
  55063. module.exports.isBrowserEnvironment = !!(!process || process.browser);
  55064. /**
  55065. * Check if running in node on the server.
  55066. */
  55067. module.exports.isNodeEnvironment = !module.exports.isBrowserEnvironment;
  55068. /**
  55069. * Update an Object3D pose if a polyfilled vrDisplay is present.
  55070. */
  55071. module.exports.PolyfillControls = function PolyfillControls (object) {
  55072. var frameData;
  55073. if (window.VRFrameData) { frameData = new window.VRFrameData(); }
  55074. this.update = function () {
  55075. var pose;
  55076. if (!vrDisplay || !polyfilledVRDisplay) { return; }
  55077. vrDisplay.getFrameData(frameData);
  55078. pose = frameData.pose;
  55079. if (pose.orientation !== null) {
  55080. object.quaternion.fromArray(pose.orientation);
  55081. }
  55082. if (pose.position !== null) {
  55083. object.position.fromArray(pose.position);
  55084. } else {
  55085. object.position.set(0, 0, 0);
  55086. }
  55087. };
  55088. };
  55089. }).call(this,_dereq_('_process'))
  55090. },{"_process":33}],194:[function(_dereq_,module,exports){
  55091. /**
  55092. * Split a delimited component property string (e.g., `material.color`) to an object
  55093. * containing `component` name and `property` name. If there is no delimiter, just return the
  55094. * string back.
  55095. *
  55096. * Cache arrays from splitting strings via delimiter to save on memory.
  55097. *
  55098. * @param {string} str - e.g., `material.opacity`.
  55099. * @param {string} delimiter - e.g., `.`.
  55100. * @returns {array} e.g., `['material', 'opacity']`.
  55101. */
  55102. var propertyPathCache = {};
  55103. function getComponentPropertyPath (str, delimiter) {
  55104. delimiter = delimiter || '.';
  55105. if (!propertyPathCache[delimiter]) { propertyPathCache[delimiter] = {}; }
  55106. if (str.indexOf(delimiter) !== -1) {
  55107. propertyPathCache[delimiter][str] = str.split(delimiter);
  55108. } else {
  55109. propertyPathCache[delimiter][str] = str;
  55110. }
  55111. return propertyPathCache[delimiter][str];
  55112. }
  55113. module.exports.getComponentPropertyPath = getComponentPropertyPath;
  55114. module.exports.propertyPathCache = propertyPathCache;
  55115. /**
  55116. * Get component property using encoded component name + component property name with a
  55117. * delimiter.
  55118. */
  55119. module.exports.getComponentProperty = function (el, name, delimiter) {
  55120. var splitName;
  55121. delimiter = delimiter || '.';
  55122. if (name.indexOf(delimiter) !== -1) {
  55123. splitName = getComponentPropertyPath(name, delimiter);
  55124. if (splitName.constructor === String) {
  55125. return el.getAttribute(splitName);
  55126. }
  55127. return el.getAttribute(splitName[0])[splitName[1]];
  55128. }
  55129. return el.getAttribute(name);
  55130. };
  55131. /**
  55132. * Set component property using encoded component name + component property name with a
  55133. * delimiter.
  55134. */
  55135. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  55136. var splitName;
  55137. delimiter = delimiter || '.';
  55138. if (name.indexOf(delimiter) !== -1) {
  55139. splitName = getComponentPropertyPath(name, delimiter);
  55140. if (splitName.constructor === String) {
  55141. el.setAttribute(splitName, value);
  55142. } else {
  55143. el.setAttribute(splitName[0], splitName[1], value);
  55144. }
  55145. return;
  55146. }
  55147. el.setAttribute(name, value);
  55148. };
  55149. },{}],195:[function(_dereq_,module,exports){
  55150. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  55151. var width = canvasEl.style.width;
  55152. var height = canvasEl.style.height;
  55153. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  55154. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  55155. // By changing the size 1 pixel and restoring the previous value
  55156. // we trigger a size recalculation cycle.
  55157. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  55158. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  55159. setTimeout(function () {
  55160. canvasEl.style.width = width;
  55161. canvasEl.style.height = height;
  55162. }, 200);
  55163. };
  55164. },{}],196:[function(_dereq_,module,exports){
  55165. /* global location */
  55166. /* Centralized place to reference utilities since utils is exposed to the user. */
  55167. var debug = _dereq_('./debug');
  55168. var deepAssign = _dereq_('deep-assign');
  55169. var device = _dereq_('./device');
  55170. var objectAssign = _dereq_('object-assign');
  55171. var objectPool = _dereq_('./object-pool');
  55172. var warn = debug('utils:warn');
  55173. module.exports.bind = _dereq_('./bind');
  55174. module.exports.coordinates = _dereq_('./coordinates');
  55175. module.exports.debug = debug;
  55176. module.exports.device = device;
  55177. module.exports.entity = _dereq_('./entity');
  55178. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  55179. module.exports.material = _dereq_('./material');
  55180. module.exports.objectPool = objectPool;
  55181. module.exports.styleParser = _dereq_('./styleParser');
  55182. module.exports.trackedControls = _dereq_('./tracked-controls');
  55183. module.exports.checkHeadsetConnected = function () {
  55184. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  55185. return device.checkHeadsetConnected(arguments);
  55186. };
  55187. module.exports.isGearVR = function () {
  55188. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  55189. return device.isGearVR(arguments);
  55190. };
  55191. module.exports.isIOS = function () {
  55192. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  55193. return device.isIOS(arguments);
  55194. };
  55195. module.exports.isMobile = function () {
  55196. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  55197. return device.isMobile(arguments);
  55198. };
  55199. /**
  55200. * Returns throttle function that gets called at most once every interval.
  55201. *
  55202. * @param {function} functionToThrottle
  55203. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55204. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55205. * @returns {function} Throttled function.
  55206. */
  55207. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  55208. var lastTime;
  55209. if (optionalContext) {
  55210. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55211. }
  55212. return function () {
  55213. var time = Date.now();
  55214. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  55215. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55216. lastTime = time;
  55217. functionToThrottle.apply(null, arguments);
  55218. }
  55219. };
  55220. };
  55221. /**
  55222. * Returns throttle function that gets called at most once every interval.
  55223. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  55224. *
  55225. * @param {function} functionToThrottle
  55226. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  55227. * @param {object} optionalContext - If given, bind function to throttle to this context.
  55228. * @returns {function} Throttled function.
  55229. */
  55230. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  55231. var lastTime;
  55232. if (optionalContext) {
  55233. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  55234. }
  55235. return function (time, delta) {
  55236. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  55237. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  55238. lastTime = time;
  55239. functionToThrottle(time, sinceLastTime);
  55240. }
  55241. };
  55242. };
  55243. /**
  55244. * Returns debounce function that gets called only once after a set of repeated calls.
  55245. *
  55246. * @param {function} functionToDebounce
  55247. * @param {number} wait - Time to wait for repeated function calls (milliseconds).
  55248. * @param {boolean} immediate - Calls the function immediately regardless of if it should be waiting.
  55249. * @returns {function} Debounced function.
  55250. */
  55251. module.exports.debounce = function (func, wait, immediate) {
  55252. var timeout;
  55253. return function () {
  55254. var context = this;
  55255. var args = arguments;
  55256. var later = function () {
  55257. timeout = null;
  55258. if (!immediate) func.apply(context, args);
  55259. };
  55260. var callNow = immediate && !timeout;
  55261. clearTimeout(timeout);
  55262. timeout = setTimeout(later, wait);
  55263. if (callNow) func.apply(context, args);
  55264. };
  55265. };
  55266. /**
  55267. * Mix the properties of source object(s) into a destination object.
  55268. *
  55269. * @param {object} dest - The object to which properties will be copied.
  55270. * @param {...object} source - The object(s) from which properties will be copied.
  55271. */
  55272. module.exports.extend = objectAssign;
  55273. module.exports.extendDeep = deepAssign;
  55274. module.exports.clone = function (obj) {
  55275. return JSON.parse(JSON.stringify(obj));
  55276. };
  55277. /**
  55278. * Checks if two values are equal.
  55279. * Includes objects and arrays and nested objects and arrays.
  55280. * Try to keep this function performant as it will be called often to see if a component
  55281. * should be updated.
  55282. *
  55283. * @param {object} a - First object.
  55284. * @param {object} b - Second object.
  55285. * @returns {boolean} Whether two objects are deeply equal.
  55286. */
  55287. var deepEqual = (function () {
  55288. var arrayPool = objectPool.createPool(function () { return []; });
  55289. return function (a, b) {
  55290. var key;
  55291. var keysA;
  55292. var keysB;
  55293. var i;
  55294. var valA;
  55295. var valB;
  55296. // If not objects or arrays, compare as values.
  55297. if (a === undefined || b === undefined || a === null || b === null ||
  55298. !(a && b && (a.constructor === Object && b.constructor === Object) ||
  55299. (a.constructor === Array && b.constructor === Array))) {
  55300. return a === b;
  55301. }
  55302. // Different number of keys, not equal.
  55303. keysA = arrayPool.use();
  55304. keysB = arrayPool.use();
  55305. keysA.length = 0;
  55306. keysB.length = 0;
  55307. for (key in a) { keysA.push(key); }
  55308. for (key in b) { keysB.push(key); }
  55309. if (keysA.length !== keysB.length) {
  55310. arrayPool.recycle(keysA);
  55311. arrayPool.recycle(keysB);
  55312. return false;
  55313. }
  55314. // Return `false` at the first sign of inequality.
  55315. for (i = 0; i < keysA.length; ++i) {
  55316. valA = a[keysA[i]];
  55317. valB = b[keysA[i]];
  55318. // Check nested array and object.
  55319. if ((typeof valA === 'object' || typeof valB === 'object') ||
  55320. (Array.isArray(valA) && Array.isArray(valB))) {
  55321. if (valA === valB) { continue; }
  55322. if (!deepEqual(valA, valB)) {
  55323. arrayPool.recycle(keysA);
  55324. arrayPool.recycle(keysB);
  55325. return false;
  55326. }
  55327. } else if (valA !== valB) {
  55328. arrayPool.recycle(keysA);
  55329. arrayPool.recycle(keysB);
  55330. return false;
  55331. }
  55332. }
  55333. arrayPool.recycle(keysA);
  55334. arrayPool.recycle(keysB);
  55335. return true;
  55336. };
  55337. })();
  55338. module.exports.deepEqual = deepEqual;
  55339. /**
  55340. * Computes the difference between two objects.
  55341. *
  55342. * @param {object} a - First object to compare (e.g., oldData).
  55343. * @param {object} b - Second object to compare (e.g., newData).
  55344. * @returns {object}
  55345. * Difference object where set of keys note which values were not equal, and values are
  55346. * `b`'s values.
  55347. */
  55348. module.exports.diff = (function () {
  55349. var keys = [];
  55350. return function (a, b, targetObject) {
  55351. var aVal;
  55352. var bVal;
  55353. var bKey;
  55354. var diff;
  55355. var key;
  55356. var i;
  55357. var isComparingObjects;
  55358. diff = targetObject || {};
  55359. // Collect A keys.
  55360. keys.length = 0;
  55361. for (key in a) { keys.push(key); }
  55362. if (!b) { return diff; }
  55363. // Collect B keys.
  55364. for (bKey in b) {
  55365. if (keys.indexOf(bKey) === -1) {
  55366. keys.push(bKey);
  55367. }
  55368. }
  55369. for (i = 0; i < keys.length; i++) {
  55370. key = keys[i];
  55371. aVal = a[key];
  55372. bVal = b[key];
  55373. isComparingObjects = aVal && bVal &&
  55374. aVal.constructor === Object && bVal.constructor === Object;
  55375. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  55376. (!isComparingObjects && aVal !== bVal)) {
  55377. diff[key] = bVal;
  55378. }
  55379. }
  55380. return diff;
  55381. };
  55382. })();
  55383. /**
  55384. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  55385. * @param {Event} event Event object.
  55386. * @returns {Boolean} Whether the key event should be captured.
  55387. */
  55388. module.exports.shouldCaptureKeyEvent = function (event) {
  55389. if (event.metaKey) { return false; }
  55390. return document.activeElement === document.body;
  55391. };
  55392. /**
  55393. * Splits a string into an array based on a delimiter.
  55394. *
  55395. * @param {string=} [str=''] Source string
  55396. * @param {string=} [delimiter=' '] Delimiter to use
  55397. * @returns {array} Array of delimited strings
  55398. */
  55399. module.exports.splitString = function (str, delimiter) {
  55400. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  55401. // First collapse the whitespace (or whatever the delimiter is).
  55402. var regex = new RegExp(delimiter, 'g');
  55403. str = (str || '').replace(regex, delimiter);
  55404. // Then split.
  55405. return str.split(delimiter);
  55406. };
  55407. /**
  55408. * Extracts data from the element given an object that contains expected keys.
  55409. *
  55410. * @param {Element} Source element.
  55411. * @param {Object} [defaults={}] Object of default key-value pairs.
  55412. * @returns {Object}
  55413. */
  55414. module.exports.getElData = function (el, defaults) {
  55415. defaults = defaults || {};
  55416. var data = {};
  55417. Object.keys(defaults).forEach(copyAttribute);
  55418. function copyAttribute (key) {
  55419. if (el.hasAttribute(key)) {
  55420. data[key] = el.getAttribute(key);
  55421. }
  55422. }
  55423. return data;
  55424. };
  55425. /**
  55426. * Retrieves querystring value.
  55427. * @param {String} name Name of querystring key.
  55428. * @return {String} Value
  55429. */
  55430. module.exports.getUrlParameter = function (name) {
  55431. // eslint-disable-next-line no-useless-escape
  55432. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  55433. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  55434. var results = regex.exec(location.search);
  55435. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  55436. };
  55437. /**
  55438. * Detects whether context is within iframe.
  55439. */
  55440. module.exports.isIframed = function () {
  55441. return window.top !== window.self;
  55442. };
  55443. /**
  55444. * Finds all elements under the element that have the isScene
  55445. * property set to true
  55446. */
  55447. module.exports.findAllScenes = function (el) {
  55448. var matchingElements = [];
  55449. var allElements = el.getElementsByTagName('*');
  55450. for (var i = 0, n = allElements.length; i < n; i++) {
  55451. if (allElements[i].isScene) {
  55452. // Element exists with isScene set.
  55453. matchingElements.push(allElements[i]);
  55454. }
  55455. }
  55456. return matchingElements;
  55457. };
  55458. // Must be at bottom to avoid circular dependency.
  55459. module.exports.srcLoader = _dereq_('./src-loader');
  55460. /**
  55461. * String split with cached result.
  55462. */
  55463. module.exports.split = (function () {
  55464. var splitCache = {};
  55465. return function (str, delimiter) {
  55466. if (!(delimiter in splitCache)) { splitCache[delimiter] = {}; }
  55467. if (str in splitCache[delimiter]) { return splitCache[delimiter][str]; }
  55468. splitCache[delimiter][str] = str.split(delimiter);
  55469. return splitCache[delimiter][str];
  55470. };
  55471. })();
  55472. },{"./bind":190,"./coordinates":191,"./debug":192,"./device":193,"./entity":194,"./forceCanvasResizeSafariMobile":195,"./material":197,"./object-pool":198,"./src-loader":199,"./styleParser":200,"./tracked-controls":201,"deep-assign":10,"object-assign":26}],197:[function(_dereq_,module,exports){
  55473. var THREE = _dereq_('../lib/three');
  55474. var HLS_MIMETYPES = ['application/x-mpegurl', 'application/vnd.apple.mpegurl'];
  55475. /**
  55476. * Update `material` texture property (usually but not always `map`)
  55477. * from `data` property (usually but not always `src`)
  55478. *
  55479. * @param {object} shader - A-Frame shader instance.
  55480. * @param {object} data
  55481. */
  55482. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  55483. var el = shader.el;
  55484. var material = shader.material;
  55485. var src = data[dataName];
  55486. // Because a single material / shader may have multiple textures,
  55487. // we need to remember the source value for this data property
  55488. // to avoid redundant operations which can be expensive otherwise
  55489. // (e.g. video texture loads).
  55490. if (!shader.materialSrcs) { shader.materialSrcs = {}; }
  55491. if (!src) {
  55492. // Forget the prior material src.
  55493. delete shader.materialSrcs[materialName];
  55494. // Remove the texture.
  55495. setMap(null);
  55496. return;
  55497. }
  55498. // Don't process if material src hasn't changed.
  55499. if (src === shader.materialSrcs[materialName]) { return; }
  55500. // Remember the new src for this texture (there may be multiple).
  55501. shader.materialSrcs[materialName] = src;
  55502. // If the new material src is already a texture, just use it.
  55503. if (src instanceof THREE.Texture) { setMap(src); } else {
  55504. // Load texture for the new material src.
  55505. // (And check if we should still use it once available in callback.)
  55506. el.sceneEl.systems.material.loadTexture(src,
  55507. {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot},
  55508. checkSetMap);
  55509. }
  55510. function checkSetMap (texture) {
  55511. // If the source has been changed, don't use loaded texture.
  55512. if (shader.materialSrcs[materialName] !== src) { return; }
  55513. setMap(texture);
  55514. }
  55515. function setMap (texture) {
  55516. material[materialName] = texture;
  55517. material.needsUpdate = true;
  55518. handleTextureEvents(el, texture);
  55519. }
  55520. };
  55521. /**
  55522. * Update `material.map` given `data.src`. For standard and flat shaders.
  55523. *
  55524. * @param {object} shader - A-Frame shader instance.
  55525. * @param {object} data
  55526. */
  55527. module.exports.updateMap = function (shader, data) {
  55528. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  55529. };
  55530. /**
  55531. * Updates the material's maps which give the illusion of extra geometry.
  55532. *
  55533. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  55534. * @param {object} shader - A-Frame shader instance
  55535. * @param {object} data
  55536. */
  55537. module.exports.updateDistortionMap = function (longType, shader, data) {
  55538. var shortType = longType;
  55539. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  55540. var el = shader.el;
  55541. var material = shader.material;
  55542. var src = data[longType + 'Map'];
  55543. var info = {};
  55544. info.src = src;
  55545. // Pass through the repeat and offset to be handled by the material loader.
  55546. info.offset = data[longType + 'TextureOffset'];
  55547. info.repeat = data[longType + 'TextureRepeat'];
  55548. info.wrap = data[longType + 'TextureWrap'];
  55549. if (src) {
  55550. if (src === shader[longType + 'TextureSrc']) { return; }
  55551. // Texture added or changed.
  55552. shader[longType + 'TextureSrc'] = src;
  55553. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  55554. return;
  55555. }
  55556. // Texture removed.
  55557. if (!material.map) { return; }
  55558. setMap(null);
  55559. function setMap (texture) {
  55560. material[shortType + 'Map'] = texture;
  55561. material.needsUpdate = true;
  55562. handleTextureEvents(el, texture);
  55563. }
  55564. };
  55565. /**
  55566. * Emit event on entities on texture-related events.
  55567. *
  55568. * @param {Element} el - Entity.
  55569. * @param {object} texture - three.js Texture.
  55570. */
  55571. function handleTextureEvents (el, texture) {
  55572. if (!texture) { return; }
  55573. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  55574. // Video events.
  55575. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  55576. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  55577. // Check to see if we need to use iOS 10 HLS shader.
  55578. // Only override the shader if it is stock shader that we know doesn't correct.
  55579. if (!el.components || !el.components.material) { return; }
  55580. if (texture.needsCorrectionBGRA && texture.needsCorrectionFlipY &&
  55581. ['standard', 'flat'].indexOf(el.components.material.data.shader) !== -1) {
  55582. el.setAttribute('material', 'shader', 'ios10hls');
  55583. }
  55584. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  55585. });
  55586. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  55587. // Works for non-looping videos only.
  55588. el.emit('materialvideoended', {src: texture.image, texture: texture});
  55589. });
  55590. }
  55591. module.exports.handleTextureEvents = handleTextureEvents;
  55592. /**
  55593. * Given video element src and type, guess whether stream is HLS.
  55594. *
  55595. * @param {string} src - src from video element (generally URL to content).
  55596. * @param {string} type - type from video element (generally MIME type if present).
  55597. */
  55598. module.exports.isHLS = function (src, type) {
  55599. if (type && HLS_MIMETYPES.includes(type.toLowerCase())) { return true; }
  55600. if (src && src.toLowerCase().indexOf('.m3u8') > 0) { return true; }
  55601. return false;
  55602. };
  55603. },{"../lib/three":174}],198:[function(_dereq_,module,exports){
  55604. /*
  55605. Adapted deePool by Kyle Simpson.
  55606. MIT License: http://getify.mit-license.org
  55607. */
  55608. var EMPTY_SLOT = Object.freeze(Object.create(null));
  55609. // Default object factory.
  55610. function defaultObjectFactory () { return {}; }
  55611. /**
  55612. * Create a new pool.
  55613. */
  55614. module.exports.createPool = function createPool (objectFactory) {
  55615. var objPool = [];
  55616. var nextFreeSlot = null; // Pool location to look for a free object to use.
  55617. objectFactory = objectFactory || defaultObjectFactory;
  55618. function use () {
  55619. var objToUse;
  55620. if (nextFreeSlot === null || nextFreeSlot === objPool.length) {
  55621. grow(objPool.length || 5);
  55622. }
  55623. objToUse = objPool[nextFreeSlot];
  55624. objPool[nextFreeSlot++] = EMPTY_SLOT;
  55625. clearObject(objToUse);
  55626. return objToUse;
  55627. }
  55628. function recycle (obj) {
  55629. if (!(obj instanceof Object)) { return; }
  55630. if (nextFreeSlot === null || nextFreeSlot === -1) {
  55631. objPool[objPool.length] = obj;
  55632. return;
  55633. }
  55634. objPool[--nextFreeSlot] = obj;
  55635. }
  55636. function grow (count) {
  55637. var currentLength;
  55638. var i;
  55639. count = count === undefined ? objPool.length : count;
  55640. if (count > 0 && nextFreeSlot == null) {
  55641. nextFreeSlot = 0;
  55642. }
  55643. if (count > 0) {
  55644. currentLength = objPool.length;
  55645. objPool.length += Number(count);
  55646. for (i = currentLength; i < objPool.length; i++) {
  55647. // Add new obj to pool.
  55648. objPool[i] = objectFactory();
  55649. }
  55650. }
  55651. return objPool.length;
  55652. }
  55653. function size () {
  55654. return objPool.length;
  55655. }
  55656. return {
  55657. grow: grow,
  55658. pool: objPool,
  55659. recycle: recycle,
  55660. size: size,
  55661. use: use
  55662. };
  55663. };
  55664. function clearObject (obj) {
  55665. var key;
  55666. if (!(obj.constructor === Object)) { return; }
  55667. for (key in obj) { obj[key] = undefined; }
  55668. }
  55669. module.exports.clearObject = clearObject;
  55670. },{}],199:[function(_dereq_,module,exports){
  55671. /* global Image, XMLHttpRequest */
  55672. var debug = _dereq_('./debug');
  55673. var warn = debug('utils:src-loader:warn');
  55674. /**
  55675. * Validate a texture, either as a selector or as a URL.
  55676. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  55677. * callback.
  55678. *
  55679. * `src` will be passed into the callback
  55680. *
  55681. * @params {string|Element} src - URL or media element.
  55682. * @params {function} isImageCb - callback if texture is an image.
  55683. * @params {function} isVideoCb - callback if texture is a video.
  55684. */
  55685. function validateSrc (src, isImageCb, isVideoCb) {
  55686. checkIsImage(src, function isAnImageUrl (isImage) {
  55687. if (isImage) {
  55688. isImageCb(src);
  55689. return;
  55690. }
  55691. isVideoCb(src);
  55692. });
  55693. }
  55694. /**
  55695. * Validates six images as a cubemap, either as selector or comma-separated
  55696. * URLs.
  55697. *
  55698. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55699. must be wrapped by `url()`.
  55700. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  55701. must be wrapped by `url()`.
  55702. */
  55703. function validateCubemapSrc (src, cb) {
  55704. var aCubemap;
  55705. var cubemapSrcRegex = '';
  55706. var i;
  55707. var urls;
  55708. var validatedUrls = [];
  55709. for (i = 0; i < 5; i++) {
  55710. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  55711. }
  55712. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  55713. urls = src.match(new RegExp(cubemapSrcRegex));
  55714. // `src` is a comma-separated list of URLs.
  55715. // In this case, re-use validateSrc for each side of the cube.
  55716. function isImageCb (url) {
  55717. validatedUrls.push(url);
  55718. if (validatedUrls.length === 6) {
  55719. cb(validatedUrls);
  55720. }
  55721. }
  55722. if (urls) {
  55723. for (i = 1; i < 7; i++) {
  55724. validateSrc(parseUrl(urls[i]), isImageCb);
  55725. }
  55726. return;
  55727. }
  55728. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  55729. aCubemap = validateAndGetQuerySelector(src);
  55730. if (!aCubemap) { return; }
  55731. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  55732. return cb(aCubemap.srcs);
  55733. }
  55734. // Else if aCubeMap is not a <a-cubemap>.
  55735. warn('Selector "%s" does not point to <a-cubemap>', src);
  55736. }
  55737. /**
  55738. * Parses src from `url(src)`.
  55739. * @param {string} src - String to parse.
  55740. * @return {string} The parsed src, if parseable.
  55741. */
  55742. function parseUrl (src) {
  55743. var parsedSrc = src.match(/\url\((.+)\)/);
  55744. if (!parsedSrc) { return; }
  55745. return parsedSrc[1];
  55746. }
  55747. /**
  55748. * Call back whether `src` is an image.
  55749. *
  55750. * @param {string|Element} src - URL or element that will be tested.
  55751. * @param {function} onResult - Callback with whether `src` is an image.
  55752. */
  55753. function checkIsImage (src, onResult) {
  55754. var request;
  55755. if (src.tagName) {
  55756. onResult(src.tagName === 'IMG');
  55757. return;
  55758. }
  55759. request = new XMLHttpRequest();
  55760. // Try to send HEAD request to check if image first.
  55761. request.open('HEAD', src);
  55762. request.addEventListener('load', function (event) {
  55763. var contentType;
  55764. if (request.status >= 200 && request.status < 300) {
  55765. contentType = request.getResponseHeader('Content-Type');
  55766. if (contentType == null) {
  55767. checkIsImageFallback(src, onResult);
  55768. } else {
  55769. if (contentType.startsWith('image')) {
  55770. onResult(true);
  55771. } else {
  55772. onResult(false);
  55773. }
  55774. }
  55775. } else {
  55776. checkIsImageFallback(src, onResult);
  55777. }
  55778. request.abort();
  55779. });
  55780. request.send();
  55781. }
  55782. function checkIsImageFallback (src, onResult) {
  55783. var tester = new Image();
  55784. tester.addEventListener('load', onLoad);
  55785. function onLoad () { onResult(true); }
  55786. tester.addEventListener('error', onError);
  55787. function onError () { onResult(false); }
  55788. tester.src = src;
  55789. }
  55790. /**
  55791. * Query and validate a query selector,
  55792. *
  55793. * @param {string} selector - DOM selector.
  55794. * @return {object|null|undefined} Selected DOM element if exists.
  55795. null if query yields no results.
  55796. undefined if `selector` is not a valid selector.
  55797. */
  55798. function validateAndGetQuerySelector (selector) {
  55799. try {
  55800. var el = document.querySelector(selector);
  55801. if (!el) {
  55802. warn('No element was found matching the selector: "%s"', selector);
  55803. }
  55804. return el;
  55805. } catch (e) { // Capture exception if it's not a valid selector.
  55806. warn('"%s" is not a valid selector', selector);
  55807. return undefined;
  55808. }
  55809. }
  55810. module.exports = {
  55811. parseUrl: parseUrl,
  55812. validateSrc: validateSrc,
  55813. validateCubemapSrc: validateCubemapSrc
  55814. };
  55815. },{"./debug":192}],200:[function(_dereq_,module,exports){
  55816. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  55817. var styleParser = _dereq_('style-attr');
  55818. /**
  55819. * Deserializes style-like string into an object of properties.
  55820. *
  55821. * @param {string} value - HTML attribute value.
  55822. * @returns {object} Property data.
  55823. */
  55824. module.exports.parse = function (value) {
  55825. var parsedData;
  55826. if (typeof value !== 'string') { return value; }
  55827. parsedData = styleParser.parse(value);
  55828. // The style parser returns an object { "" : "test"} when fed a string
  55829. if (parsedData['']) { return value; }
  55830. return transformKeysToCamelCase(parsedData);
  55831. };
  55832. /**
  55833. * Serialize an object of properties into a style-like string.
  55834. *
  55835. * @param {object} data - Property data.
  55836. * @returns {string}
  55837. */
  55838. module.exports.stringify = function (data) {
  55839. if (typeof data === 'string') { return data; }
  55840. return styleParser.stringify(data);
  55841. };
  55842. /**
  55843. * Converts string from hyphen to camelCase.
  55844. *
  55845. * @param {string} str - String to camelCase.
  55846. * @return {string} CamelCased string.
  55847. */
  55848. function toCamelCase (str) {
  55849. return str.replace(/-([a-z])/g, camelCase);
  55850. function camelCase (g) { return g[1].toUpperCase(); }
  55851. }
  55852. module.exports.toCamelCase = toCamelCase;
  55853. /**
  55854. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  55855. * `maxValue`).
  55856. *
  55857. * @param {object} obj - The object to camelCase keys.
  55858. * @return {object} The object with keys camelCased.
  55859. */
  55860. function transformKeysToCamelCase (obj) {
  55861. var keys = Object.keys(obj);
  55862. var camelCaseObj = {};
  55863. keys.forEach(function (key) {
  55864. var camelCaseKey = toCamelCase(key);
  55865. camelCaseObj[camelCaseKey] = obj[key];
  55866. });
  55867. return camelCaseObj;
  55868. }
  55869. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  55870. },{"style-attr":36}],201:[function(_dereq_,module,exports){
  55871. var DEFAULT_HANDEDNESS = _dereq_('../constants').DEFAULT_HANDEDNESS;
  55872. var AXIS_LABELS = ['x', 'y', 'z', 'w'];
  55873. var NUM_HANDS = 2; // Number of hands in a pair. Should always be 2.
  55874. /**
  55875. * Called on controller component `.play` handlers.
  55876. * Check if controller matches parameters and inject tracked-controls component.
  55877. * Handle event listeners.
  55878. * Generate controllerconnected or controllerdisconnected events.
  55879. *
  55880. * @param {object} component - Tracked controls component.
  55881. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55882. * @param {object} queryObject - Map of values to match.
  55883. */
  55884. module.exports.checkControllerPresentAndSetup = function (component, idPrefix, queryObject) {
  55885. var el = component.el;
  55886. var isPresent = isControllerPresent(component, idPrefix, queryObject);
  55887. // If component was previously paused and now playing, re-add event listeners.
  55888. // Handle the event listeners here since this helper method is control of calling
  55889. // `.addEventListeners` and `.removeEventListeners`.
  55890. if (component.controllerPresent && !component.controllerEventsActive) {
  55891. component.addEventListeners();
  55892. }
  55893. // Nothing changed, no need to do anything.
  55894. if (isPresent === component.controllerPresent) { return isPresent; }
  55895. component.controllerPresent = isPresent;
  55896. // Update controller presence.
  55897. if (isPresent) {
  55898. component.injectTrackedControls();
  55899. component.addEventListeners();
  55900. el.emit('controllerconnected', {name: component.name, component: component});
  55901. } else {
  55902. component.removeEventListeners();
  55903. el.emit('controllerdisconnected', {name: component.name, component: component});
  55904. }
  55905. };
  55906. /**
  55907. * Enumerate controller (that have pose) and check if they match parameters.
  55908. *
  55909. * @param {object} component - Tracked controls component.
  55910. * @param {object} idPrefix - Prefix to match in gamepad id if any.
  55911. * @param {object} queryObject - Map of values to match.
  55912. */
  55913. function isControllerPresent (component, idPrefix, queryObject) {
  55914. var gamepads;
  55915. var sceneEl = component.el.sceneEl;
  55916. var trackedControlsSystem;
  55917. var filterControllerIndex = queryObject.index || 0;
  55918. if (!idPrefix) { return false; }
  55919. trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  55920. if (!trackedControlsSystem) { return false; }
  55921. gamepads = trackedControlsSystem.controllers;
  55922. if (!gamepads.length) { return false; }
  55923. return !!findMatchingController(gamepads, null, idPrefix, queryObject.hand, filterControllerIndex);
  55924. }
  55925. module.exports.isControllerPresent = isControllerPresent;
  55926. /**
  55927. * Walk through the given controllers to find any where the device ID equals filterIdExact, or startWith filterIdPrefix.
  55928. * A controller where this considered true is considered a 'match'.
  55929. *
  55930. * For each matching controller:
  55931. * If filterHand is set, and the controller:
  55932. * is handed, we further verify that controller.hand equals filterHand.
  55933. * is unhanded (controller.hand is ''), we skip until we have found a number of matching controllers that equals filterControllerIndex
  55934. * If filterHand is not set, we skip until we have found the nth matching controller, where n equals filterControllerIndex
  55935. *
  55936. * The method should be called with one of: [filterIdExact, filterIdPrefix] AND one or both of: [filterHand, filterControllerIndex]
  55937. *
  55938. * @param {object} controllers - Array of gamepads to search
  55939. * @param {string} filterIdExact - If set, used to find controllers with id === this value
  55940. * @param {string} filterIdPrefix - If set, used to find controllers with id startsWith this value
  55941. * @param {object} filterHand - If set, further filters controllers with matching 'hand' property
  55942. * @param {object} filterControllerIndex - Find the nth matching controller, where n equals filterControllerIndex. defaults to 0.
  55943. */
  55944. function findMatchingController (controllers, filterIdExact, filterIdPrefix, filterHand, filterControllerIndex) {
  55945. var controller;
  55946. var i;
  55947. var matchingControllerOccurence = 0;
  55948. var targetControllerMatch = filterControllerIndex || 0;
  55949. for (i = 0; i < controllers.length; i++) {
  55950. controller = controllers[i];
  55951. // Determine if the controller ID matches our criteria
  55952. if (filterIdPrefix && controller.id.indexOf(filterIdPrefix) === -1) { continue; }
  55953. if (!filterIdPrefix && controller.id !== filterIdExact) { continue; }
  55954. // If the hand filter and controller handedness are defined we compare them.
  55955. if (filterHand && controller.hand && filterHand !== controller.hand) { continue; }
  55956. // If we have detected an unhanded controller and the component was asking for a particular hand,
  55957. // we need to treat the controllers in the array as pairs of controllers. This effectively means that we
  55958. // need to skip NUM_HANDS matches for each controller number, instead of 1.
  55959. if (filterHand && !controller.hand) {
  55960. targetControllerMatch = NUM_HANDS * filterControllerIndex + ((filterHand === DEFAULT_HANDEDNESS) ? 0 : 1);
  55961. }
  55962. // We are looking for the nth occurence of a matching controller (n equals targetControllerMatch).
  55963. if (matchingControllerOccurence === targetControllerMatch) {
  55964. return controller;
  55965. }
  55966. ++matchingControllerOccurence;
  55967. }
  55968. return undefined;
  55969. }
  55970. module.exports.findMatchingController = findMatchingController;
  55971. /**
  55972. * Emit specific `moved` event(s) if axes changed based on original axismoved event.
  55973. *
  55974. * @param {object} component - Controller component in use.
  55975. * @param {array} axesMapping - For example `{thumbstick: [0, 1]}`.
  55976. * @param {object} evt - Event to process.
  55977. */
  55978. module.exports.emitIfAxesChanged = function (component, axesMapping, evt) {
  55979. var axes;
  55980. var buttonTypes;
  55981. var changed;
  55982. var detail;
  55983. var i;
  55984. var j;
  55985. buttonTypes = Object.keys(axesMapping);
  55986. for (i = 0; i < buttonTypes.length; i++) {
  55987. axes = axesMapping[buttonTypes[i]];
  55988. changed = false;
  55989. for (j = 0; j < axes.length; j++) {
  55990. if (evt.detail.changed[axes[j]]) { changed = true; }
  55991. }
  55992. if (!changed) { continue; }
  55993. // Axis has changed. Emit the specific moved event with axis values in detail.
  55994. detail = {};
  55995. for (j = 0; j < axes.length; j++) {
  55996. detail[AXIS_LABELS[j]] = evt.detail.axis[axes[j]];
  55997. }
  55998. component.el.emit(buttonTypes[i] + 'moved', detail);
  55999. }
  56000. };
  56001. /**
  56002. * Handle a button event and reemits the events.
  56003. *
  56004. * @param {string} id - id of the button.
  56005. * @param {string} evtName - name of the reemitted event
  56006. * @param {object} component - reference to the component
  56007. * @param {string} hand - handedness of the controller: left or right.
  56008. */
  56009. module.exports.onButtonEvent = function (id, evtName, component, hand) {
  56010. var mapping = hand ? component.mapping[hand] : component.mapping;
  56011. var buttonName = mapping.buttons[id];
  56012. component.el.emit(buttonName + evtName);
  56013. if (component.updateModel) {
  56014. component.updateModel(buttonName, evtName);
  56015. }
  56016. };
  56017. },{"../constants":117}],202:[function(_dereq_,module,exports){
  56018. window.glStats = function () {
  56019. var _rS = null;
  56020. var _totalDrawArraysCalls = 0,
  56021. _totalDrawElementsCalls = 0,
  56022. _totalUseProgramCalls = 0,
  56023. _totalFaces = 0,
  56024. _totalVertices = 0,
  56025. _totalPoints = 0,
  56026. _totalBindTexures = 0;
  56027. function _h ( f, c ) {
  56028. return function () {
  56029. c.apply( this, arguments );
  56030. f.apply( this, arguments );
  56031. };
  56032. }
  56033. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  56034. _totalDrawArraysCalls++;
  56035. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  56036. else _totalVertices += arguments[ 2 ];
  56037. } );
  56038. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  56039. _totalDrawElementsCalls++;
  56040. _totalFaces += arguments[ 1 ] / 3;
  56041. _totalVertices += arguments[ 1 ];
  56042. } );
  56043. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  56044. _totalUseProgramCalls++;
  56045. } );
  56046. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  56047. _totalBindTexures++;
  56048. } );
  56049. var _values = {
  56050. allcalls: {
  56051. over: 3000,
  56052. caption: 'Calls (hook)'
  56053. },
  56054. drawelements: {
  56055. caption: 'drawElements (hook)'
  56056. },
  56057. drawarrays: {
  56058. caption: 'drawArrays (hook)'
  56059. }
  56060. };
  56061. var _groups = [ {
  56062. caption: 'WebGL',
  56063. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  56064. } ];
  56065. var _fractions = [ {
  56066. base: 'allcalls',
  56067. steps: [ 'drawelements', 'drawarrays' ]
  56068. } ];
  56069. function _update () {
  56070. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  56071. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  56072. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  56073. _rS( 'bindTexture' ).set( _totalBindTexures );
  56074. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  56075. _rS( 'glfaces' ).set( _totalFaces );
  56076. _rS( 'glvertices' ).set( _totalVertices );
  56077. _rS( 'glpoints' ).set( _totalPoints );
  56078. }
  56079. function _start () {
  56080. _totalDrawArraysCalls = 0;
  56081. _totalDrawElementsCalls = 0;
  56082. _totalUseProgramCalls = 0;
  56083. _totalFaces = 0;
  56084. _totalVertices = 0;
  56085. _totalPoints = 0;
  56086. _totalBindTexures = 0;
  56087. }
  56088. function _end () {}
  56089. function _attach ( r ) {
  56090. _rS = r;
  56091. }
  56092. return {
  56093. update: _update,
  56094. start: _start,
  56095. end: _end,
  56096. attach: _attach,
  56097. values: _values,
  56098. groups: _groups,
  56099. fractions: _fractions
  56100. };
  56101. };
  56102. window.threeStats = function ( renderer ) {
  56103. var _rS = null;
  56104. var _values = {
  56105. 'renderer.info.memory.geometries': {
  56106. caption: 'Geometries'
  56107. },
  56108. 'renderer.info.memory.textures': {
  56109. caption: 'Textures'
  56110. },
  56111. 'renderer.info.programs': {
  56112. caption: 'Programs'
  56113. },
  56114. 'renderer.info.render.calls': {
  56115. caption: 'Calls'
  56116. },
  56117. 'renderer.info.render.faces': {
  56118. caption: 'Faces',
  56119. over: 1000
  56120. },
  56121. 'renderer.info.render.points': {
  56122. caption: 'Points'
  56123. },
  56124. 'renderer.info.render.vertices': {
  56125. caption: 'Vertices'
  56126. }
  56127. };
  56128. var _groups = [ {
  56129. caption: 'Three.js - Memory',
  56130. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  56131. }, {
  56132. caption: 'Three.js - Render',
  56133. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  56134. } ];
  56135. var _fractions = [];
  56136. function _update () {
  56137. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  56138. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  56139. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  56140. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  56141. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  56142. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  56143. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  56144. }
  56145. function _start () {}
  56146. function _end () {}
  56147. function _attach ( r ) {
  56148. _rS = r;
  56149. }
  56150. return {
  56151. update: _update,
  56152. start: _start,
  56153. end: _end,
  56154. attach: _attach,
  56155. values: _values,
  56156. groups: _groups,
  56157. fractions: _fractions
  56158. };
  56159. };
  56160. /*
  56161. * From https://github.com/paulirish/memory-stats.js
  56162. */
  56163. window.BrowserStats = function () {
  56164. var _rS = null;
  56165. var _usedJSHeapSize = 0,
  56166. _totalJSHeapSize = 0;
  56167. if ( window.performance && !performance.memory ) {
  56168. performance.memory = {
  56169. usedJSHeapSize: 0,
  56170. totalJSHeapSize: 0
  56171. };
  56172. }
  56173. if ( performance.memory.totalJSHeapSize === 0 ) {
  56174. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  56175. }
  56176. var _values = {
  56177. memory: {
  56178. caption: 'Used Memory',
  56179. average: true,
  56180. avgMs: 1000,
  56181. over: 22
  56182. },
  56183. total: {
  56184. caption: 'Total Memory'
  56185. }
  56186. };
  56187. var _groups = [ {
  56188. caption: 'Browser',
  56189. values: [ 'memory', 'total' ]
  56190. } ];
  56191. var _fractions = [ {
  56192. base: 'total',
  56193. steps: [ 'memory' ]
  56194. } ];
  56195. var log1024 = Math.log( 1024 );
  56196. function _size ( v ) {
  56197. var precision = 100; //Math.pow(10, 2);
  56198. var i = Math.floor( Math.log( v ) / log1024 );
  56199. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  56200. }
  56201. function _update () {
  56202. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  56203. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  56204. _rS( 'memory' ).set( _usedJSHeapSize );
  56205. _rS( 'total' ).set( _totalJSHeapSize );
  56206. }
  56207. function _start () {
  56208. _usedJSHeapSize = 0;
  56209. }
  56210. function _end () {}
  56211. function _attach ( r ) {
  56212. _rS = r;
  56213. }
  56214. return {
  56215. update: _update,
  56216. start: _start,
  56217. end: _end,
  56218. attach: _attach,
  56219. values: _values,
  56220. groups: _groups,
  56221. fractions: _fractions
  56222. };
  56223. };
  56224. if (typeof module === 'object') {
  56225. module.exports = {
  56226. glStats: window.glStats,
  56227. threeStats: window.threeStats,
  56228. BrowserStats: window.BrowserStats
  56229. };
  56230. }
  56231. },{}],203:[function(_dereq_,module,exports){
  56232. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  56233. 'use strict';
  56234. ( function () {
  56235. if ( 'performance' in window == false ) {
  56236. window.performance = {};
  56237. }
  56238. var performance = window.performance;
  56239. if ( 'now' in performance == false ) {
  56240. var nowOffset = Date.now();
  56241. if ( performance.timing && performance.timing.navigationStart ) {
  56242. nowOffset = performance.timing.navigationStart;
  56243. }
  56244. performance.now = function now () {
  56245. return Date.now() - nowOffset;
  56246. };
  56247. }
  56248. if( !performance.mark ) {
  56249. performance.mark = function(){}
  56250. }
  56251. if( !performance.measure ) {
  56252. performance.measure = function(){}
  56253. }
  56254. } )();
  56255. window.rStats = function rStats ( settings ) {
  56256. function iterateKeys ( array, callback ) {
  56257. var keys = Object.keys( array );
  56258. for ( var j = 0, l = keys.length; j < l; j++ ) {
  56259. callback( keys[ j ] );
  56260. }
  56261. }
  56262. function importCSS ( url ) {
  56263. var element = document.createElement( 'link' );
  56264. element.href = url;
  56265. element.rel = 'stylesheet';
  56266. element.type = 'text/css';
  56267. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  56268. }
  56269. var _settings = settings || {};
  56270. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  56271. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  56272. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  56273. var _css = _settings.css || [ _cssFont, _cssRStats ];
  56274. _css.forEach(function (uri) {
  56275. importCSS( uri );
  56276. });
  56277. if ( !_settings.values ) _settings.values = {};
  56278. var _base, _div, _elHeight = 10, _elWidth = 200;
  56279. var _perfCounters = {};
  56280. function Graph ( _dom, _id, _defArg ) {
  56281. var _def = _defArg || {};
  56282. var _canvas = document.createElement( 'canvas' ),
  56283. _ctx = _canvas.getContext( '2d' ),
  56284. _max = 0,
  56285. _current = 0;
  56286. var c = _def.color ? _def.color : '#666666';
  56287. var _dotCanvas = document.createElement( 'canvas' ),
  56288. _dotCtx = _dotCanvas.getContext( '2d' );
  56289. _dotCanvas.width = 1;
  56290. _dotCanvas.height = 2 * _elHeight;
  56291. _dotCtx.fillStyle = '#444444';
  56292. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56293. _dotCtx.fillStyle = c;
  56294. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56295. _dotCtx.fillStyle = '#ffffff';
  56296. _dotCtx.globalAlpha = 0.5;
  56297. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  56298. _dotCtx.globalAlpha = 1;
  56299. var _alarmCanvas = document.createElement( 'canvas' ),
  56300. _alarmCtx = _alarmCanvas.getContext( '2d' );
  56301. _alarmCanvas.width = 1;
  56302. _alarmCanvas.height = 2 * _elHeight;
  56303. _alarmCtx.fillStyle = '#444444';
  56304. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  56305. _alarmCtx.fillStyle = '#b70000';
  56306. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  56307. _alarmCtx.globalAlpha = 0.5;
  56308. _alarmCtx.fillStyle = '#ffffff';
  56309. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  56310. _alarmCtx.globalAlpha = 1;
  56311. function _init () {
  56312. _canvas.width = _elWidth;
  56313. _canvas.height = _elHeight;
  56314. _canvas.style.width = _canvas.width + 'px';
  56315. _canvas.style.height = _canvas.height + 'px';
  56316. _canvas.className = 'rs-canvas';
  56317. _dom.appendChild( _canvas );
  56318. _ctx.fillStyle = '#444444';
  56319. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56320. }
  56321. function _draw ( v, alarm ) {
  56322. _current += ( v - _current ) * 0.1;
  56323. _max *= 0.99;
  56324. if ( _current > _max ) _max = _current;
  56325. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56326. if ( alarm ) {
  56327. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56328. } else {
  56329. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  56330. }
  56331. }
  56332. _init();
  56333. return {
  56334. draw: _draw
  56335. };
  56336. }
  56337. function StackGraph ( _dom, _num ) {
  56338. var _canvas = document.createElement( 'canvas' ),
  56339. _ctx = _canvas.getContext( '2d' );
  56340. function _init () {
  56341. _canvas.width = _elWidth;
  56342. _canvas.height = _elHeight * _num;
  56343. _canvas.style.width = _canvas.width + 'px';
  56344. _canvas.style.height = _canvas.height + 'px';
  56345. _canvas.className = 'rs-canvas';
  56346. _dom.appendChild( _canvas );
  56347. _ctx.fillStyle = '#444444';
  56348. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  56349. }
  56350. function _draw ( v ) {
  56351. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  56352. var th = 0;
  56353. iterateKeys( v, function ( j ) {
  56354. var h = v[ j ] * _canvas.height;
  56355. _ctx.fillStyle = _colours[ j ];
  56356. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  56357. th += h;
  56358. } );
  56359. }
  56360. _init();
  56361. return {
  56362. draw: _draw
  56363. };
  56364. }
  56365. function PerfCounter ( id, group ) {
  56366. var _id = id,
  56367. _time,
  56368. _value = 0,
  56369. _total = 0,
  56370. _averageValue = 0,
  56371. _accumValue = 0,
  56372. _accumStart = performance.now(),
  56373. _accumSamples = 0,
  56374. _dom = document.createElement( 'div' ),
  56375. _spanId = document.createElement( 'span' ),
  56376. _spanValue = document.createElement( 'div' ),
  56377. _spanValueText = document.createTextNode( '' ),
  56378. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  56379. _graph = new Graph( _dom, _id, _def ),
  56380. _started = false;
  56381. _spanId.className = 'rs-counter-id';
  56382. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  56383. _spanValue.className = 'rs-counter-value';
  56384. _spanValue.appendChild( _spanValueText );
  56385. _dom.appendChild( _spanId );
  56386. _dom.appendChild( _spanValue );
  56387. if ( group ) group.div.appendChild( _dom );
  56388. else _div.appendChild( _dom );
  56389. _time = performance.now();
  56390. function _average ( v ) {
  56391. if ( _def && _def.average ) {
  56392. _accumValue += v;
  56393. _accumSamples++;
  56394. var t = performance.now();
  56395. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  56396. _averageValue = _accumValue / _accumSamples;
  56397. _accumValue = 0;
  56398. _accumStart = t;
  56399. _accumSamples = 0;
  56400. }
  56401. }
  56402. }
  56403. function _start () {
  56404. _time = performance.now();
  56405. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  56406. _started = true;
  56407. }
  56408. function _end () {
  56409. _value = performance.now() - _time;
  56410. if( _settings.userTimingAPI ) {
  56411. performance.mark( _id + '-end' );
  56412. if( _started ) {
  56413. performance.measure( _id, _id + '-start', _id + '-end' );
  56414. }
  56415. }
  56416. _average( _value );
  56417. }
  56418. function _tick () {
  56419. _end();
  56420. _start();
  56421. }
  56422. function _draw () {
  56423. var v = ( _def && _def.average ) ? _averageValue : _value;
  56424. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  56425. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  56426. _graph.draw( _value, a );
  56427. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  56428. }
  56429. function _frame () {
  56430. var t = performance.now();
  56431. var e = t - _time;
  56432. _total++;
  56433. if ( e > 1000 ) {
  56434. if ( _def && _def.interpolate === false ) {
  56435. _value = _total;
  56436. } else {
  56437. _value = _total * 1000 / e;
  56438. }
  56439. _total = 0;
  56440. _time = t;
  56441. _average( _value );
  56442. }
  56443. }
  56444. function _set ( v ) {
  56445. _value = v;
  56446. _average( _value );
  56447. }
  56448. return {
  56449. set: _set,
  56450. start: _start,
  56451. tick: _tick,
  56452. end: _end,
  56453. frame: _frame,
  56454. value: function () {
  56455. return _value;
  56456. },
  56457. draw: _draw
  56458. };
  56459. }
  56460. function sample () {
  56461. var _value = 0;
  56462. function _set ( v ) {
  56463. _value = v;
  56464. }
  56465. return {
  56466. set: _set,
  56467. value: function () {
  56468. return _value;
  56469. }
  56470. };
  56471. }
  56472. function _perf ( idArg ) {
  56473. var id = idArg.toLowerCase();
  56474. if ( id === undefined ) id = 'default';
  56475. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  56476. var group = null;
  56477. if ( _settings && _settings.groups ) {
  56478. iterateKeys( _settings.groups, function ( j ) {
  56479. var g = _settings.groups[ parseInt( j, 10 ) ];
  56480. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  56481. group = g;
  56482. }
  56483. } );
  56484. }
  56485. var p = new PerfCounter( id, group );
  56486. _perfCounters[ id ] = p;
  56487. return p;
  56488. }
  56489. function _init () {
  56490. if ( _settings.plugins ) {
  56491. if ( !_settings.values ) _settings.values = {};
  56492. if ( !_settings.groups ) _settings.groups = [];
  56493. if ( !_settings.fractions ) _settings.fractions = [];
  56494. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  56495. _settings.plugins[ j ].attach( _perf );
  56496. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  56497. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  56498. } );
  56499. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  56500. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  56501. }
  56502. } else {
  56503. _settings.plugins = {};
  56504. }
  56505. _base = document.createElement( 'div' );
  56506. _base.className = 'rs-base';
  56507. _div = document.createElement( 'div' );
  56508. _div.className = 'rs-container';
  56509. _div.style.height = 'auto';
  56510. _base.appendChild( _div );
  56511. document.body.appendChild( _base );
  56512. if ( !_settings ) return;
  56513. if ( _settings.groups ) {
  56514. iterateKeys( _settings.groups, function ( j ) {
  56515. var g = _settings.groups[ parseInt( j, 10 ) ];
  56516. var div = document.createElement( 'div' );
  56517. div.className = 'rs-group';
  56518. g.div = div;
  56519. var h1 = document.createElement( 'h1' );
  56520. h1.textContent = g.caption;
  56521. h1.addEventListener( 'click', function ( e ) {
  56522. this.classList.toggle( 'hidden' );
  56523. e.preventDefault();
  56524. }.bind( div ) );
  56525. _div.appendChild( h1 );
  56526. _div.appendChild( div );
  56527. } );
  56528. }
  56529. if ( _settings.fractions ) {
  56530. iterateKeys( _settings.fractions, function ( j ) {
  56531. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56532. var div = document.createElement( 'div' );
  56533. div.className = 'rs-fraction';
  56534. var legend = document.createElement( 'div' );
  56535. legend.className = 'rs-legend';
  56536. var h = 0;
  56537. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56538. var p = document.createElement( 'p' );
  56539. p.textContent = _settings.fractions[ j ].steps[ k ];
  56540. p.style.color = _colours[ h ];
  56541. legend.appendChild( p );
  56542. h++;
  56543. } );
  56544. div.appendChild( legend );
  56545. div.style.height = h * _elHeight + 'px';
  56546. f.div = div;
  56547. var graph = new StackGraph( div, h );
  56548. f.graph = graph;
  56549. _div.appendChild( div );
  56550. } );
  56551. }
  56552. }
  56553. function _update () {
  56554. iterateKeys( _settings.plugins, function ( j ) {
  56555. _settings.plugins[ j ].update();
  56556. } );
  56557. iterateKeys( _perfCounters, function ( j ) {
  56558. _perfCounters[ j ].draw();
  56559. } );
  56560. if ( _settings && _settings.fractions ) {
  56561. iterateKeys( _settings.fractions, function ( j ) {
  56562. var f = _settings.fractions[ parseInt( j, 10 ) ];
  56563. var v = [];
  56564. var base = _perfCounters[ f.base.toLowerCase() ];
  56565. if ( base ) {
  56566. base = base.value();
  56567. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  56568. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  56569. var val = _perfCounters[ s ];
  56570. if ( val ) {
  56571. v.push( val.value() / base );
  56572. }
  56573. } );
  56574. }
  56575. f.graph.draw( v );
  56576. } );
  56577. }
  56578. /*if( _height != _div.clientHeight ) {
  56579. _height = _div.clientHeight;
  56580. _base.style.height = _height + 2 * _elHeight + 'px';
  56581. console.log( _base.clientHeight );
  56582. }*/
  56583. }
  56584. _init();
  56585. return function ( id ) {
  56586. if ( id ) return _perf( id );
  56587. return {
  56588. element: _base,
  56589. update: _update
  56590. };
  56591. };
  56592. }
  56593. if (typeof module === 'object') {
  56594. module.exports = window.rStats;
  56595. }
  56596. },{}],204:[function(_dereq_,module,exports){
  56597. /*
  56598. * Copyright 2015 Google Inc. All Rights Reserved.
  56599. * Licensed under the Apache License, Version 2.0 (the "License");
  56600. * you may not use this file except in compliance with the License.
  56601. * You may obtain a copy of the License at
  56602. *
  56603. * http://www.apache.org/licenses/LICENSE-2.0
  56604. *
  56605. * Unless required by applicable law or agreed to in writing, software
  56606. * distributed under the License is distributed on an "AS IS" BASIS,
  56607. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56608. * See the License for the specific language governing permissions and
  56609. * limitations under the License.
  56610. */
  56611. var Util = {};
  56612. Util.base64 = function(mimeType, base64) {
  56613. return 'data:' + mimeType + ';base64,' + base64;
  56614. };
  56615. Util.isMobile = function() {
  56616. var check = false;
  56617. (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);
  56618. return check;
  56619. };
  56620. Util.isIOS = function() {
  56621. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  56622. };
  56623. Util.isIFrame = function() {
  56624. try {
  56625. return window.self !== window.top;
  56626. } catch (e) {
  56627. return true;
  56628. }
  56629. };
  56630. Util.appendQueryParameter = function(url, key, value) {
  56631. // Determine delimiter based on if the URL already GET parameters in it.
  56632. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  56633. url += delimiter + key + '=' + value;
  56634. return url;
  56635. };
  56636. // From http://goo.gl/4WX3tg
  56637. Util.getQueryParameter = function(name) {
  56638. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  56639. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  56640. results = regex.exec(location.search);
  56641. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  56642. };
  56643. Util.isLandscapeMode = function() {
  56644. return (window.orientation == 90 || window.orientation == -90);
  56645. };
  56646. module.exports = Util;
  56647. },{}],205:[function(_dereq_,module,exports){
  56648. /*
  56649. * Copyright 2015 Google Inc. All Rights Reserved.
  56650. * Licensed under the Apache License, Version 2.0 (the "License");
  56651. * you may not use this file except in compliance with the License.
  56652. * You may obtain a copy of the License at
  56653. *
  56654. * http://www.apache.org/licenses/LICENSE-2.0
  56655. *
  56656. * Unless required by applicable law or agreed to in writing, software
  56657. * distributed under the License is distributed on an "AS IS" BASIS,
  56658. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  56659. * See the License for the specific language governing permissions and
  56660. * limitations under the License.
  56661. */
  56662. var Util = _dereq_('./util.js');
  56663. /**
  56664. * Android and iOS compatible wakelock implementation.
  56665. *
  56666. * Refactored thanks to dkovalev@.
  56667. */
  56668. function AndroidWakeLock() {
  56669. var video = document.createElement('video');
  56670. video.addEventListener('ended', function() {
  56671. video.play();
  56672. });
  56673. this.request = function() {
  56674. if (video.paused) {
  56675. // Base64 version of videos_src/no-sleep-60s.webm.
  56676. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  56677. video.play();
  56678. }
  56679. };
  56680. this.release = function() {
  56681. video.pause();
  56682. video.src = '';
  56683. };
  56684. }
  56685. function iOSWakeLock() {
  56686. var timer = null;
  56687. this.request = function() {
  56688. if (!timer) {
  56689. timer = setInterval(function() {
  56690. window.location.href = '/';
  56691. setTimeout(window.stop, 0);
  56692. }, 15000);
  56693. }
  56694. }
  56695. this.release = function() {
  56696. if (timer) {
  56697. clearInterval(timer);
  56698. timer = null;
  56699. }
  56700. }
  56701. }
  56702. function getWakeLock() {
  56703. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  56704. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  56705. return iOSWakeLock;
  56706. } else {
  56707. return AndroidWakeLock;
  56708. }
  56709. }
  56710. module.exports = getWakeLock();
  56711. },{"./util.js":204}]},{},[172])(172)
  56712. });
  56713. //# sourceMappingURL=aframe-master.js.map