aframe-v0.5.0.js 2.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459
  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. var str = Object.prototype.toString
  3. module.exports = anArray
  4. function anArray(arr) {
  5. return (
  6. arr.BYTES_PER_ELEMENT
  7. && str.call(arr.buffer) === '[object ArrayBuffer]'
  8. || Array.isArray(arr)
  9. )
  10. }
  11. },{}],2:[function(_dereq_,module,exports){
  12. module.exports = function numtype(num, def) {
  13. return typeof num === 'number'
  14. ? num
  15. : (typeof def === 'number' ? def : 0)
  16. }
  17. },{}],3:[function(_dereq_,module,exports){
  18. 'use strict';
  19. // For more information about browser field, check out the browser field at https://github.com/substack/browserify-handbook#browser-field.
  20. module.exports = {
  21. // Create a <link> tag with optional data attributes
  22. createLink: function(href, attributes) {
  23. var head = document.head || document.getElementsByTagName('head')[0];
  24. var link = document.createElement('link');
  25. link.href = href;
  26. link.rel = 'stylesheet';
  27. for (var key in attributes) {
  28. if ( ! attributes.hasOwnProperty(key)) {
  29. continue;
  30. }
  31. var value = attributes[key];
  32. link.setAttribute('data-' + key, value);
  33. }
  34. head.appendChild(link);
  35. },
  36. // Create a <style> tag with optional data attributes
  37. createStyle: function(cssText, attributes) {
  38. var head = document.head || document.getElementsByTagName('head')[0],
  39. style = document.createElement('style');
  40. style.type = 'text/css';
  41. for (var key in attributes) {
  42. if ( ! attributes.hasOwnProperty(key)) {
  43. continue;
  44. }
  45. var value = attributes[key];
  46. style.setAttribute('data-' + key, value);
  47. }
  48. if (style.sheet) { // for jsdom and IE9+
  49. style.innerHTML = cssText;
  50. style.sheet.cssText = cssText;
  51. head.appendChild(style);
  52. } else if (style.styleSheet) { // for IE8 and below
  53. head.appendChild(style);
  54. style.styleSheet.cssText = cssText;
  55. } else { // for Chrome, Firefox, and Safari
  56. style.appendChild(document.createTextNode(cssText));
  57. head.appendChild(style);
  58. }
  59. }
  60. };
  61. },{}],4:[function(_dereq_,module,exports){
  62. (function (global){
  63. /*!
  64. * The buffer module from node.js, for the browser.
  65. *
  66. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  67. * @license MIT
  68. */
  69. /* eslint-disable no-proto */
  70. 'use strict'
  71. var base64 = _dereq_('base64-js')
  72. var ieee754 = _dereq_('ieee754')
  73. var isArray = _dereq_('isarray')
  74. exports.Buffer = Buffer
  75. exports.SlowBuffer = SlowBuffer
  76. exports.INSPECT_MAX_BYTES = 50
  77. /**
  78. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  79. * === true Use Uint8Array implementation (fastest)
  80. * === false Use Object implementation (most compatible, even IE6)
  81. *
  82. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  83. * Opera 11.6+, iOS 4.2+.
  84. *
  85. * Due to various browser bugs, sometimes the Object implementation will be used even
  86. * when the browser supports typed arrays.
  87. *
  88. * Note:
  89. *
  90. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  91. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  92. *
  93. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  94. *
  95. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  96. * incorrect length in some situations.
  97. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  98. * get the Object implementation, which is slower but behaves correctly.
  99. */
  100. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  101. ? global.TYPED_ARRAY_SUPPORT
  102. : typedArraySupport()
  103. /*
  104. * Export kMaxLength after typed array support is determined.
  105. */
  106. exports.kMaxLength = kMaxLength()
  107. function typedArraySupport () {
  108. try {
  109. var arr = new Uint8Array(1)
  110. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  111. return arr.foo() === 42 && // typed array instances can be augmented
  112. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  113. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  114. } catch (e) {
  115. return false
  116. }
  117. }
  118. function kMaxLength () {
  119. return Buffer.TYPED_ARRAY_SUPPORT
  120. ? 0x7fffffff
  121. : 0x3fffffff
  122. }
  123. function createBuffer (that, length) {
  124. if (kMaxLength() < length) {
  125. throw new RangeError('Invalid typed array length')
  126. }
  127. if (Buffer.TYPED_ARRAY_SUPPORT) {
  128. // Return an augmented `Uint8Array` instance, for best performance
  129. that = new Uint8Array(length)
  130. that.__proto__ = Buffer.prototype
  131. } else {
  132. // Fallback: Return an object instance of the Buffer class
  133. if (that === null) {
  134. that = new Buffer(length)
  135. }
  136. that.length = length
  137. }
  138. return that
  139. }
  140. /**
  141. * The Buffer constructor returns instances of `Uint8Array` that have their
  142. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  143. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  144. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  145. * returns a single octet.
  146. *
  147. * The `Uint8Array` prototype remains unmodified.
  148. */
  149. function Buffer (arg, encodingOrOffset, length) {
  150. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  151. return new Buffer(arg, encodingOrOffset, length)
  152. }
  153. // Common case.
  154. if (typeof arg === 'number') {
  155. if (typeof encodingOrOffset === 'string') {
  156. throw new Error(
  157. 'If encoding is specified then the first argument must be a string'
  158. )
  159. }
  160. return allocUnsafe(this, arg)
  161. }
  162. return from(this, arg, encodingOrOffset, length)
  163. }
  164. Buffer.poolSize = 8192 // not used by this implementation
  165. // TODO: Legacy, not needed anymore. Remove in next major version.
  166. Buffer._augment = function (arr) {
  167. arr.__proto__ = Buffer.prototype
  168. return arr
  169. }
  170. function from (that, value, encodingOrOffset, length) {
  171. if (typeof value === 'number') {
  172. throw new TypeError('"value" argument must not be a number')
  173. }
  174. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  175. return fromArrayBuffer(that, value, encodingOrOffset, length)
  176. }
  177. if (typeof value === 'string') {
  178. return fromString(that, value, encodingOrOffset)
  179. }
  180. return fromObject(that, value)
  181. }
  182. /**
  183. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  184. * if value is a number.
  185. * Buffer.from(str[, encoding])
  186. * Buffer.from(array)
  187. * Buffer.from(buffer)
  188. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  189. **/
  190. Buffer.from = function (value, encodingOrOffset, length) {
  191. return from(null, value, encodingOrOffset, length)
  192. }
  193. if (Buffer.TYPED_ARRAY_SUPPORT) {
  194. Buffer.prototype.__proto__ = Uint8Array.prototype
  195. Buffer.__proto__ = Uint8Array
  196. if (typeof Symbol !== 'undefined' && Symbol.species &&
  197. Buffer[Symbol.species] === Buffer) {
  198. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  199. Object.defineProperty(Buffer, Symbol.species, {
  200. value: null,
  201. configurable: true
  202. })
  203. }
  204. }
  205. function assertSize (size) {
  206. if (typeof size !== 'number') {
  207. throw new TypeError('"size" argument must be a number')
  208. } else if (size < 0) {
  209. throw new RangeError('"size" argument must not be negative')
  210. }
  211. }
  212. function alloc (that, size, fill, encoding) {
  213. assertSize(size)
  214. if (size <= 0) {
  215. return createBuffer(that, size)
  216. }
  217. if (fill !== undefined) {
  218. // Only pay attention to encoding if it's a string. This
  219. // prevents accidentally sending in a number that would
  220. // be interpretted as a start offset.
  221. return typeof encoding === 'string'
  222. ? createBuffer(that, size).fill(fill, encoding)
  223. : createBuffer(that, size).fill(fill)
  224. }
  225. return createBuffer(that, size)
  226. }
  227. /**
  228. * Creates a new filled Buffer instance.
  229. * alloc(size[, fill[, encoding]])
  230. **/
  231. Buffer.alloc = function (size, fill, encoding) {
  232. return alloc(null, size, fill, encoding)
  233. }
  234. function allocUnsafe (that, size) {
  235. assertSize(size)
  236. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  237. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  238. for (var i = 0; i < size; ++i) {
  239. that[i] = 0
  240. }
  241. }
  242. return that
  243. }
  244. /**
  245. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  246. * */
  247. Buffer.allocUnsafe = function (size) {
  248. return allocUnsafe(null, size)
  249. }
  250. /**
  251. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  252. */
  253. Buffer.allocUnsafeSlow = function (size) {
  254. return allocUnsafe(null, size)
  255. }
  256. function fromString (that, string, encoding) {
  257. if (typeof encoding !== 'string' || encoding === '') {
  258. encoding = 'utf8'
  259. }
  260. if (!Buffer.isEncoding(encoding)) {
  261. throw new TypeError('"encoding" must be a valid string encoding')
  262. }
  263. var length = byteLength(string, encoding) | 0
  264. that = createBuffer(that, length)
  265. var actual = that.write(string, encoding)
  266. if (actual !== length) {
  267. // Writing a hex string, for example, that contains invalid characters will
  268. // cause everything after the first invalid character to be ignored. (e.g.
  269. // 'abxxcd' will be treated as 'ab')
  270. that = that.slice(0, actual)
  271. }
  272. return that
  273. }
  274. function fromArrayLike (that, array) {
  275. var length = array.length < 0 ? 0 : checked(array.length) | 0
  276. that = createBuffer(that, length)
  277. for (var i = 0; i < length; i += 1) {
  278. that[i] = array[i] & 255
  279. }
  280. return that
  281. }
  282. function fromArrayBuffer (that, array, byteOffset, length) {
  283. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  284. if (byteOffset < 0 || array.byteLength < byteOffset) {
  285. throw new RangeError('\'offset\' is out of bounds')
  286. }
  287. if (array.byteLength < byteOffset + (length || 0)) {
  288. throw new RangeError('\'length\' is out of bounds')
  289. }
  290. if (byteOffset === undefined && length === undefined) {
  291. array = new Uint8Array(array)
  292. } else if (length === undefined) {
  293. array = new Uint8Array(array, byteOffset)
  294. } else {
  295. array = new Uint8Array(array, byteOffset, length)
  296. }
  297. if (Buffer.TYPED_ARRAY_SUPPORT) {
  298. // Return an augmented `Uint8Array` instance, for best performance
  299. that = array
  300. that.__proto__ = Buffer.prototype
  301. } else {
  302. // Fallback: Return an object instance of the Buffer class
  303. that = fromArrayLike(that, array)
  304. }
  305. return that
  306. }
  307. function fromObject (that, obj) {
  308. if (Buffer.isBuffer(obj)) {
  309. var len = checked(obj.length) | 0
  310. that = createBuffer(that, len)
  311. if (that.length === 0) {
  312. return that
  313. }
  314. obj.copy(that, 0, 0, len)
  315. return that
  316. }
  317. if (obj) {
  318. if ((typeof ArrayBuffer !== 'undefined' &&
  319. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  320. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  321. return createBuffer(that, 0)
  322. }
  323. return fromArrayLike(that, obj)
  324. }
  325. if (obj.type === 'Buffer' && isArray(obj.data)) {
  326. return fromArrayLike(that, obj.data)
  327. }
  328. }
  329. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  330. }
  331. function checked (length) {
  332. // Note: cannot use `length < kMaxLength()` here because that fails when
  333. // length is NaN (which is otherwise coerced to zero.)
  334. if (length >= kMaxLength()) {
  335. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  336. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  337. }
  338. return length | 0
  339. }
  340. function SlowBuffer (length) {
  341. if (+length != length) { // eslint-disable-line eqeqeq
  342. length = 0
  343. }
  344. return Buffer.alloc(+length)
  345. }
  346. Buffer.isBuffer = function isBuffer (b) {
  347. return !!(b != null && b._isBuffer)
  348. }
  349. Buffer.compare = function compare (a, b) {
  350. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  351. throw new TypeError('Arguments must be Buffers')
  352. }
  353. if (a === b) return 0
  354. var x = a.length
  355. var y = b.length
  356. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  357. if (a[i] !== b[i]) {
  358. x = a[i]
  359. y = b[i]
  360. break
  361. }
  362. }
  363. if (x < y) return -1
  364. if (y < x) return 1
  365. return 0
  366. }
  367. Buffer.isEncoding = function isEncoding (encoding) {
  368. switch (String(encoding).toLowerCase()) {
  369. case 'hex':
  370. case 'utf8':
  371. case 'utf-8':
  372. case 'ascii':
  373. case 'latin1':
  374. case 'binary':
  375. case 'base64':
  376. case 'ucs2':
  377. case 'ucs-2':
  378. case 'utf16le':
  379. case 'utf-16le':
  380. return true
  381. default:
  382. return false
  383. }
  384. }
  385. Buffer.concat = function concat (list, length) {
  386. if (!isArray(list)) {
  387. throw new TypeError('"list" argument must be an Array of Buffers')
  388. }
  389. if (list.length === 0) {
  390. return Buffer.alloc(0)
  391. }
  392. var i
  393. if (length === undefined) {
  394. length = 0
  395. for (i = 0; i < list.length; ++i) {
  396. length += list[i].length
  397. }
  398. }
  399. var buffer = Buffer.allocUnsafe(length)
  400. var pos = 0
  401. for (i = 0; i < list.length; ++i) {
  402. var buf = list[i]
  403. if (!Buffer.isBuffer(buf)) {
  404. throw new TypeError('"list" argument must be an Array of Buffers')
  405. }
  406. buf.copy(buffer, pos)
  407. pos += buf.length
  408. }
  409. return buffer
  410. }
  411. function byteLength (string, encoding) {
  412. if (Buffer.isBuffer(string)) {
  413. return string.length
  414. }
  415. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  416. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  417. return string.byteLength
  418. }
  419. if (typeof string !== 'string') {
  420. string = '' + string
  421. }
  422. var len = string.length
  423. if (len === 0) return 0
  424. // Use a for loop to avoid recursion
  425. var loweredCase = false
  426. for (;;) {
  427. switch (encoding) {
  428. case 'ascii':
  429. case 'latin1':
  430. case 'binary':
  431. return len
  432. case 'utf8':
  433. case 'utf-8':
  434. case undefined:
  435. return utf8ToBytes(string).length
  436. case 'ucs2':
  437. case 'ucs-2':
  438. case 'utf16le':
  439. case 'utf-16le':
  440. return len * 2
  441. case 'hex':
  442. return len >>> 1
  443. case 'base64':
  444. return base64ToBytes(string).length
  445. default:
  446. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  447. encoding = ('' + encoding).toLowerCase()
  448. loweredCase = true
  449. }
  450. }
  451. }
  452. Buffer.byteLength = byteLength
  453. function slowToString (encoding, start, end) {
  454. var loweredCase = false
  455. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  456. // property of a typed array.
  457. // This behaves neither like String nor Uint8Array in that we set start/end
  458. // to their upper/lower bounds if the value passed is out of range.
  459. // undefined is handled specially as per ECMA-262 6th Edition,
  460. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  461. if (start === undefined || start < 0) {
  462. start = 0
  463. }
  464. // Return early if start > this.length. Done here to prevent potential uint32
  465. // coercion fail below.
  466. if (start > this.length) {
  467. return ''
  468. }
  469. if (end === undefined || end > this.length) {
  470. end = this.length
  471. }
  472. if (end <= 0) {
  473. return ''
  474. }
  475. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  476. end >>>= 0
  477. start >>>= 0
  478. if (end <= start) {
  479. return ''
  480. }
  481. if (!encoding) encoding = 'utf8'
  482. while (true) {
  483. switch (encoding) {
  484. case 'hex':
  485. return hexSlice(this, start, end)
  486. case 'utf8':
  487. case 'utf-8':
  488. return utf8Slice(this, start, end)
  489. case 'ascii':
  490. return asciiSlice(this, start, end)
  491. case 'latin1':
  492. case 'binary':
  493. return latin1Slice(this, start, end)
  494. case 'base64':
  495. return base64Slice(this, start, end)
  496. case 'ucs2':
  497. case 'ucs-2':
  498. case 'utf16le':
  499. case 'utf-16le':
  500. return utf16leSlice(this, start, end)
  501. default:
  502. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  503. encoding = (encoding + '').toLowerCase()
  504. loweredCase = true
  505. }
  506. }
  507. }
  508. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  509. // Buffer instances.
  510. Buffer.prototype._isBuffer = true
  511. function swap (b, n, m) {
  512. var i = b[n]
  513. b[n] = b[m]
  514. b[m] = i
  515. }
  516. Buffer.prototype.swap16 = function swap16 () {
  517. var len = this.length
  518. if (len % 2 !== 0) {
  519. throw new RangeError('Buffer size must be a multiple of 16-bits')
  520. }
  521. for (var i = 0; i < len; i += 2) {
  522. swap(this, i, i + 1)
  523. }
  524. return this
  525. }
  526. Buffer.prototype.swap32 = function swap32 () {
  527. var len = this.length
  528. if (len % 4 !== 0) {
  529. throw new RangeError('Buffer size must be a multiple of 32-bits')
  530. }
  531. for (var i = 0; i < len; i += 4) {
  532. swap(this, i, i + 3)
  533. swap(this, i + 1, i + 2)
  534. }
  535. return this
  536. }
  537. Buffer.prototype.swap64 = function swap64 () {
  538. var len = this.length
  539. if (len % 8 !== 0) {
  540. throw new RangeError('Buffer size must be a multiple of 64-bits')
  541. }
  542. for (var i = 0; i < len; i += 8) {
  543. swap(this, i, i + 7)
  544. swap(this, i + 1, i + 6)
  545. swap(this, i + 2, i + 5)
  546. swap(this, i + 3, i + 4)
  547. }
  548. return this
  549. }
  550. Buffer.prototype.toString = function toString () {
  551. var length = this.length | 0
  552. if (length === 0) return ''
  553. if (arguments.length === 0) return utf8Slice(this, 0, length)
  554. return slowToString.apply(this, arguments)
  555. }
  556. Buffer.prototype.equals = function equals (b) {
  557. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  558. if (this === b) return true
  559. return Buffer.compare(this, b) === 0
  560. }
  561. Buffer.prototype.inspect = function inspect () {
  562. var str = ''
  563. var max = exports.INSPECT_MAX_BYTES
  564. if (this.length > 0) {
  565. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  566. if (this.length > max) str += ' ... '
  567. }
  568. return '<Buffer ' + str + '>'
  569. }
  570. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  571. if (!Buffer.isBuffer(target)) {
  572. throw new TypeError('Argument must be a Buffer')
  573. }
  574. if (start === undefined) {
  575. start = 0
  576. }
  577. if (end === undefined) {
  578. end = target ? target.length : 0
  579. }
  580. if (thisStart === undefined) {
  581. thisStart = 0
  582. }
  583. if (thisEnd === undefined) {
  584. thisEnd = this.length
  585. }
  586. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  587. throw new RangeError('out of range index')
  588. }
  589. if (thisStart >= thisEnd && start >= end) {
  590. return 0
  591. }
  592. if (thisStart >= thisEnd) {
  593. return -1
  594. }
  595. if (start >= end) {
  596. return 1
  597. }
  598. start >>>= 0
  599. end >>>= 0
  600. thisStart >>>= 0
  601. thisEnd >>>= 0
  602. if (this === target) return 0
  603. var x = thisEnd - thisStart
  604. var y = end - start
  605. var len = Math.min(x, y)
  606. var thisCopy = this.slice(thisStart, thisEnd)
  607. var targetCopy = target.slice(start, end)
  608. for (var i = 0; i < len; ++i) {
  609. if (thisCopy[i] !== targetCopy[i]) {
  610. x = thisCopy[i]
  611. y = targetCopy[i]
  612. break
  613. }
  614. }
  615. if (x < y) return -1
  616. if (y < x) return 1
  617. return 0
  618. }
  619. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  620. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  621. //
  622. // Arguments:
  623. // - buffer - a Buffer to search
  624. // - val - a string, Buffer, or number
  625. // - byteOffset - an index into `buffer`; will be clamped to an int32
  626. // - encoding - an optional encoding, relevant is val is a string
  627. // - dir - true for indexOf, false for lastIndexOf
  628. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  629. // Empty buffer means no match
  630. if (buffer.length === 0) return -1
  631. // Normalize byteOffset
  632. if (typeof byteOffset === 'string') {
  633. encoding = byteOffset
  634. byteOffset = 0
  635. } else if (byteOffset > 0x7fffffff) {
  636. byteOffset = 0x7fffffff
  637. } else if (byteOffset < -0x80000000) {
  638. byteOffset = -0x80000000
  639. }
  640. byteOffset = +byteOffset // Coerce to Number.
  641. if (isNaN(byteOffset)) {
  642. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  643. byteOffset = dir ? 0 : (buffer.length - 1)
  644. }
  645. // Normalize byteOffset: negative offsets start from the end of the buffer
  646. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  647. if (byteOffset >= buffer.length) {
  648. if (dir) return -1
  649. else byteOffset = buffer.length - 1
  650. } else if (byteOffset < 0) {
  651. if (dir) byteOffset = 0
  652. else return -1
  653. }
  654. // Normalize val
  655. if (typeof val === 'string') {
  656. val = Buffer.from(val, encoding)
  657. }
  658. // Finally, search either indexOf (if dir is true) or lastIndexOf
  659. if (Buffer.isBuffer(val)) {
  660. // Special case: looking for empty string/buffer always fails
  661. if (val.length === 0) {
  662. return -1
  663. }
  664. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  665. } else if (typeof val === 'number') {
  666. val = val & 0xFF // Search for a byte value [0-255]
  667. if (Buffer.TYPED_ARRAY_SUPPORT &&
  668. typeof Uint8Array.prototype.indexOf === 'function') {
  669. if (dir) {
  670. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  671. } else {
  672. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  673. }
  674. }
  675. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  676. }
  677. throw new TypeError('val must be string, number or Buffer')
  678. }
  679. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  680. var indexSize = 1
  681. var arrLength = arr.length
  682. var valLength = val.length
  683. if (encoding !== undefined) {
  684. encoding = String(encoding).toLowerCase()
  685. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  686. encoding === 'utf16le' || encoding === 'utf-16le') {
  687. if (arr.length < 2 || val.length < 2) {
  688. return -1
  689. }
  690. indexSize = 2
  691. arrLength /= 2
  692. valLength /= 2
  693. byteOffset /= 2
  694. }
  695. }
  696. function read (buf, i) {
  697. if (indexSize === 1) {
  698. return buf[i]
  699. } else {
  700. return buf.readUInt16BE(i * indexSize)
  701. }
  702. }
  703. var i
  704. if (dir) {
  705. var foundIndex = -1
  706. for (i = byteOffset; i < arrLength; i++) {
  707. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  708. if (foundIndex === -1) foundIndex = i
  709. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  710. } else {
  711. if (foundIndex !== -1) i -= i - foundIndex
  712. foundIndex = -1
  713. }
  714. }
  715. } else {
  716. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  717. for (i = byteOffset; i >= 0; i--) {
  718. var found = true
  719. for (var j = 0; j < valLength; j++) {
  720. if (read(arr, i + j) !== read(val, j)) {
  721. found = false
  722. break
  723. }
  724. }
  725. if (found) return i
  726. }
  727. }
  728. return -1
  729. }
  730. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  731. return this.indexOf(val, byteOffset, encoding) !== -1
  732. }
  733. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  734. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  735. }
  736. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  737. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  738. }
  739. function hexWrite (buf, string, offset, length) {
  740. offset = Number(offset) || 0
  741. var remaining = buf.length - offset
  742. if (!length) {
  743. length = remaining
  744. } else {
  745. length = Number(length)
  746. if (length > remaining) {
  747. length = remaining
  748. }
  749. }
  750. // must be an even number of digits
  751. var strLen = string.length
  752. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  753. if (length > strLen / 2) {
  754. length = strLen / 2
  755. }
  756. for (var i = 0; i < length; ++i) {
  757. var parsed = parseInt(string.substr(i * 2, 2), 16)
  758. if (isNaN(parsed)) return i
  759. buf[offset + i] = parsed
  760. }
  761. return i
  762. }
  763. function utf8Write (buf, string, offset, length) {
  764. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  765. }
  766. function asciiWrite (buf, string, offset, length) {
  767. return blitBuffer(asciiToBytes(string), buf, offset, length)
  768. }
  769. function latin1Write (buf, string, offset, length) {
  770. return asciiWrite(buf, string, offset, length)
  771. }
  772. function base64Write (buf, string, offset, length) {
  773. return blitBuffer(base64ToBytes(string), buf, offset, length)
  774. }
  775. function ucs2Write (buf, string, offset, length) {
  776. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  777. }
  778. Buffer.prototype.write = function write (string, offset, length, encoding) {
  779. // Buffer#write(string)
  780. if (offset === undefined) {
  781. encoding = 'utf8'
  782. length = this.length
  783. offset = 0
  784. // Buffer#write(string, encoding)
  785. } else if (length === undefined && typeof offset === 'string') {
  786. encoding = offset
  787. length = this.length
  788. offset = 0
  789. // Buffer#write(string, offset[, length][, encoding])
  790. } else if (isFinite(offset)) {
  791. offset = offset | 0
  792. if (isFinite(length)) {
  793. length = length | 0
  794. if (encoding === undefined) encoding = 'utf8'
  795. } else {
  796. encoding = length
  797. length = undefined
  798. }
  799. // legacy write(string, encoding, offset, length) - remove in v0.13
  800. } else {
  801. throw new Error(
  802. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  803. )
  804. }
  805. var remaining = this.length - offset
  806. if (length === undefined || length > remaining) length = remaining
  807. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  808. throw new RangeError('Attempt to write outside buffer bounds')
  809. }
  810. if (!encoding) encoding = 'utf8'
  811. var loweredCase = false
  812. for (;;) {
  813. switch (encoding) {
  814. case 'hex':
  815. return hexWrite(this, string, offset, length)
  816. case 'utf8':
  817. case 'utf-8':
  818. return utf8Write(this, string, offset, length)
  819. case 'ascii':
  820. return asciiWrite(this, string, offset, length)
  821. case 'latin1':
  822. case 'binary':
  823. return latin1Write(this, string, offset, length)
  824. case 'base64':
  825. // Warning: maxLength not taken into account in base64Write
  826. return base64Write(this, string, offset, length)
  827. case 'ucs2':
  828. case 'ucs-2':
  829. case 'utf16le':
  830. case 'utf-16le':
  831. return ucs2Write(this, string, offset, length)
  832. default:
  833. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  834. encoding = ('' + encoding).toLowerCase()
  835. loweredCase = true
  836. }
  837. }
  838. }
  839. Buffer.prototype.toJSON = function toJSON () {
  840. return {
  841. type: 'Buffer',
  842. data: Array.prototype.slice.call(this._arr || this, 0)
  843. }
  844. }
  845. function base64Slice (buf, start, end) {
  846. if (start === 0 && end === buf.length) {
  847. return base64.fromByteArray(buf)
  848. } else {
  849. return base64.fromByteArray(buf.slice(start, end))
  850. }
  851. }
  852. function utf8Slice (buf, start, end) {
  853. end = Math.min(buf.length, end)
  854. var res = []
  855. var i = start
  856. while (i < end) {
  857. var firstByte = buf[i]
  858. var codePoint = null
  859. var bytesPerSequence = (firstByte > 0xEF) ? 4
  860. : (firstByte > 0xDF) ? 3
  861. : (firstByte > 0xBF) ? 2
  862. : 1
  863. if (i + bytesPerSequence <= end) {
  864. var secondByte, thirdByte, fourthByte, tempCodePoint
  865. switch (bytesPerSequence) {
  866. case 1:
  867. if (firstByte < 0x80) {
  868. codePoint = firstByte
  869. }
  870. break
  871. case 2:
  872. secondByte = buf[i + 1]
  873. if ((secondByte & 0xC0) === 0x80) {
  874. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  875. if (tempCodePoint > 0x7F) {
  876. codePoint = tempCodePoint
  877. }
  878. }
  879. break
  880. case 3:
  881. secondByte = buf[i + 1]
  882. thirdByte = buf[i + 2]
  883. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  884. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  885. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  886. codePoint = tempCodePoint
  887. }
  888. }
  889. break
  890. case 4:
  891. secondByte = buf[i + 1]
  892. thirdByte = buf[i + 2]
  893. fourthByte = buf[i + 3]
  894. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  895. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  896. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  897. codePoint = tempCodePoint
  898. }
  899. }
  900. }
  901. }
  902. if (codePoint === null) {
  903. // we did not generate a valid codePoint so insert a
  904. // replacement char (U+FFFD) and advance only 1 byte
  905. codePoint = 0xFFFD
  906. bytesPerSequence = 1
  907. } else if (codePoint > 0xFFFF) {
  908. // encode to utf16 (surrogate pair dance)
  909. codePoint -= 0x10000
  910. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  911. codePoint = 0xDC00 | codePoint & 0x3FF
  912. }
  913. res.push(codePoint)
  914. i += bytesPerSequence
  915. }
  916. return decodeCodePointsArray(res)
  917. }
  918. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  919. // the lowest limit is Chrome, with 0x10000 args.
  920. // We go 1 magnitude less, for safety
  921. var MAX_ARGUMENTS_LENGTH = 0x1000
  922. function decodeCodePointsArray (codePoints) {
  923. var len = codePoints.length
  924. if (len <= MAX_ARGUMENTS_LENGTH) {
  925. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  926. }
  927. // Decode in chunks to avoid "call stack size exceeded".
  928. var res = ''
  929. var i = 0
  930. while (i < len) {
  931. res += String.fromCharCode.apply(
  932. String,
  933. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  934. )
  935. }
  936. return res
  937. }
  938. function asciiSlice (buf, start, end) {
  939. var ret = ''
  940. end = Math.min(buf.length, end)
  941. for (var i = start; i < end; ++i) {
  942. ret += String.fromCharCode(buf[i] & 0x7F)
  943. }
  944. return ret
  945. }
  946. function latin1Slice (buf, start, end) {
  947. var ret = ''
  948. end = Math.min(buf.length, end)
  949. for (var i = start; i < end; ++i) {
  950. ret += String.fromCharCode(buf[i])
  951. }
  952. return ret
  953. }
  954. function hexSlice (buf, start, end) {
  955. var len = buf.length
  956. if (!start || start < 0) start = 0
  957. if (!end || end < 0 || end > len) end = len
  958. var out = ''
  959. for (var i = start; i < end; ++i) {
  960. out += toHex(buf[i])
  961. }
  962. return out
  963. }
  964. function utf16leSlice (buf, start, end) {
  965. var bytes = buf.slice(start, end)
  966. var res = ''
  967. for (var i = 0; i < bytes.length; i += 2) {
  968. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  969. }
  970. return res
  971. }
  972. Buffer.prototype.slice = function slice (start, end) {
  973. var len = this.length
  974. start = ~~start
  975. end = end === undefined ? len : ~~end
  976. if (start < 0) {
  977. start += len
  978. if (start < 0) start = 0
  979. } else if (start > len) {
  980. start = len
  981. }
  982. if (end < 0) {
  983. end += len
  984. if (end < 0) end = 0
  985. } else if (end > len) {
  986. end = len
  987. }
  988. if (end < start) end = start
  989. var newBuf
  990. if (Buffer.TYPED_ARRAY_SUPPORT) {
  991. newBuf = this.subarray(start, end)
  992. newBuf.__proto__ = Buffer.prototype
  993. } else {
  994. var sliceLen = end - start
  995. newBuf = new Buffer(sliceLen, undefined)
  996. for (var i = 0; i < sliceLen; ++i) {
  997. newBuf[i] = this[i + start]
  998. }
  999. }
  1000. return newBuf
  1001. }
  1002. /*
  1003. * Need to make sure that buffer isn't trying to write out of bounds.
  1004. */
  1005. function checkOffset (offset, ext, length) {
  1006. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  1007. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  1008. }
  1009. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  1010. offset = offset | 0
  1011. byteLength = byteLength | 0
  1012. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1013. var val = this[offset]
  1014. var mul = 1
  1015. var i = 0
  1016. while (++i < byteLength && (mul *= 0x100)) {
  1017. val += this[offset + i] * mul
  1018. }
  1019. return val
  1020. }
  1021. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  1022. offset = offset | 0
  1023. byteLength = byteLength | 0
  1024. if (!noAssert) {
  1025. checkOffset(offset, byteLength, this.length)
  1026. }
  1027. var val = this[offset + --byteLength]
  1028. var mul = 1
  1029. while (byteLength > 0 && (mul *= 0x100)) {
  1030. val += this[offset + --byteLength] * mul
  1031. }
  1032. return val
  1033. }
  1034. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  1035. if (!noAssert) checkOffset(offset, 1, this.length)
  1036. return this[offset]
  1037. }
  1038. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1039. if (!noAssert) checkOffset(offset, 2, this.length)
  1040. return this[offset] | (this[offset + 1] << 8)
  1041. }
  1042. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1043. if (!noAssert) checkOffset(offset, 2, this.length)
  1044. return (this[offset] << 8) | this[offset + 1]
  1045. }
  1046. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1047. if (!noAssert) checkOffset(offset, 4, this.length)
  1048. return ((this[offset]) |
  1049. (this[offset + 1] << 8) |
  1050. (this[offset + 2] << 16)) +
  1051. (this[offset + 3] * 0x1000000)
  1052. }
  1053. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1054. if (!noAssert) checkOffset(offset, 4, this.length)
  1055. return (this[offset] * 0x1000000) +
  1056. ((this[offset + 1] << 16) |
  1057. (this[offset + 2] << 8) |
  1058. this[offset + 3])
  1059. }
  1060. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1061. offset = offset | 0
  1062. byteLength = byteLength | 0
  1063. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1064. var val = this[offset]
  1065. var mul = 1
  1066. var i = 0
  1067. while (++i < byteLength && (mul *= 0x100)) {
  1068. val += this[offset + i] * mul
  1069. }
  1070. mul *= 0x80
  1071. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1072. return val
  1073. }
  1074. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1075. offset = offset | 0
  1076. byteLength = byteLength | 0
  1077. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1078. var i = byteLength
  1079. var mul = 1
  1080. var val = this[offset + --i]
  1081. while (i > 0 && (mul *= 0x100)) {
  1082. val += this[offset + --i] * mul
  1083. }
  1084. mul *= 0x80
  1085. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1086. return val
  1087. }
  1088. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1089. if (!noAssert) checkOffset(offset, 1, this.length)
  1090. if (!(this[offset] & 0x80)) return (this[offset])
  1091. return ((0xff - this[offset] + 1) * -1)
  1092. }
  1093. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1094. if (!noAssert) checkOffset(offset, 2, this.length)
  1095. var val = this[offset] | (this[offset + 1] << 8)
  1096. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1097. }
  1098. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1099. if (!noAssert) checkOffset(offset, 2, this.length)
  1100. var val = this[offset + 1] | (this[offset] << 8)
  1101. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1102. }
  1103. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1104. if (!noAssert) checkOffset(offset, 4, this.length)
  1105. return (this[offset]) |
  1106. (this[offset + 1] << 8) |
  1107. (this[offset + 2] << 16) |
  1108. (this[offset + 3] << 24)
  1109. }
  1110. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1111. if (!noAssert) checkOffset(offset, 4, this.length)
  1112. return (this[offset] << 24) |
  1113. (this[offset + 1] << 16) |
  1114. (this[offset + 2] << 8) |
  1115. (this[offset + 3])
  1116. }
  1117. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1118. if (!noAssert) checkOffset(offset, 4, this.length)
  1119. return ieee754.read(this, offset, true, 23, 4)
  1120. }
  1121. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1122. if (!noAssert) checkOffset(offset, 4, this.length)
  1123. return ieee754.read(this, offset, false, 23, 4)
  1124. }
  1125. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1126. if (!noAssert) checkOffset(offset, 8, this.length)
  1127. return ieee754.read(this, offset, true, 52, 8)
  1128. }
  1129. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1130. if (!noAssert) checkOffset(offset, 8, this.length)
  1131. return ieee754.read(this, offset, false, 52, 8)
  1132. }
  1133. function checkInt (buf, value, offset, ext, max, min) {
  1134. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  1135. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  1136. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1137. }
  1138. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1139. value = +value
  1140. offset = offset | 0
  1141. byteLength = byteLength | 0
  1142. if (!noAssert) {
  1143. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1144. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1145. }
  1146. var mul = 1
  1147. var i = 0
  1148. this[offset] = value & 0xFF
  1149. while (++i < byteLength && (mul *= 0x100)) {
  1150. this[offset + i] = (value / mul) & 0xFF
  1151. }
  1152. return offset + byteLength
  1153. }
  1154. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1155. value = +value
  1156. offset = offset | 0
  1157. byteLength = byteLength | 0
  1158. if (!noAssert) {
  1159. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  1160. checkInt(this, value, offset, byteLength, maxBytes, 0)
  1161. }
  1162. var i = byteLength - 1
  1163. var mul = 1
  1164. this[offset + i] = value & 0xFF
  1165. while (--i >= 0 && (mul *= 0x100)) {
  1166. this[offset + i] = (value / mul) & 0xFF
  1167. }
  1168. return offset + byteLength
  1169. }
  1170. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1171. value = +value
  1172. offset = offset | 0
  1173. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1174. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1175. this[offset] = (value & 0xff)
  1176. return offset + 1
  1177. }
  1178. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1179. if (value < 0) value = 0xffff + value + 1
  1180. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  1181. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1182. (littleEndian ? i : 1 - i) * 8
  1183. }
  1184. }
  1185. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1186. value = +value
  1187. offset = offset | 0
  1188. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1189. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1190. this[offset] = (value & 0xff)
  1191. this[offset + 1] = (value >>> 8)
  1192. } else {
  1193. objectWriteUInt16(this, value, offset, true)
  1194. }
  1195. return offset + 2
  1196. }
  1197. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1198. value = +value
  1199. offset = offset | 0
  1200. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1201. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1202. this[offset] = (value >>> 8)
  1203. this[offset + 1] = (value & 0xff)
  1204. } else {
  1205. objectWriteUInt16(this, value, offset, false)
  1206. }
  1207. return offset + 2
  1208. }
  1209. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1210. if (value < 0) value = 0xffffffff + value + 1
  1211. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  1212. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1213. }
  1214. }
  1215. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1216. value = +value
  1217. offset = offset | 0
  1218. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1219. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1220. this[offset + 3] = (value >>> 24)
  1221. this[offset + 2] = (value >>> 16)
  1222. this[offset + 1] = (value >>> 8)
  1223. this[offset] = (value & 0xff)
  1224. } else {
  1225. objectWriteUInt32(this, value, offset, true)
  1226. }
  1227. return offset + 4
  1228. }
  1229. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1230. value = +value
  1231. offset = offset | 0
  1232. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1233. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1234. this[offset] = (value >>> 24)
  1235. this[offset + 1] = (value >>> 16)
  1236. this[offset + 2] = (value >>> 8)
  1237. this[offset + 3] = (value & 0xff)
  1238. } else {
  1239. objectWriteUInt32(this, value, offset, false)
  1240. }
  1241. return offset + 4
  1242. }
  1243. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1244. value = +value
  1245. offset = offset | 0
  1246. if (!noAssert) {
  1247. var limit = Math.pow(2, 8 * byteLength - 1)
  1248. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1249. }
  1250. var i = 0
  1251. var mul = 1
  1252. var sub = 0
  1253. this[offset] = value & 0xFF
  1254. while (++i < byteLength && (mul *= 0x100)) {
  1255. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  1256. sub = 1
  1257. }
  1258. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1259. }
  1260. return offset + byteLength
  1261. }
  1262. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1263. value = +value
  1264. offset = offset | 0
  1265. if (!noAssert) {
  1266. var limit = Math.pow(2, 8 * byteLength - 1)
  1267. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1268. }
  1269. var i = byteLength - 1
  1270. var mul = 1
  1271. var sub = 0
  1272. this[offset + i] = value & 0xFF
  1273. while (--i >= 0 && (mul *= 0x100)) {
  1274. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  1275. sub = 1
  1276. }
  1277. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1278. }
  1279. return offset + byteLength
  1280. }
  1281. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1282. value = +value
  1283. offset = offset | 0
  1284. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1285. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1286. if (value < 0) value = 0xff + value + 1
  1287. this[offset] = (value & 0xff)
  1288. return offset + 1
  1289. }
  1290. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1291. value = +value
  1292. offset = offset | 0
  1293. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1294. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1295. this[offset] = (value & 0xff)
  1296. this[offset + 1] = (value >>> 8)
  1297. } else {
  1298. objectWriteUInt16(this, value, offset, true)
  1299. }
  1300. return offset + 2
  1301. }
  1302. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1303. value = +value
  1304. offset = offset | 0
  1305. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1306. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1307. this[offset] = (value >>> 8)
  1308. this[offset + 1] = (value & 0xff)
  1309. } else {
  1310. objectWriteUInt16(this, value, offset, false)
  1311. }
  1312. return offset + 2
  1313. }
  1314. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1315. value = +value
  1316. offset = offset | 0
  1317. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1318. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1319. this[offset] = (value & 0xff)
  1320. this[offset + 1] = (value >>> 8)
  1321. this[offset + 2] = (value >>> 16)
  1322. this[offset + 3] = (value >>> 24)
  1323. } else {
  1324. objectWriteUInt32(this, value, offset, true)
  1325. }
  1326. return offset + 4
  1327. }
  1328. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1329. value = +value
  1330. offset = offset | 0
  1331. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1332. if (value < 0) value = 0xffffffff + value + 1
  1333. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1334. this[offset] = (value >>> 24)
  1335. this[offset + 1] = (value >>> 16)
  1336. this[offset + 2] = (value >>> 8)
  1337. this[offset + 3] = (value & 0xff)
  1338. } else {
  1339. objectWriteUInt32(this, value, offset, false)
  1340. }
  1341. return offset + 4
  1342. }
  1343. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1344. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  1345. if (offset < 0) throw new RangeError('Index out of range')
  1346. }
  1347. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1348. if (!noAssert) {
  1349. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1350. }
  1351. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1352. return offset + 4
  1353. }
  1354. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1355. return writeFloat(this, value, offset, true, noAssert)
  1356. }
  1357. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1358. return writeFloat(this, value, offset, false, noAssert)
  1359. }
  1360. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1361. if (!noAssert) {
  1362. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1363. }
  1364. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1365. return offset + 8
  1366. }
  1367. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1368. return writeDouble(this, value, offset, true, noAssert)
  1369. }
  1370. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1371. return writeDouble(this, value, offset, false, noAssert)
  1372. }
  1373. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1374. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1375. if (!start) start = 0
  1376. if (!end && end !== 0) end = this.length
  1377. if (targetStart >= target.length) targetStart = target.length
  1378. if (!targetStart) targetStart = 0
  1379. if (end > 0 && end < start) end = start
  1380. // Copy 0 bytes; we're done
  1381. if (end === start) return 0
  1382. if (target.length === 0 || this.length === 0) return 0
  1383. // Fatal error conditions
  1384. if (targetStart < 0) {
  1385. throw new RangeError('targetStart out of bounds')
  1386. }
  1387. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1388. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1389. // Are we oob?
  1390. if (end > this.length) end = this.length
  1391. if (target.length - targetStart < end - start) {
  1392. end = target.length - targetStart + start
  1393. }
  1394. var len = end - start
  1395. var i
  1396. if (this === target && start < targetStart && targetStart < end) {
  1397. // descending copy from end
  1398. for (i = len - 1; i >= 0; --i) {
  1399. target[i + targetStart] = this[i + start]
  1400. }
  1401. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1402. // ascending copy from start
  1403. for (i = 0; i < len; ++i) {
  1404. target[i + targetStart] = this[i + start]
  1405. }
  1406. } else {
  1407. Uint8Array.prototype.set.call(
  1408. target,
  1409. this.subarray(start, start + len),
  1410. targetStart
  1411. )
  1412. }
  1413. return len
  1414. }
  1415. // Usage:
  1416. // buffer.fill(number[, offset[, end]])
  1417. // buffer.fill(buffer[, offset[, end]])
  1418. // buffer.fill(string[, offset[, end]][, encoding])
  1419. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  1420. // Handle string cases:
  1421. if (typeof val === 'string') {
  1422. if (typeof start === 'string') {
  1423. encoding = start
  1424. start = 0
  1425. end = this.length
  1426. } else if (typeof end === 'string') {
  1427. encoding = end
  1428. end = this.length
  1429. }
  1430. if (val.length === 1) {
  1431. var code = val.charCodeAt(0)
  1432. if (code < 256) {
  1433. val = code
  1434. }
  1435. }
  1436. if (encoding !== undefined && typeof encoding !== 'string') {
  1437. throw new TypeError('encoding must be a string')
  1438. }
  1439. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  1440. throw new TypeError('Unknown encoding: ' + encoding)
  1441. }
  1442. } else if (typeof val === 'number') {
  1443. val = val & 255
  1444. }
  1445. // Invalid ranges are not set to a default, so can range check early.
  1446. if (start < 0 || this.length < start || this.length < end) {
  1447. throw new RangeError('Out of range index')
  1448. }
  1449. if (end <= start) {
  1450. return this
  1451. }
  1452. start = start >>> 0
  1453. end = end === undefined ? this.length : end >>> 0
  1454. if (!val) val = 0
  1455. var i
  1456. if (typeof val === 'number') {
  1457. for (i = start; i < end; ++i) {
  1458. this[i] = val
  1459. }
  1460. } else {
  1461. var bytes = Buffer.isBuffer(val)
  1462. ? val
  1463. : utf8ToBytes(new Buffer(val, encoding).toString())
  1464. var len = bytes.length
  1465. for (i = 0; i < end - start; ++i) {
  1466. this[i + start] = bytes[i % len]
  1467. }
  1468. }
  1469. return this
  1470. }
  1471. // HELPER FUNCTIONS
  1472. // ================
  1473. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1474. function base64clean (str) {
  1475. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1476. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1477. // Node converts strings with length < 2 to ''
  1478. if (str.length < 2) return ''
  1479. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1480. while (str.length % 4 !== 0) {
  1481. str = str + '='
  1482. }
  1483. return str
  1484. }
  1485. function stringtrim (str) {
  1486. if (str.trim) return str.trim()
  1487. return str.replace(/^\s+|\s+$/g, '')
  1488. }
  1489. function toHex (n) {
  1490. if (n < 16) return '0' + n.toString(16)
  1491. return n.toString(16)
  1492. }
  1493. function utf8ToBytes (string, units) {
  1494. units = units || Infinity
  1495. var codePoint
  1496. var length = string.length
  1497. var leadSurrogate = null
  1498. var bytes = []
  1499. for (var i = 0; i < length; ++i) {
  1500. codePoint = string.charCodeAt(i)
  1501. // is surrogate component
  1502. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1503. // last char was a lead
  1504. if (!leadSurrogate) {
  1505. // no lead yet
  1506. if (codePoint > 0xDBFF) {
  1507. // unexpected trail
  1508. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1509. continue
  1510. } else if (i + 1 === length) {
  1511. // unpaired lead
  1512. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1513. continue
  1514. }
  1515. // valid lead
  1516. leadSurrogate = codePoint
  1517. continue
  1518. }
  1519. // 2 leads in a row
  1520. if (codePoint < 0xDC00) {
  1521. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1522. leadSurrogate = codePoint
  1523. continue
  1524. }
  1525. // valid surrogate pair
  1526. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  1527. } else if (leadSurrogate) {
  1528. // valid bmp char, but last char was a lead
  1529. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1530. }
  1531. leadSurrogate = null
  1532. // encode utf8
  1533. if (codePoint < 0x80) {
  1534. if ((units -= 1) < 0) break
  1535. bytes.push(codePoint)
  1536. } else if (codePoint < 0x800) {
  1537. if ((units -= 2) < 0) break
  1538. bytes.push(
  1539. codePoint >> 0x6 | 0xC0,
  1540. codePoint & 0x3F | 0x80
  1541. )
  1542. } else if (codePoint < 0x10000) {
  1543. if ((units -= 3) < 0) break
  1544. bytes.push(
  1545. codePoint >> 0xC | 0xE0,
  1546. codePoint >> 0x6 & 0x3F | 0x80,
  1547. codePoint & 0x3F | 0x80
  1548. )
  1549. } else if (codePoint < 0x110000) {
  1550. if ((units -= 4) < 0) break
  1551. bytes.push(
  1552. codePoint >> 0x12 | 0xF0,
  1553. codePoint >> 0xC & 0x3F | 0x80,
  1554. codePoint >> 0x6 & 0x3F | 0x80,
  1555. codePoint & 0x3F | 0x80
  1556. )
  1557. } else {
  1558. throw new Error('Invalid code point')
  1559. }
  1560. }
  1561. return bytes
  1562. }
  1563. function asciiToBytes (str) {
  1564. var byteArray = []
  1565. for (var i = 0; i < str.length; ++i) {
  1566. // Node's code seems to be doing this and not & 0x7F..
  1567. byteArray.push(str.charCodeAt(i) & 0xFF)
  1568. }
  1569. return byteArray
  1570. }
  1571. function utf16leToBytes (str, units) {
  1572. var c, hi, lo
  1573. var byteArray = []
  1574. for (var i = 0; i < str.length; ++i) {
  1575. if ((units -= 2) < 0) break
  1576. c = str.charCodeAt(i)
  1577. hi = c >> 8
  1578. lo = c % 256
  1579. byteArray.push(lo)
  1580. byteArray.push(hi)
  1581. }
  1582. return byteArray
  1583. }
  1584. function base64ToBytes (str) {
  1585. return base64.toByteArray(base64clean(str))
  1586. }
  1587. function blitBuffer (src, dst, offset, length) {
  1588. for (var i = 0; i < length; ++i) {
  1589. if ((i + offset >= dst.length) || (i >= src.length)) break
  1590. dst[i + offset] = src[i]
  1591. }
  1592. return i
  1593. }
  1594. function isnan (val) {
  1595. return val !== val // eslint-disable-line no-self-compare
  1596. }
  1597. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1598. },{"base64-js":5,"ieee754":6,"isarray":7}],5:[function(_dereq_,module,exports){
  1599. 'use strict'
  1600. exports.byteLength = byteLength
  1601. exports.toByteArray = toByteArray
  1602. exports.fromByteArray = fromByteArray
  1603. var lookup = []
  1604. var revLookup = []
  1605. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  1606. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  1607. for (var i = 0, len = code.length; i < len; ++i) {
  1608. lookup[i] = code[i]
  1609. revLookup[code.charCodeAt(i)] = i
  1610. }
  1611. revLookup['-'.charCodeAt(0)] = 62
  1612. revLookup['_'.charCodeAt(0)] = 63
  1613. function placeHoldersCount (b64) {
  1614. var len = b64.length
  1615. if (len % 4 > 0) {
  1616. throw new Error('Invalid string. Length must be a multiple of 4')
  1617. }
  1618. // the number of equal signs (place holders)
  1619. // if there are two placeholders, than the two characters before it
  1620. // represent one byte
  1621. // if there is only one, then the three characters before it represent 2 bytes
  1622. // this is just a cheap hack to not do indexOf twice
  1623. return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
  1624. }
  1625. function byteLength (b64) {
  1626. // base64 is 4/3 + up to two characters of the original data
  1627. return b64.length * 3 / 4 - placeHoldersCount(b64)
  1628. }
  1629. function toByteArray (b64) {
  1630. var i, j, l, tmp, placeHolders, arr
  1631. var len = b64.length
  1632. placeHolders = placeHoldersCount(b64)
  1633. arr = new Arr(len * 3 / 4 - placeHolders)
  1634. // if there are placeholders, only get up to the last complete 4 chars
  1635. l = placeHolders > 0 ? len - 4 : len
  1636. var L = 0
  1637. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  1638. tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
  1639. arr[L++] = (tmp >> 16) & 0xFF
  1640. arr[L++] = (tmp >> 8) & 0xFF
  1641. arr[L++] = tmp & 0xFF
  1642. }
  1643. if (placeHolders === 2) {
  1644. tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1645. arr[L++] = tmp & 0xFF
  1646. } else if (placeHolders === 1) {
  1647. tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1648. arr[L++] = (tmp >> 8) & 0xFF
  1649. arr[L++] = tmp & 0xFF
  1650. }
  1651. return arr
  1652. }
  1653. function tripletToBase64 (num) {
  1654. return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
  1655. }
  1656. function encodeChunk (uint8, start, end) {
  1657. var tmp
  1658. var output = []
  1659. for (var i = start; i < end; i += 3) {
  1660. tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  1661. output.push(tripletToBase64(tmp))
  1662. }
  1663. return output.join('')
  1664. }
  1665. function fromByteArray (uint8) {
  1666. var tmp
  1667. var len = uint8.length
  1668. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1669. var output = ''
  1670. var parts = []
  1671. var maxChunkLength = 16383 // must be multiple of 3
  1672. // go through the array every three bytes, we'll deal with trailing stuff later
  1673. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1674. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  1675. }
  1676. // pad the end with zeros, but make sure to not forget the extra bytes
  1677. if (extraBytes === 1) {
  1678. tmp = uint8[len - 1]
  1679. output += lookup[tmp >> 2]
  1680. output += lookup[(tmp << 4) & 0x3F]
  1681. output += '=='
  1682. } else if (extraBytes === 2) {
  1683. tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
  1684. output += lookup[tmp >> 10]
  1685. output += lookup[(tmp >> 4) & 0x3F]
  1686. output += lookup[(tmp << 2) & 0x3F]
  1687. output += '='
  1688. }
  1689. parts.push(output)
  1690. return parts.join('')
  1691. }
  1692. },{}],6:[function(_dereq_,module,exports){
  1693. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  1694. var e, m
  1695. var eLen = nBytes * 8 - mLen - 1
  1696. var eMax = (1 << eLen) - 1
  1697. var eBias = eMax >> 1
  1698. var nBits = -7
  1699. var i = isLE ? (nBytes - 1) : 0
  1700. var d = isLE ? -1 : 1
  1701. var s = buffer[offset + i]
  1702. i += d
  1703. e = s & ((1 << (-nBits)) - 1)
  1704. s >>= (-nBits)
  1705. nBits += eLen
  1706. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  1707. m = e & ((1 << (-nBits)) - 1)
  1708. e >>= (-nBits)
  1709. nBits += mLen
  1710. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  1711. if (e === 0) {
  1712. e = 1 - eBias
  1713. } else if (e === eMax) {
  1714. return m ? NaN : ((s ? -1 : 1) * Infinity)
  1715. } else {
  1716. m = m + Math.pow(2, mLen)
  1717. e = e - eBias
  1718. }
  1719. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  1720. }
  1721. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  1722. var e, m, c
  1723. var eLen = nBytes * 8 - mLen - 1
  1724. var eMax = (1 << eLen) - 1
  1725. var eBias = eMax >> 1
  1726. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  1727. var i = isLE ? 0 : (nBytes - 1)
  1728. var d = isLE ? 1 : -1
  1729. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  1730. value = Math.abs(value)
  1731. if (isNaN(value) || value === Infinity) {
  1732. m = isNaN(value) ? 1 : 0
  1733. e = eMax
  1734. } else {
  1735. e = Math.floor(Math.log(value) / Math.LN2)
  1736. if (value * (c = Math.pow(2, -e)) < 1) {
  1737. e--
  1738. c *= 2
  1739. }
  1740. if (e + eBias >= 1) {
  1741. value += rt / c
  1742. } else {
  1743. value += rt * Math.pow(2, 1 - eBias)
  1744. }
  1745. if (value * c >= 2) {
  1746. e++
  1747. c /= 2
  1748. }
  1749. if (e + eBias >= eMax) {
  1750. m = 0
  1751. e = eMax
  1752. } else if (e + eBias >= 1) {
  1753. m = (value * c - 1) * Math.pow(2, mLen)
  1754. e = e + eBias
  1755. } else {
  1756. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  1757. e = 0
  1758. }
  1759. }
  1760. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  1761. e = (e << mLen) | m
  1762. eLen += mLen
  1763. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  1764. buffer[offset + i - d] |= s * 128
  1765. }
  1766. },{}],7:[function(_dereq_,module,exports){
  1767. var toString = {}.toString;
  1768. module.exports = Array.isArray || function (arr) {
  1769. return toString.call(arr) == '[object Array]';
  1770. };
  1771. },{}],8:[function(_dereq_,module,exports){
  1772. (function (process){
  1773. // Copyright Joyent, Inc. and other Node contributors.
  1774. //
  1775. // Permission is hereby granted, free of charge, to any person obtaining a
  1776. // copy of this software and associated documentation files (the
  1777. // "Software"), to deal in the Software without restriction, including
  1778. // without limitation the rights to use, copy, modify, merge, publish,
  1779. // distribute, sublicense, and/or sell copies of the Software, and to permit
  1780. // persons to whom the Software is furnished to do so, subject to the
  1781. // following conditions:
  1782. //
  1783. // The above copyright notice and this permission notice shall be included
  1784. // in all copies or substantial portions of the Software.
  1785. //
  1786. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  1787. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  1788. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  1789. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  1790. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  1791. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  1792. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  1793. // resolves . and .. elements in a path array with directory names there
  1794. // must be no slashes, empty elements, or device names (c:\) in the array
  1795. // (so also no leading and trailing slashes - it does not distinguish
  1796. // relative and absolute paths)
  1797. function normalizeArray(parts, allowAboveRoot) {
  1798. // if the path tries to go above the root, `up` ends up > 0
  1799. var up = 0;
  1800. for (var i = parts.length - 1; i >= 0; i--) {
  1801. var last = parts[i];
  1802. if (last === '.') {
  1803. parts.splice(i, 1);
  1804. } else if (last === '..') {
  1805. parts.splice(i, 1);
  1806. up++;
  1807. } else if (up) {
  1808. parts.splice(i, 1);
  1809. up--;
  1810. }
  1811. }
  1812. // if the path is allowed to go above the root, restore leading ..s
  1813. if (allowAboveRoot) {
  1814. for (; up--; up) {
  1815. parts.unshift('..');
  1816. }
  1817. }
  1818. return parts;
  1819. }
  1820. // Split a filename into [root, dir, basename, ext], unix version
  1821. // 'root' is just a slash, or nothing.
  1822. var splitPathRe =
  1823. /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
  1824. var splitPath = function(filename) {
  1825. return splitPathRe.exec(filename).slice(1);
  1826. };
  1827. // path.resolve([from ...], to)
  1828. // posix version
  1829. exports.resolve = function() {
  1830. var resolvedPath = '',
  1831. resolvedAbsolute = false;
  1832. for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
  1833. var path = (i >= 0) ? arguments[i] : process.cwd();
  1834. // Skip empty and invalid entries
  1835. if (typeof path !== 'string') {
  1836. throw new TypeError('Arguments to path.resolve must be strings');
  1837. } else if (!path) {
  1838. continue;
  1839. }
  1840. resolvedPath = path + '/' + resolvedPath;
  1841. resolvedAbsolute = path.charAt(0) === '/';
  1842. }
  1843. // At this point the path should be resolved to a full absolute path, but
  1844. // handle relative paths to be safe (might happen when process.cwd() fails)
  1845. // Normalize the path
  1846. resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
  1847. return !!p;
  1848. }), !resolvedAbsolute).join('/');
  1849. return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
  1850. };
  1851. // path.normalize(path)
  1852. // posix version
  1853. exports.normalize = function(path) {
  1854. var isAbsolute = exports.isAbsolute(path),
  1855. trailingSlash = substr(path, -1) === '/';
  1856. // Normalize the path
  1857. path = normalizeArray(filter(path.split('/'), function(p) {
  1858. return !!p;
  1859. }), !isAbsolute).join('/');
  1860. if (!path && !isAbsolute) {
  1861. path = '.';
  1862. }
  1863. if (path && trailingSlash) {
  1864. path += '/';
  1865. }
  1866. return (isAbsolute ? '/' : '') + path;
  1867. };
  1868. // posix version
  1869. exports.isAbsolute = function(path) {
  1870. return path.charAt(0) === '/';
  1871. };
  1872. // posix version
  1873. exports.join = function() {
  1874. var paths = Array.prototype.slice.call(arguments, 0);
  1875. return exports.normalize(filter(paths, function(p, index) {
  1876. if (typeof p !== 'string') {
  1877. throw new TypeError('Arguments to path.join must be strings');
  1878. }
  1879. return p;
  1880. }).join('/'));
  1881. };
  1882. // path.relative(from, to)
  1883. // posix version
  1884. exports.relative = function(from, to) {
  1885. from = exports.resolve(from).substr(1);
  1886. to = exports.resolve(to).substr(1);
  1887. function trim(arr) {
  1888. var start = 0;
  1889. for (; start < arr.length; start++) {
  1890. if (arr[start] !== '') break;
  1891. }
  1892. var end = arr.length - 1;
  1893. for (; end >= 0; end--) {
  1894. if (arr[end] !== '') break;
  1895. }
  1896. if (start > end) return [];
  1897. return arr.slice(start, end - start + 1);
  1898. }
  1899. var fromParts = trim(from.split('/'));
  1900. var toParts = trim(to.split('/'));
  1901. var length = Math.min(fromParts.length, toParts.length);
  1902. var samePartsLength = length;
  1903. for (var i = 0; i < length; i++) {
  1904. if (fromParts[i] !== toParts[i]) {
  1905. samePartsLength = i;
  1906. break;
  1907. }
  1908. }
  1909. var outputParts = [];
  1910. for (var i = samePartsLength; i < fromParts.length; i++) {
  1911. outputParts.push('..');
  1912. }
  1913. outputParts = outputParts.concat(toParts.slice(samePartsLength));
  1914. return outputParts.join('/');
  1915. };
  1916. exports.sep = '/';
  1917. exports.delimiter = ':';
  1918. exports.dirname = function(path) {
  1919. var result = splitPath(path),
  1920. root = result[0],
  1921. dir = result[1];
  1922. if (!root && !dir) {
  1923. // No dirname whatsoever
  1924. return '.';
  1925. }
  1926. if (dir) {
  1927. // It has a dirname, strip trailing slash
  1928. dir = dir.substr(0, dir.length - 1);
  1929. }
  1930. return root + dir;
  1931. };
  1932. exports.basename = function(path, ext) {
  1933. var f = splitPath(path)[2];
  1934. // TODO: make this comparison case-insensitive on windows?
  1935. if (ext && f.substr(-1 * ext.length) === ext) {
  1936. f = f.substr(0, f.length - ext.length);
  1937. }
  1938. return f;
  1939. };
  1940. exports.extname = function(path) {
  1941. return splitPath(path)[3];
  1942. };
  1943. function filter (xs, f) {
  1944. if (xs.filter) return xs.filter(f);
  1945. var res = [];
  1946. for (var i = 0; i < xs.length; i++) {
  1947. if (f(xs[i], i, xs)) res.push(xs[i]);
  1948. }
  1949. return res;
  1950. }
  1951. // String.prototype.substr - negative index don't work in IE8
  1952. var substr = 'ab'.substr(-1) === 'b'
  1953. ? function (str, start, len) { return str.substr(start, len) }
  1954. : function (str, start, len) {
  1955. if (start < 0) start = str.length + start;
  1956. return str.substr(start, len);
  1957. }
  1958. ;
  1959. }).call(this,_dereq_('_process'))
  1960. },{"_process":9}],9:[function(_dereq_,module,exports){
  1961. // shim for using process in browser
  1962. var process = module.exports = {};
  1963. // cached from whatever global is present so that test runners that stub it
  1964. // don't break things. But we need to wrap it in a try catch in case it is
  1965. // wrapped in strict mode code which doesn't define any globals. It's inside a
  1966. // function because try/catches deoptimize in certain engines.
  1967. var cachedSetTimeout;
  1968. var cachedClearTimeout;
  1969. function defaultSetTimout() {
  1970. throw new Error('setTimeout has not been defined');
  1971. }
  1972. function defaultClearTimeout () {
  1973. throw new Error('clearTimeout has not been defined');
  1974. }
  1975. (function () {
  1976. try {
  1977. if (typeof setTimeout === 'function') {
  1978. cachedSetTimeout = setTimeout;
  1979. } else {
  1980. cachedSetTimeout = defaultSetTimout;
  1981. }
  1982. } catch (e) {
  1983. cachedSetTimeout = defaultSetTimout;
  1984. }
  1985. try {
  1986. if (typeof clearTimeout === 'function') {
  1987. cachedClearTimeout = clearTimeout;
  1988. } else {
  1989. cachedClearTimeout = defaultClearTimeout;
  1990. }
  1991. } catch (e) {
  1992. cachedClearTimeout = defaultClearTimeout;
  1993. }
  1994. } ())
  1995. function runTimeout(fun) {
  1996. if (cachedSetTimeout === setTimeout) {
  1997. //normal enviroments in sane situations
  1998. return setTimeout(fun, 0);
  1999. }
  2000. // if setTimeout wasn't available but was latter defined
  2001. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  2002. cachedSetTimeout = setTimeout;
  2003. return setTimeout(fun, 0);
  2004. }
  2005. try {
  2006. // when when somebody has screwed with setTimeout but no I.E. maddness
  2007. return cachedSetTimeout(fun, 0);
  2008. } catch(e){
  2009. try {
  2010. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2011. return cachedSetTimeout.call(null, fun, 0);
  2012. } catch(e){
  2013. // 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
  2014. return cachedSetTimeout.call(this, fun, 0);
  2015. }
  2016. }
  2017. }
  2018. function runClearTimeout(marker) {
  2019. if (cachedClearTimeout === clearTimeout) {
  2020. //normal enviroments in sane situations
  2021. return clearTimeout(marker);
  2022. }
  2023. // if clearTimeout wasn't available but was latter defined
  2024. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  2025. cachedClearTimeout = clearTimeout;
  2026. return clearTimeout(marker);
  2027. }
  2028. try {
  2029. // when when somebody has screwed with setTimeout but no I.E. maddness
  2030. return cachedClearTimeout(marker);
  2031. } catch (e){
  2032. try {
  2033. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  2034. return cachedClearTimeout.call(null, marker);
  2035. } catch (e){
  2036. // 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.
  2037. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  2038. return cachedClearTimeout.call(this, marker);
  2039. }
  2040. }
  2041. }
  2042. var queue = [];
  2043. var draining = false;
  2044. var currentQueue;
  2045. var queueIndex = -1;
  2046. function cleanUpNextTick() {
  2047. if (!draining || !currentQueue) {
  2048. return;
  2049. }
  2050. draining = false;
  2051. if (currentQueue.length) {
  2052. queue = currentQueue.concat(queue);
  2053. } else {
  2054. queueIndex = -1;
  2055. }
  2056. if (queue.length) {
  2057. drainQueue();
  2058. }
  2059. }
  2060. function drainQueue() {
  2061. if (draining) {
  2062. return;
  2063. }
  2064. var timeout = runTimeout(cleanUpNextTick);
  2065. draining = true;
  2066. var len = queue.length;
  2067. while(len) {
  2068. currentQueue = queue;
  2069. queue = [];
  2070. while (++queueIndex < len) {
  2071. if (currentQueue) {
  2072. currentQueue[queueIndex].run();
  2073. }
  2074. }
  2075. queueIndex = -1;
  2076. len = queue.length;
  2077. }
  2078. currentQueue = null;
  2079. draining = false;
  2080. runClearTimeout(timeout);
  2081. }
  2082. process.nextTick = function (fun) {
  2083. var args = new Array(arguments.length - 1);
  2084. if (arguments.length > 1) {
  2085. for (var i = 1; i < arguments.length; i++) {
  2086. args[i - 1] = arguments[i];
  2087. }
  2088. }
  2089. queue.push(new Item(fun, args));
  2090. if (queue.length === 1 && !draining) {
  2091. runTimeout(drainQueue);
  2092. }
  2093. };
  2094. // v8 likes predictible objects
  2095. function Item(fun, array) {
  2096. this.fun = fun;
  2097. this.array = array;
  2098. }
  2099. Item.prototype.run = function () {
  2100. this.fun.apply(null, this.array);
  2101. };
  2102. process.title = 'browser';
  2103. process.browser = true;
  2104. process.env = {};
  2105. process.argv = [];
  2106. process.version = ''; // empty string to avoid regexp issues
  2107. process.versions = {};
  2108. function noop() {}
  2109. process.on = noop;
  2110. process.addListener = noop;
  2111. process.once = noop;
  2112. process.off = noop;
  2113. process.removeListener = noop;
  2114. process.removeAllListeners = noop;
  2115. process.emit = noop;
  2116. process.binding = function (name) {
  2117. throw new Error('process.binding is not supported');
  2118. };
  2119. process.cwd = function () { return '/' };
  2120. process.chdir = function (dir) {
  2121. throw new Error('process.chdir is not supported');
  2122. };
  2123. process.umask = function() { return 0; };
  2124. },{}],10:[function(_dereq_,module,exports){
  2125. var Buffer = _dereq_('buffer').Buffer; // for use with browserify
  2126. module.exports = function (a, b) {
  2127. if (!Buffer.isBuffer(a)) return undefined;
  2128. if (!Buffer.isBuffer(b)) return undefined;
  2129. if (typeof a.equals === 'function') return a.equals(b);
  2130. if (a.length !== b.length) return false;
  2131. for (var i = 0; i < a.length; i++) {
  2132. if (a[i] !== b[i]) return false;
  2133. }
  2134. return true;
  2135. };
  2136. },{"buffer":4}],11:[function(_dereq_,module,exports){
  2137. (function (process){
  2138. /**
  2139. * This is the web browser implementation of `debug()`.
  2140. *
  2141. * Expose `debug()` as the module.
  2142. */
  2143. exports = module.exports = _dereq_('./debug');
  2144. exports.log = log;
  2145. exports.formatArgs = formatArgs;
  2146. exports.save = save;
  2147. exports.load = load;
  2148. exports.useColors = useColors;
  2149. exports.storage = 'undefined' != typeof chrome
  2150. && 'undefined' != typeof chrome.storage
  2151. ? chrome.storage.local
  2152. : localstorage();
  2153. /**
  2154. * Colors.
  2155. */
  2156. exports.colors = [
  2157. 'lightseagreen',
  2158. 'forestgreen',
  2159. 'goldenrod',
  2160. 'dodgerblue',
  2161. 'darkorchid',
  2162. 'crimson'
  2163. ];
  2164. /**
  2165. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  2166. * and the Firebug extension (any Firefox version) are known
  2167. * to support "%c" CSS customizations.
  2168. *
  2169. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  2170. */
  2171. function useColors() {
  2172. // is webkit? http://stackoverflow.com/a/16459606/376773
  2173. // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  2174. return (typeof document !== 'undefined' && 'WebkitAppearance' in document.documentElement.style) ||
  2175. // is firebug? http://stackoverflow.com/a/398120/376773
  2176. (window.console && (console.firebug || (console.exception && console.table))) ||
  2177. // is firefox >= v31?
  2178. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  2179. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  2180. }
  2181. /**
  2182. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  2183. */
  2184. exports.formatters.j = function(v) {
  2185. try {
  2186. return JSON.stringify(v);
  2187. } catch (err) {
  2188. return '[UnexpectedJSONParseError]: ' + err.message;
  2189. }
  2190. };
  2191. /**
  2192. * Colorize log arguments if enabled.
  2193. *
  2194. * @api public
  2195. */
  2196. function formatArgs() {
  2197. var args = arguments;
  2198. var useColors = this.useColors;
  2199. args[0] = (useColors ? '%c' : '')
  2200. + this.namespace
  2201. + (useColors ? ' %c' : ' ')
  2202. + args[0]
  2203. + (useColors ? '%c ' : ' ')
  2204. + '+' + exports.humanize(this.diff);
  2205. if (!useColors) return args;
  2206. var c = 'color: ' + this.color;
  2207. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  2208. // the final "%c" is somewhat tricky, because there could be other
  2209. // arguments passed either before or after the %c, so we need to
  2210. // figure out the correct index to insert the CSS into
  2211. var index = 0;
  2212. var lastC = 0;
  2213. args[0].replace(/%[a-z%]/g, function(match) {
  2214. if ('%%' === match) return;
  2215. index++;
  2216. if ('%c' === match) {
  2217. // we only are interested in the *last* %c
  2218. // (the user may have provided their own)
  2219. lastC = index;
  2220. }
  2221. });
  2222. args.splice(lastC, 0, c);
  2223. return args;
  2224. }
  2225. /**
  2226. * Invokes `console.log()` when available.
  2227. * No-op when `console.log` is not a "function".
  2228. *
  2229. * @api public
  2230. */
  2231. function log() {
  2232. // this hackery is required for IE8/9, where
  2233. // the `console.log` function doesn't have 'apply'
  2234. return 'object' === typeof console
  2235. && console.log
  2236. && Function.prototype.apply.call(console.log, console, arguments);
  2237. }
  2238. /**
  2239. * Save `namespaces`.
  2240. *
  2241. * @param {String} namespaces
  2242. * @api private
  2243. */
  2244. function save(namespaces) {
  2245. try {
  2246. if (null == namespaces) {
  2247. exports.storage.removeItem('debug');
  2248. } else {
  2249. exports.storage.debug = namespaces;
  2250. }
  2251. } catch(e) {}
  2252. }
  2253. /**
  2254. * Load `namespaces`.
  2255. *
  2256. * @return {String} returns the previously persisted debug modes
  2257. * @api private
  2258. */
  2259. function load() {
  2260. var r;
  2261. try {
  2262. return exports.storage.debug;
  2263. } catch(e) {}
  2264. // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  2265. if (typeof process !== 'undefined' && 'env' in process) {
  2266. return process.env.DEBUG;
  2267. }
  2268. }
  2269. /**
  2270. * Enable namespaces listed in `localStorage.debug` initially.
  2271. */
  2272. exports.enable(load());
  2273. /**
  2274. * Localstorage attempts to return the localstorage.
  2275. *
  2276. * This is necessary because safari throws
  2277. * when a user disables cookies/localstorage
  2278. * and you attempt to access it.
  2279. *
  2280. * @return {LocalStorage}
  2281. * @api private
  2282. */
  2283. function localstorage(){
  2284. try {
  2285. return window.localStorage;
  2286. } catch (e) {}
  2287. }
  2288. }).call(this,_dereq_('_process'))
  2289. },{"./debug":12,"_process":9}],12:[function(_dereq_,module,exports){
  2290. /**
  2291. * This is the common logic for both the Node.js and web browser
  2292. * implementations of `debug()`.
  2293. *
  2294. * Expose `debug()` as the module.
  2295. */
  2296. exports = module.exports = debug.debug = debug;
  2297. exports.coerce = coerce;
  2298. exports.disable = disable;
  2299. exports.enable = enable;
  2300. exports.enabled = enabled;
  2301. exports.humanize = _dereq_('ms');
  2302. /**
  2303. * The currently active debug mode names, and names to skip.
  2304. */
  2305. exports.names = [];
  2306. exports.skips = [];
  2307. /**
  2308. * Map of special "%n" handling functions, for the debug "format" argument.
  2309. *
  2310. * Valid key names are a single, lowercased letter, i.e. "n".
  2311. */
  2312. exports.formatters = {};
  2313. /**
  2314. * Previously assigned color.
  2315. */
  2316. var prevColor = 0;
  2317. /**
  2318. * Previous log timestamp.
  2319. */
  2320. var prevTime;
  2321. /**
  2322. * Select a color.
  2323. *
  2324. * @return {Number}
  2325. * @api private
  2326. */
  2327. function selectColor() {
  2328. return exports.colors[prevColor++ % exports.colors.length];
  2329. }
  2330. /**
  2331. * Create a debugger with the given `namespace`.
  2332. *
  2333. * @param {String} namespace
  2334. * @return {Function}
  2335. * @api public
  2336. */
  2337. function debug(namespace) {
  2338. // define the `disabled` version
  2339. function disabled() {
  2340. }
  2341. disabled.enabled = false;
  2342. // define the `enabled` version
  2343. function enabled() {
  2344. var self = enabled;
  2345. // set `diff` timestamp
  2346. var curr = +new Date();
  2347. var ms = curr - (prevTime || curr);
  2348. self.diff = ms;
  2349. self.prev = prevTime;
  2350. self.curr = curr;
  2351. prevTime = curr;
  2352. // add the `color` if not set
  2353. if (null == self.useColors) self.useColors = exports.useColors();
  2354. if (null == self.color && self.useColors) self.color = selectColor();
  2355. var args = new Array(arguments.length);
  2356. for (var i = 0; i < args.length; i++) {
  2357. args[i] = arguments[i];
  2358. }
  2359. args[0] = exports.coerce(args[0]);
  2360. if ('string' !== typeof args[0]) {
  2361. // anything else let's inspect with %o
  2362. args = ['%o'].concat(args);
  2363. }
  2364. // apply any `formatters` transformations
  2365. var index = 0;
  2366. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  2367. // if we encounter an escaped % then don't increase the array index
  2368. if (match === '%%') return match;
  2369. index++;
  2370. var formatter = exports.formatters[format];
  2371. if ('function' === typeof formatter) {
  2372. var val = args[index];
  2373. match = formatter.call(self, val);
  2374. // now we need to remove `args[index]` since it's inlined in the `format`
  2375. args.splice(index, 1);
  2376. index--;
  2377. }
  2378. return match;
  2379. });
  2380. // apply env-specific formatting
  2381. args = exports.formatArgs.apply(self, args);
  2382. var logFn = enabled.log || exports.log || console.log.bind(console);
  2383. logFn.apply(self, args);
  2384. }
  2385. enabled.enabled = true;
  2386. var fn = exports.enabled(namespace) ? enabled : disabled;
  2387. fn.namespace = namespace;
  2388. return fn;
  2389. }
  2390. /**
  2391. * Enables a debug mode by namespaces. This can include modes
  2392. * separated by a colon and wildcards.
  2393. *
  2394. * @param {String} namespaces
  2395. * @api public
  2396. */
  2397. function enable(namespaces) {
  2398. exports.save(namespaces);
  2399. var split = (namespaces || '').split(/[\s,]+/);
  2400. var len = split.length;
  2401. for (var i = 0; i < len; i++) {
  2402. if (!split[i]) continue; // ignore empty strings
  2403. namespaces = split[i].replace(/[\\^$+?.()|[\]{}]/g, '\\$&').replace(/\*/g, '.*?');
  2404. if (namespaces[0] === '-') {
  2405. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  2406. } else {
  2407. exports.names.push(new RegExp('^' + namespaces + '$'));
  2408. }
  2409. }
  2410. }
  2411. /**
  2412. * Disable debug output.
  2413. *
  2414. * @api public
  2415. */
  2416. function disable() {
  2417. exports.enable('');
  2418. }
  2419. /**
  2420. * Returns true if the given mode name is enabled, false otherwise.
  2421. *
  2422. * @param {String} name
  2423. * @return {Boolean}
  2424. * @api public
  2425. */
  2426. function enabled(name) {
  2427. var i, len;
  2428. for (i = 0, len = exports.skips.length; i < len; i++) {
  2429. if (exports.skips[i].test(name)) {
  2430. return false;
  2431. }
  2432. }
  2433. for (i = 0, len = exports.names.length; i < len; i++) {
  2434. if (exports.names[i].test(name)) {
  2435. return true;
  2436. }
  2437. }
  2438. return false;
  2439. }
  2440. /**
  2441. * Coerce `val`.
  2442. *
  2443. * @param {Mixed} val
  2444. * @return {Mixed}
  2445. * @api private
  2446. */
  2447. function coerce(val) {
  2448. if (val instanceof Error) return val.stack || val.message;
  2449. return val;
  2450. }
  2451. },{"ms":13}],13:[function(_dereq_,module,exports){
  2452. /**
  2453. * Helpers.
  2454. */
  2455. var s = 1000
  2456. var m = s * 60
  2457. var h = m * 60
  2458. var d = h * 24
  2459. var y = d * 365.25
  2460. /**
  2461. * Parse or format the given `val`.
  2462. *
  2463. * Options:
  2464. *
  2465. * - `long` verbose formatting [false]
  2466. *
  2467. * @param {String|Number} val
  2468. * @param {Object} options
  2469. * @throws {Error} throw an error if val is not a non-empty string or a number
  2470. * @return {String|Number}
  2471. * @api public
  2472. */
  2473. module.exports = function (val, options) {
  2474. options = options || {}
  2475. var type = typeof val
  2476. if (type === 'string' && val.length > 0) {
  2477. return parse(val)
  2478. } else if (type === 'number' && isNaN(val) === false) {
  2479. return options.long ?
  2480. fmtLong(val) :
  2481. fmtShort(val)
  2482. }
  2483. throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val))
  2484. }
  2485. /**
  2486. * Parse the given `str` and return milliseconds.
  2487. *
  2488. * @param {String} str
  2489. * @return {Number}
  2490. * @api private
  2491. */
  2492. function parse(str) {
  2493. str = String(str)
  2494. if (str.length > 10000) {
  2495. return
  2496. }
  2497. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str)
  2498. if (!match) {
  2499. return
  2500. }
  2501. var n = parseFloat(match[1])
  2502. var type = (match[2] || 'ms').toLowerCase()
  2503. switch (type) {
  2504. case 'years':
  2505. case 'year':
  2506. case 'yrs':
  2507. case 'yr':
  2508. case 'y':
  2509. return n * y
  2510. case 'days':
  2511. case 'day':
  2512. case 'd':
  2513. return n * d
  2514. case 'hours':
  2515. case 'hour':
  2516. case 'hrs':
  2517. case 'hr':
  2518. case 'h':
  2519. return n * h
  2520. case 'minutes':
  2521. case 'minute':
  2522. case 'mins':
  2523. case 'min':
  2524. case 'm':
  2525. return n * m
  2526. case 'seconds':
  2527. case 'second':
  2528. case 'secs':
  2529. case 'sec':
  2530. case 's':
  2531. return n * s
  2532. case 'milliseconds':
  2533. case 'millisecond':
  2534. case 'msecs':
  2535. case 'msec':
  2536. case 'ms':
  2537. return n
  2538. default:
  2539. return undefined
  2540. }
  2541. }
  2542. /**
  2543. * Short format for `ms`.
  2544. *
  2545. * @param {Number} ms
  2546. * @return {String}
  2547. * @api private
  2548. */
  2549. function fmtShort(ms) {
  2550. if (ms >= d) {
  2551. return Math.round(ms / d) + 'd'
  2552. }
  2553. if (ms >= h) {
  2554. return Math.round(ms / h) + 'h'
  2555. }
  2556. if (ms >= m) {
  2557. return Math.round(ms / m) + 'm'
  2558. }
  2559. if (ms >= s) {
  2560. return Math.round(ms / s) + 's'
  2561. }
  2562. return ms + 'ms'
  2563. }
  2564. /**
  2565. * Long format for `ms`.
  2566. *
  2567. * @param {Number} ms
  2568. * @return {String}
  2569. * @api private
  2570. */
  2571. function fmtLong(ms) {
  2572. return plural(ms, d, 'day') ||
  2573. plural(ms, h, 'hour') ||
  2574. plural(ms, m, 'minute') ||
  2575. plural(ms, s, 'second') ||
  2576. ms + ' ms'
  2577. }
  2578. /**
  2579. * Pluralization helper.
  2580. */
  2581. function plural(ms, n, name) {
  2582. if (ms < n) {
  2583. return
  2584. }
  2585. if (ms < n * 1.5) {
  2586. return Math.floor(ms / n) + ' ' + name
  2587. }
  2588. return Math.ceil(ms / n) + ' ' + name + 's'
  2589. }
  2590. },{}],14:[function(_dereq_,module,exports){
  2591. 'use strict';
  2592. var isObj = _dereq_('is-obj');
  2593. var hasOwnProperty = Object.prototype.hasOwnProperty;
  2594. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  2595. function toObject(val) {
  2596. if (val === null || val === undefined) {
  2597. throw new TypeError('Sources cannot be null or undefined');
  2598. }
  2599. return Object(val);
  2600. }
  2601. function assignKey(to, from, key) {
  2602. var val = from[key];
  2603. if (val === undefined || val === null) {
  2604. return;
  2605. }
  2606. if (hasOwnProperty.call(to, key)) {
  2607. if (to[key] === undefined || to[key] === null) {
  2608. throw new TypeError('Cannot convert undefined or null to object (' + key + ')');
  2609. }
  2610. }
  2611. if (!hasOwnProperty.call(to, key) || !isObj(val)) {
  2612. to[key] = val;
  2613. } else {
  2614. to[key] = assign(Object(to[key]), from[key]);
  2615. }
  2616. }
  2617. function assign(to, from) {
  2618. if (to === from) {
  2619. return to;
  2620. }
  2621. from = Object(from);
  2622. for (var key in from) {
  2623. if (hasOwnProperty.call(from, key)) {
  2624. assignKey(to, from, key);
  2625. }
  2626. }
  2627. if (Object.getOwnPropertySymbols) {
  2628. var symbols = Object.getOwnPropertySymbols(from);
  2629. for (var i = 0; i < symbols.length; i++) {
  2630. if (propIsEnumerable.call(from, symbols[i])) {
  2631. assignKey(to, from, symbols[i]);
  2632. }
  2633. }
  2634. }
  2635. return to;
  2636. }
  2637. module.exports = function deepAssign(target) {
  2638. target = toObject(target);
  2639. for (var s = 1; s < arguments.length; s++) {
  2640. assign(target, arguments[s]);
  2641. }
  2642. return target;
  2643. };
  2644. },{"is-obj":15}],15:[function(_dereq_,module,exports){
  2645. 'use strict';
  2646. module.exports = function (x) {
  2647. var type = typeof x;
  2648. return x !== null && (type === 'object' || type === 'function');
  2649. };
  2650. },{}],16:[function(_dereq_,module,exports){
  2651. /*! (C) WebReflection Mit Style License */
  2652. (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");
  2653. },{}],17:[function(_dereq_,module,exports){
  2654. module.exports = function(dtype) {
  2655. switch (dtype) {
  2656. case 'int8':
  2657. return Int8Array
  2658. case 'int16':
  2659. return Int16Array
  2660. case 'int32':
  2661. return Int32Array
  2662. case 'uint8':
  2663. return Uint8Array
  2664. case 'uint16':
  2665. return Uint16Array
  2666. case 'uint32':
  2667. return Uint32Array
  2668. case 'float32':
  2669. return Float32Array
  2670. case 'float64':
  2671. return Float64Array
  2672. case 'array':
  2673. return Array
  2674. case 'uint8_clamped':
  2675. return Uint8ClampedArray
  2676. }
  2677. }
  2678. },{}],18:[function(_dereq_,module,exports){
  2679. /*eslint new-cap:0*/
  2680. var dtype = _dereq_('dtype')
  2681. module.exports = flattenVertexData
  2682. function flattenVertexData (data, output, offset) {
  2683. if (!data) throw new TypeError('must specify data as first parameter')
  2684. offset = +(offset || 0) | 0
  2685. if (Array.isArray(data) && Array.isArray(data[0])) {
  2686. var dim = data[0].length
  2687. var length = data.length * dim
  2688. // no output specified, create a new typed array
  2689. if (!output || typeof output === 'string') {
  2690. output = new (dtype(output || 'float32'))(length + offset)
  2691. }
  2692. var dstLength = output.length - offset
  2693. if (length !== dstLength) {
  2694. throw new Error('source length ' + length + ' (' + dim + 'x' + data.length + ')' +
  2695. ' does not match destination length ' + dstLength)
  2696. }
  2697. for (var i = 0, k = offset; i < data.length; i++) {
  2698. for (var j = 0; j < dim; j++) {
  2699. output[k++] = data[i][j]
  2700. }
  2701. }
  2702. } else {
  2703. if (!output || typeof output === 'string') {
  2704. // no output, create a new one
  2705. var Ctor = dtype(output || 'float32')
  2706. if (offset === 0) {
  2707. output = new Ctor(data)
  2708. } else {
  2709. output = new Ctor(data.length + offset)
  2710. output.set(data, offset)
  2711. }
  2712. } else {
  2713. // store output in existing array
  2714. output.set(data, offset)
  2715. }
  2716. }
  2717. return output
  2718. }
  2719. },{"dtype":17}],19:[function(_dereq_,module,exports){
  2720. var isFunction = _dereq_('is-function')
  2721. module.exports = forEach
  2722. var toString = Object.prototype.toString
  2723. var hasOwnProperty = Object.prototype.hasOwnProperty
  2724. function forEach(list, iterator, context) {
  2725. if (!isFunction(iterator)) {
  2726. throw new TypeError('iterator must be a function')
  2727. }
  2728. if (arguments.length < 3) {
  2729. context = this
  2730. }
  2731. if (toString.call(list) === '[object Array]')
  2732. forEachArray(list, iterator, context)
  2733. else if (typeof list === 'string')
  2734. forEachString(list, iterator, context)
  2735. else
  2736. forEachObject(list, iterator, context)
  2737. }
  2738. function forEachArray(array, iterator, context) {
  2739. for (var i = 0, len = array.length; i < len; i++) {
  2740. if (hasOwnProperty.call(array, i)) {
  2741. iterator.call(context, array[i], i, array)
  2742. }
  2743. }
  2744. }
  2745. function forEachString(string, iterator, context) {
  2746. for (var i = 0, len = string.length; i < len; i++) {
  2747. // no such thing as a sparse string.
  2748. iterator.call(context, string.charAt(i), i, string)
  2749. }
  2750. }
  2751. function forEachObject(object, iterator, context) {
  2752. for (var k in object) {
  2753. if (hasOwnProperty.call(object, k)) {
  2754. iterator.call(context, object[k], k, object)
  2755. }
  2756. }
  2757. }
  2758. },{"is-function":24}],20:[function(_dereq_,module,exports){
  2759. (function (global){
  2760. if (typeof window !== "undefined") {
  2761. module.exports = window;
  2762. } else if (typeof global !== "undefined") {
  2763. module.exports = global;
  2764. } else if (typeof self !== "undefined"){
  2765. module.exports = self;
  2766. } else {
  2767. module.exports = {};
  2768. }
  2769. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  2770. },{}],21:[function(_dereq_,module,exports){
  2771. module.exports = function compile(property) {
  2772. if (!property || typeof property !== 'string')
  2773. throw new Error('must specify property for indexof search')
  2774. return new Function('array', 'value', 'start', [
  2775. 'start = start || 0',
  2776. 'for (var i=start; i<array.length; i++)',
  2777. ' if (array[i]["' + property +'"] === value)',
  2778. ' return i',
  2779. 'return -1'
  2780. ].join('\n'))
  2781. }
  2782. },{}],22:[function(_dereq_,module,exports){
  2783. if (typeof Object.create === 'function') {
  2784. // implementation from standard node.js 'util' module
  2785. module.exports = function inherits(ctor, superCtor) {
  2786. ctor.super_ = superCtor
  2787. ctor.prototype = Object.create(superCtor.prototype, {
  2788. constructor: {
  2789. value: ctor,
  2790. enumerable: false,
  2791. writable: true,
  2792. configurable: true
  2793. }
  2794. });
  2795. };
  2796. } else {
  2797. // old school shim for old browsers
  2798. module.exports = function inherits(ctor, superCtor) {
  2799. ctor.super_ = superCtor
  2800. var TempCtor = function () {}
  2801. TempCtor.prototype = superCtor.prototype
  2802. ctor.prototype = new TempCtor()
  2803. ctor.prototype.constructor = ctor
  2804. }
  2805. }
  2806. },{}],23:[function(_dereq_,module,exports){
  2807. /*!
  2808. * Determine if an object is a Buffer
  2809. *
  2810. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  2811. * @license MIT
  2812. */
  2813. // The _isBuffer check is for Safari 5-7 support, because it's missing
  2814. // Object.prototype.constructor. Remove this eventually
  2815. module.exports = function (obj) {
  2816. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  2817. }
  2818. function isBuffer (obj) {
  2819. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  2820. }
  2821. // For Node v0.10 support. Remove this eventually.
  2822. function isSlowBuffer (obj) {
  2823. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  2824. }
  2825. },{}],24:[function(_dereq_,module,exports){
  2826. module.exports = isFunction
  2827. var toString = Object.prototype.toString
  2828. function isFunction (fn) {
  2829. var string = toString.call(fn)
  2830. return string === '[object Function]' ||
  2831. (typeof fn === 'function' && string !== '[object RegExp]') ||
  2832. (typeof window !== 'undefined' &&
  2833. // IE8 and below
  2834. (fn === window.setTimeout ||
  2835. fn === window.alert ||
  2836. fn === window.confirm ||
  2837. fn === window.prompt))
  2838. };
  2839. },{}],25:[function(_dereq_,module,exports){
  2840. var wordWrap = _dereq_('word-wrapper')
  2841. var xtend = _dereq_('xtend')
  2842. var findChar = _dereq_('indexof-property')('id')
  2843. var number = _dereq_('as-number')
  2844. var X_HEIGHTS = ['x', 'e', 'a', 'o', 'n', 's', 'r', 'c', 'u', 'm', 'v', 'w', 'z']
  2845. var M_WIDTHS = ['m', 'w']
  2846. var CAP_HEIGHTS = ['H', 'I', 'N', 'E', 'F', 'K', 'L', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  2847. var TAB_ID = '\t'.charCodeAt(0)
  2848. var SPACE_ID = ' '.charCodeAt(0)
  2849. var ALIGN_LEFT = 0,
  2850. ALIGN_CENTER = 1,
  2851. ALIGN_RIGHT = 2
  2852. module.exports = function createLayout(opt) {
  2853. return new TextLayout(opt)
  2854. }
  2855. function TextLayout(opt) {
  2856. this.glyphs = []
  2857. this._measure = this.computeMetrics.bind(this)
  2858. this.update(opt)
  2859. }
  2860. TextLayout.prototype.update = function(opt) {
  2861. opt = xtend({
  2862. measure: this._measure
  2863. }, opt)
  2864. this._opt = opt
  2865. this._opt.tabSize = number(this._opt.tabSize, 4)
  2866. if (!opt.font)
  2867. throw new Error('must provide a valid bitmap font')
  2868. var glyphs = this.glyphs
  2869. var text = opt.text||''
  2870. var font = opt.font
  2871. this._setupSpaceGlyphs(font)
  2872. var lines = wordWrap.lines(text, opt)
  2873. var minWidth = opt.width || 0
  2874. //clear glyphs
  2875. glyphs.length = 0
  2876. //get max line width
  2877. var maxLineWidth = lines.reduce(function(prev, line) {
  2878. return Math.max(prev, line.width, minWidth)
  2879. }, 0)
  2880. //the pen position
  2881. var x = 0
  2882. var y = 0
  2883. var lineHeight = number(opt.lineHeight, font.common.lineHeight)
  2884. var baseline = font.common.base
  2885. var descender = lineHeight-baseline
  2886. var letterSpacing = opt.letterSpacing || 0
  2887. var height = lineHeight * lines.length - descender
  2888. var align = getAlignType(this._opt.align)
  2889. //draw text along baseline
  2890. y -= height
  2891. //the metrics for this text layout
  2892. this._width = maxLineWidth
  2893. this._height = height
  2894. this._descender = lineHeight - baseline
  2895. this._baseline = baseline
  2896. this._xHeight = getXHeight(font)
  2897. this._capHeight = getCapHeight(font)
  2898. this._lineHeight = lineHeight
  2899. this._ascender = lineHeight - descender - this._xHeight
  2900. //layout each glyph
  2901. var self = this
  2902. lines.forEach(function(line, lineIndex) {
  2903. var start = line.start
  2904. var end = line.end
  2905. var lineWidth = line.width
  2906. var lastGlyph
  2907. //for each glyph in that line...
  2908. for (var i=start; i<end; i++) {
  2909. var id = text.charCodeAt(i)
  2910. var glyph = self.getGlyph(font, id)
  2911. if (glyph) {
  2912. if (lastGlyph)
  2913. x += getKerning(font, lastGlyph.id, glyph.id)
  2914. var tx = x
  2915. if (align === ALIGN_CENTER)
  2916. tx += (maxLineWidth-lineWidth)/2
  2917. else if (align === ALIGN_RIGHT)
  2918. tx += (maxLineWidth-lineWidth)
  2919. glyphs.push({
  2920. position: [tx, y],
  2921. data: glyph,
  2922. index: i,
  2923. line: lineIndex
  2924. })
  2925. //move pen forward
  2926. x += glyph.xadvance + letterSpacing
  2927. lastGlyph = glyph
  2928. }
  2929. }
  2930. //next line down
  2931. y += lineHeight
  2932. x = 0
  2933. })
  2934. this._linesTotal = lines.length;
  2935. }
  2936. TextLayout.prototype._setupSpaceGlyphs = function(font) {
  2937. //These are fallbacks, when the font doesn't include
  2938. //' ' or '\t' glyphs
  2939. this._fallbackSpaceGlyph = null
  2940. this._fallbackTabGlyph = null
  2941. if (!font.chars || font.chars.length === 0)
  2942. return
  2943. //try to get space glyph
  2944. //then fall back to the 'm' or 'w' glyphs
  2945. //then fall back to the first glyph available
  2946. var space = getGlyphById(font, SPACE_ID)
  2947. || getMGlyph(font)
  2948. || font.chars[0]
  2949. //and create a fallback for tab
  2950. var tabWidth = this._opt.tabSize * space.xadvance
  2951. this._fallbackSpaceGlyph = space
  2952. this._fallbackTabGlyph = xtend(space, {
  2953. x: 0, y: 0, xadvance: tabWidth, id: TAB_ID,
  2954. xoffset: 0, yoffset: 0, width: 0, height: 0
  2955. })
  2956. }
  2957. TextLayout.prototype.getGlyph = function(font, id) {
  2958. var glyph = getGlyphById(font, id)
  2959. if (glyph)
  2960. return glyph
  2961. else if (id === TAB_ID)
  2962. return this._fallbackTabGlyph
  2963. else if (id === SPACE_ID)
  2964. return this._fallbackSpaceGlyph
  2965. return null
  2966. }
  2967. TextLayout.prototype.computeMetrics = function(text, start, end, width) {
  2968. var letterSpacing = this._opt.letterSpacing || 0
  2969. var font = this._opt.font
  2970. var curPen = 0
  2971. var curWidth = 0
  2972. var count = 0
  2973. var glyph
  2974. var lastGlyph
  2975. if (!font.chars || font.chars.length === 0) {
  2976. return {
  2977. start: start,
  2978. end: start,
  2979. width: 0
  2980. }
  2981. }
  2982. end = Math.min(text.length, end)
  2983. for (var i=start; i < end; i++) {
  2984. var id = text.charCodeAt(i)
  2985. var glyph = this.getGlyph(font, id)
  2986. if (glyph) {
  2987. //move pen forward
  2988. var xoff = glyph.xoffset
  2989. var kern = lastGlyph ? getKerning(font, lastGlyph.id, glyph.id) : 0
  2990. curPen += kern
  2991. var nextPen = curPen + glyph.xadvance + letterSpacing
  2992. var nextWidth = curPen + glyph.width
  2993. //we've hit our limit; we can't move onto the next glyph
  2994. if (nextWidth >= width || nextPen >= width)
  2995. break
  2996. //otherwise continue along our line
  2997. curPen = nextPen
  2998. curWidth = nextWidth
  2999. lastGlyph = glyph
  3000. }
  3001. count++
  3002. }
  3003. //make sure rightmost edge lines up with rendered glyphs
  3004. if (lastGlyph)
  3005. curWidth += lastGlyph.xoffset
  3006. return {
  3007. start: start,
  3008. end: start + count,
  3009. width: curWidth
  3010. }
  3011. }
  3012. //getters for the private vars
  3013. ;['width', 'height',
  3014. 'descender', 'ascender',
  3015. 'xHeight', 'baseline',
  3016. 'capHeight',
  3017. 'lineHeight' ].forEach(addGetter)
  3018. function addGetter(name) {
  3019. Object.defineProperty(TextLayout.prototype, name, {
  3020. get: wrapper(name),
  3021. configurable: true
  3022. })
  3023. }
  3024. //create lookups for private vars
  3025. function wrapper(name) {
  3026. return (new Function([
  3027. 'return function '+name+'() {',
  3028. ' return this._'+name,
  3029. '}'
  3030. ].join('\n')))()
  3031. }
  3032. function getGlyphById(font, id) {
  3033. if (!font.chars || font.chars.length === 0)
  3034. return null
  3035. var glyphIdx = findChar(font.chars, id)
  3036. if (glyphIdx >= 0)
  3037. return font.chars[glyphIdx]
  3038. return null
  3039. }
  3040. function getXHeight(font) {
  3041. for (var i=0; i<X_HEIGHTS.length; i++) {
  3042. var id = X_HEIGHTS[i].charCodeAt(0)
  3043. var idx = findChar(font.chars, id)
  3044. if (idx >= 0)
  3045. return font.chars[idx].height
  3046. }
  3047. return 0
  3048. }
  3049. function getMGlyph(font) {
  3050. for (var i=0; i<M_WIDTHS.length; i++) {
  3051. var id = M_WIDTHS[i].charCodeAt(0)
  3052. var idx = findChar(font.chars, id)
  3053. if (idx >= 0)
  3054. return font.chars[idx]
  3055. }
  3056. return 0
  3057. }
  3058. function getCapHeight(font) {
  3059. for (var i=0; i<CAP_HEIGHTS.length; i++) {
  3060. var id = CAP_HEIGHTS[i].charCodeAt(0)
  3061. var idx = findChar(font.chars, id)
  3062. if (idx >= 0)
  3063. return font.chars[idx].height
  3064. }
  3065. return 0
  3066. }
  3067. function getKerning(font, left, right) {
  3068. if (!font.kernings || font.kernings.length === 0)
  3069. return 0
  3070. var table = font.kernings
  3071. for (var i=0; i<table.length; i++) {
  3072. var kern = table[i]
  3073. if (kern.first === left && kern.second === right)
  3074. return kern.amount
  3075. }
  3076. return 0
  3077. }
  3078. function getAlignType(align) {
  3079. if (align === 'center')
  3080. return ALIGN_CENTER
  3081. else if (align === 'right')
  3082. return ALIGN_RIGHT
  3083. return ALIGN_LEFT
  3084. }
  3085. },{"as-number":2,"indexof-property":21,"word-wrapper":51,"xtend":54}],26:[function(_dereq_,module,exports){
  3086. (function (Buffer){
  3087. var xhr = _dereq_('xhr')
  3088. var noop = function(){}
  3089. var parseASCII = _dereq_('parse-bmfont-ascii')
  3090. var parseXML = _dereq_('parse-bmfont-xml')
  3091. var readBinary = _dereq_('parse-bmfont-binary')
  3092. var isBinaryFormat = _dereq_('./lib/is-binary')
  3093. var xtend = _dereq_('xtend')
  3094. var xml2 = (function hasXML2() {
  3095. return self.XMLHttpRequest && "withCredentials" in new XMLHttpRequest
  3096. })()
  3097. module.exports = function(opt, cb) {
  3098. cb = typeof cb === 'function' ? cb : noop
  3099. if (typeof opt === 'string')
  3100. opt = { uri: opt }
  3101. else if (!opt)
  3102. opt = {}
  3103. var expectBinary = opt.binary
  3104. if (expectBinary)
  3105. opt = getBinaryOpts(opt)
  3106. xhr(opt, function(err, res, body) {
  3107. if (err)
  3108. return cb(err)
  3109. if (!/^2/.test(res.statusCode))
  3110. return cb(new Error('http status code: '+res.statusCode))
  3111. if (!body)
  3112. return cb(new Error('no body result'))
  3113. var binary = false
  3114. //if the response type is an array buffer,
  3115. //we need to convert it into a regular Buffer object
  3116. if (isArrayBuffer(body)) {
  3117. var array = new Uint8Array(body)
  3118. body = new Buffer(array, 'binary')
  3119. }
  3120. //now check the string/Buffer response
  3121. //and see if it has a binary BMF header
  3122. if (isBinaryFormat(body)) {
  3123. binary = true
  3124. //if we have a string, turn it into a Buffer
  3125. if (typeof body === 'string')
  3126. body = new Buffer(body, 'binary')
  3127. }
  3128. //we are not parsing a binary format, just ASCII/XML/etc
  3129. if (!binary) {
  3130. //might still be a buffer if responseType is 'arraybuffer'
  3131. if (Buffer.isBuffer(body))
  3132. body = body.toString(opt.encoding)
  3133. body = body.trim()
  3134. }
  3135. var result
  3136. try {
  3137. var type = res.headers['content-type']
  3138. if (binary)
  3139. result = readBinary(body)
  3140. else if (/json/.test(type) || body.charAt(0) === '{')
  3141. result = JSON.parse(body)
  3142. else if (/xml/.test(type) || body.charAt(0) === '<')
  3143. result = parseXML(body)
  3144. else
  3145. result = parseASCII(body)
  3146. } catch (e) {
  3147. cb(new Error('error parsing font '+e.message))
  3148. cb = noop
  3149. }
  3150. cb(null, result)
  3151. })
  3152. }
  3153. function isArrayBuffer(arr) {
  3154. var str = Object.prototype.toString
  3155. return str.call(arr) === '[object ArrayBuffer]'
  3156. }
  3157. function getBinaryOpts(opt) {
  3158. //IE10+ and other modern browsers support array buffers
  3159. if (xml2)
  3160. return xtend(opt, { responseType: 'arraybuffer' })
  3161. if (typeof self.XMLHttpRequest === 'undefined')
  3162. throw new Error('your browser does not support XHR loading')
  3163. //IE9 and XML1 browsers could still use an override
  3164. var req = new self.XMLHttpRequest()
  3165. req.overrideMimeType('text/plain; charset=x-user-defined')
  3166. return xtend({
  3167. xhr: req
  3168. }, opt)
  3169. }
  3170. }).call(this,_dereq_("buffer").Buffer)
  3171. },{"./lib/is-binary":27,"buffer":4,"parse-bmfont-ascii":29,"parse-bmfont-binary":30,"parse-bmfont-xml":31,"xhr":52,"xtend":54}],27:[function(_dereq_,module,exports){
  3172. (function (Buffer){
  3173. var equal = _dereq_('buffer-equal')
  3174. var HEADER = new Buffer([66, 77, 70, 3])
  3175. module.exports = function(buf) {
  3176. if (typeof buf === 'string')
  3177. return buf.substring(0, 3) === 'BMF'
  3178. return buf.length > 4 && equal(buf.slice(0, 4), HEADER)
  3179. }
  3180. }).call(this,_dereq_("buffer").Buffer)
  3181. },{"buffer":4,"buffer-equal":10}],28:[function(_dereq_,module,exports){
  3182. 'use strict';
  3183. /* eslint-disable no-unused-vars */
  3184. var hasOwnProperty = Object.prototype.hasOwnProperty;
  3185. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  3186. function toObject(val) {
  3187. if (val === null || val === undefined) {
  3188. throw new TypeError('Object.assign cannot be called with null or undefined');
  3189. }
  3190. return Object(val);
  3191. }
  3192. function shouldUseNative() {
  3193. try {
  3194. if (!Object.assign) {
  3195. return false;
  3196. }
  3197. // Detect buggy property enumeration order in older V8 versions.
  3198. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  3199. var test1 = new String('abc'); // eslint-disable-line
  3200. test1[5] = 'de';
  3201. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  3202. return false;
  3203. }
  3204. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3205. var test2 = {};
  3206. for (var i = 0; i < 10; i++) {
  3207. test2['_' + String.fromCharCode(i)] = i;
  3208. }
  3209. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  3210. return test2[n];
  3211. });
  3212. if (order2.join('') !== '0123456789') {
  3213. return false;
  3214. }
  3215. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  3216. var test3 = {};
  3217. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  3218. test3[letter] = letter;
  3219. });
  3220. if (Object.keys(Object.assign({}, test3)).join('') !==
  3221. 'abcdefghijklmnopqrst') {
  3222. return false;
  3223. }
  3224. return true;
  3225. } catch (e) {
  3226. // We don't expect any of the above to throw, but better to be safe.
  3227. return false;
  3228. }
  3229. }
  3230. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  3231. var from;
  3232. var to = toObject(target);
  3233. var symbols;
  3234. for (var s = 1; s < arguments.length; s++) {
  3235. from = Object(arguments[s]);
  3236. for (var key in from) {
  3237. if (hasOwnProperty.call(from, key)) {
  3238. to[key] = from[key];
  3239. }
  3240. }
  3241. if (Object.getOwnPropertySymbols) {
  3242. symbols = Object.getOwnPropertySymbols(from);
  3243. for (var i = 0; i < symbols.length; i++) {
  3244. if (propIsEnumerable.call(from, symbols[i])) {
  3245. to[symbols[i]] = from[symbols[i]];
  3246. }
  3247. }
  3248. }
  3249. }
  3250. return to;
  3251. };
  3252. },{}],29:[function(_dereq_,module,exports){
  3253. module.exports = function parseBMFontAscii(data) {
  3254. if (!data)
  3255. throw new Error('no data provided')
  3256. data = data.toString().trim()
  3257. var output = {
  3258. pages: [],
  3259. chars: [],
  3260. kernings: []
  3261. }
  3262. var lines = data.split(/\r\n?|\n/g)
  3263. if (lines.length === 0)
  3264. throw new Error('no data in BMFont file')
  3265. for (var i = 0; i < lines.length; i++) {
  3266. var lineData = splitLine(lines[i], i)
  3267. if (!lineData) //skip empty lines
  3268. continue
  3269. if (lineData.key === 'page') {
  3270. if (typeof lineData.data.id !== 'number')
  3271. throw new Error('malformed file at line ' + i + ' -- needs page id=N')
  3272. if (typeof lineData.data.file !== 'string')
  3273. throw new Error('malformed file at line ' + i + ' -- needs page file="path"')
  3274. output.pages[lineData.data.id] = lineData.data.file
  3275. } else if (lineData.key === 'chars' || lineData.key === 'kernings') {
  3276. //... do nothing for these two ...
  3277. } else if (lineData.key === 'char') {
  3278. output.chars.push(lineData.data)
  3279. } else if (lineData.key === 'kerning') {
  3280. output.kernings.push(lineData.data)
  3281. } else {
  3282. output[lineData.key] = lineData.data
  3283. }
  3284. }
  3285. return output
  3286. }
  3287. function splitLine(line, idx) {
  3288. line = line.replace(/\t+/g, ' ').trim()
  3289. if (!line)
  3290. return null
  3291. var space = line.indexOf(' ')
  3292. if (space === -1)
  3293. throw new Error("no named row at line " + idx)
  3294. var key = line.substring(0, space)
  3295. line = line.substring(space + 1)
  3296. //clear "letter" field as it is non-standard and
  3297. //requires additional complexity to parse " / = symbols
  3298. line = line.replace(/letter=[\'\"]\S+[\'\"]/gi, '')
  3299. line = line.split("=")
  3300. line = line.map(function(str) {
  3301. return str.trim().match((/(".*?"|[^"\s]+)+(?=\s*|\s*$)/g))
  3302. })
  3303. var data = []
  3304. for (var i = 0; i < line.length; i++) {
  3305. var dt = line[i]
  3306. if (i === 0) {
  3307. data.push({
  3308. key: dt[0],
  3309. data: ""
  3310. })
  3311. } else if (i === line.length - 1) {
  3312. data[data.length - 1].data = parseData(dt[0])
  3313. } else {
  3314. data[data.length - 1].data = parseData(dt[0])
  3315. data.push({
  3316. key: dt[1],
  3317. data: ""
  3318. })
  3319. }
  3320. }
  3321. var out = {
  3322. key: key,
  3323. data: {}
  3324. }
  3325. data.forEach(function(v) {
  3326. out.data[v.key] = v.data;
  3327. })
  3328. return out
  3329. }
  3330. function parseData(data) {
  3331. if (!data || data.length === 0)
  3332. return ""
  3333. if (data.indexOf('"') === 0 || data.indexOf("'") === 0)
  3334. return data.substring(1, data.length - 1)
  3335. if (data.indexOf(',') !== -1)
  3336. return parseIntList(data)
  3337. return parseInt(data, 10)
  3338. }
  3339. function parseIntList(data) {
  3340. return data.split(',').map(function(val) {
  3341. return parseInt(val, 10)
  3342. })
  3343. }
  3344. },{}],30:[function(_dereq_,module,exports){
  3345. var HEADER = [66, 77, 70]
  3346. module.exports = function readBMFontBinary(buf) {
  3347. if (buf.length < 6)
  3348. throw new Error('invalid buffer length for BMFont')
  3349. var header = HEADER.every(function(byte, i) {
  3350. return buf.readUInt8(i) === byte
  3351. })
  3352. if (!header)
  3353. throw new Error('BMFont missing BMF byte header')
  3354. var i = 3
  3355. var vers = buf.readUInt8(i++)
  3356. if (vers > 3)
  3357. throw new Error('Only supports BMFont Binary v3 (BMFont App v1.10)')
  3358. var target = { kernings: [], chars: [] }
  3359. for (var b=0; b<5; b++)
  3360. i += readBlock(target, buf, i)
  3361. return target
  3362. }
  3363. function readBlock(target, buf, i) {
  3364. if (i > buf.length-1)
  3365. return 0
  3366. var blockID = buf.readUInt8(i++)
  3367. var blockSize = buf.readInt32LE(i)
  3368. i += 4
  3369. switch(blockID) {
  3370. case 1:
  3371. target.info = readInfo(buf, i)
  3372. break
  3373. case 2:
  3374. target.common = readCommon(buf, i)
  3375. break
  3376. case 3:
  3377. target.pages = readPages(buf, i, blockSize)
  3378. break
  3379. case 4:
  3380. target.chars = readChars(buf, i, blockSize)
  3381. break
  3382. case 5:
  3383. target.kernings = readKernings(buf, i, blockSize)
  3384. break
  3385. }
  3386. return 5 + blockSize
  3387. }
  3388. function readInfo(buf, i) {
  3389. var info = {}
  3390. info.size = buf.readInt16LE(i)
  3391. var bitField = buf.readUInt8(i+2)
  3392. info.smooth = (bitField >> 7) & 1
  3393. info.unicode = (bitField >> 6) & 1
  3394. info.italic = (bitField >> 5) & 1
  3395. info.bold = (bitField >> 4) & 1
  3396. //fixedHeight is only mentioned in binary spec
  3397. if ((bitField >> 3) & 1)
  3398. info.fixedHeight = 1
  3399. info.charset = buf.readUInt8(i+3) || ''
  3400. info.stretchH = buf.readUInt16LE(i+4)
  3401. info.aa = buf.readUInt8(i+6)
  3402. info.padding = [
  3403. buf.readInt8(i+7),
  3404. buf.readInt8(i+8),
  3405. buf.readInt8(i+9),
  3406. buf.readInt8(i+10)
  3407. ]
  3408. info.spacing = [
  3409. buf.readInt8(i+11),
  3410. buf.readInt8(i+12)
  3411. ]
  3412. info.outline = buf.readUInt8(i+13)
  3413. info.face = readStringNT(buf, i+14)
  3414. return info
  3415. }
  3416. function readCommon(buf, i) {
  3417. var common = {}
  3418. common.lineHeight = buf.readUInt16LE(i)
  3419. common.base = buf.readUInt16LE(i+2)
  3420. common.scaleW = buf.readUInt16LE(i+4)
  3421. common.scaleH = buf.readUInt16LE(i+6)
  3422. common.pages = buf.readUInt16LE(i+8)
  3423. var bitField = buf.readUInt8(i+10)
  3424. common.packed = 0
  3425. common.alphaChnl = buf.readUInt8(i+11)
  3426. common.redChnl = buf.readUInt8(i+12)
  3427. common.greenChnl = buf.readUInt8(i+13)
  3428. common.blueChnl = buf.readUInt8(i+14)
  3429. return common
  3430. }
  3431. function readPages(buf, i, size) {
  3432. var pages = []
  3433. var text = readNameNT(buf, i)
  3434. var len = text.length+1
  3435. var count = size / len
  3436. for (var c=0; c<count; c++) {
  3437. pages[c] = buf.slice(i, i+text.length).toString('utf8')
  3438. i += len
  3439. }
  3440. return pages
  3441. }
  3442. function readChars(buf, i, blockSize) {
  3443. var chars = []
  3444. var count = blockSize / 20
  3445. for (var c=0; c<count; c++) {
  3446. var char = {}
  3447. var off = c*20
  3448. char.id = buf.readUInt32LE(i + 0 + off)
  3449. char.x = buf.readUInt16LE(i + 4 + off)
  3450. char.y = buf.readUInt16LE(i + 6 + off)
  3451. char.width = buf.readUInt16LE(i + 8 + off)
  3452. char.height = buf.readUInt16LE(i + 10 + off)
  3453. char.xoffset = buf.readInt16LE(i + 12 + off)
  3454. char.yoffset = buf.readInt16LE(i + 14 + off)
  3455. char.xadvance = buf.readInt16LE(i + 16 + off)
  3456. char.page = buf.readUInt8(i + 18 + off)
  3457. char.chnl = buf.readUInt8(i + 19 + off)
  3458. chars[c] = char
  3459. }
  3460. return chars
  3461. }
  3462. function readKernings(buf, i, blockSize) {
  3463. var kernings = []
  3464. var count = blockSize / 10
  3465. for (var c=0; c<count; c++) {
  3466. var kern = {}
  3467. var off = c*10
  3468. kern.first = buf.readUInt32LE(i + 0 + off)
  3469. kern.second = buf.readUInt32LE(i + 4 + off)
  3470. kern.amount = buf.readInt16LE(i + 8 + off)
  3471. kernings[c] = kern
  3472. }
  3473. return kernings
  3474. }
  3475. function readNameNT(buf, offset) {
  3476. var pos=offset
  3477. for (; pos<buf.length; pos++) {
  3478. if (buf[pos] === 0x00)
  3479. break
  3480. }
  3481. return buf.slice(offset, pos)
  3482. }
  3483. function readStringNT(buf, offset) {
  3484. return readNameNT(buf, offset).toString('utf8')
  3485. }
  3486. },{}],31:[function(_dereq_,module,exports){
  3487. var parseAttributes = _dereq_('./parse-attribs')
  3488. var parseFromString = _dereq_('xml-parse-from-string')
  3489. //In some cases element.attribute.nodeName can return
  3490. //all lowercase values.. so we need to map them to the correct
  3491. //case
  3492. var NAME_MAP = {
  3493. scaleh: 'scaleH',
  3494. scalew: 'scaleW',
  3495. stretchh: 'stretchH',
  3496. lineheight: 'lineHeight',
  3497. alphachnl: 'alphaChnl',
  3498. redchnl: 'redChnl',
  3499. greenchnl: 'greenChnl',
  3500. bluechnl: 'blueChnl'
  3501. }
  3502. module.exports = function parse(data) {
  3503. data = data.toString()
  3504. var xmlRoot = parseFromString(data)
  3505. var output = {
  3506. pages: [],
  3507. chars: [],
  3508. kernings: []
  3509. }
  3510. //get config settings
  3511. ;['info', 'common'].forEach(function(key) {
  3512. var element = xmlRoot.getElementsByTagName(key)[0]
  3513. if (element)
  3514. output[key] = parseAttributes(getAttribs(element))
  3515. })
  3516. //get page info
  3517. var pageRoot = xmlRoot.getElementsByTagName('pages')[0]
  3518. if (!pageRoot)
  3519. throw new Error('malformed file -- no <pages> element')
  3520. var pages = pageRoot.getElementsByTagName('page')
  3521. for (var i=0; i<pages.length; i++) {
  3522. var p = pages[i]
  3523. var id = parseInt(p.getAttribute('id'), 10)
  3524. var file = p.getAttribute('file')
  3525. if (isNaN(id))
  3526. throw new Error('malformed file -- page "id" attribute is NaN')
  3527. if (!file)
  3528. throw new Error('malformed file -- needs page "file" attribute')
  3529. output.pages[parseInt(id, 10)] = file
  3530. }
  3531. //get kernings / chars
  3532. ;['chars', 'kernings'].forEach(function(key) {
  3533. var element = xmlRoot.getElementsByTagName(key)[0]
  3534. if (!element)
  3535. return
  3536. var childTag = key.substring(0, key.length-1)
  3537. var children = element.getElementsByTagName(childTag)
  3538. for (var i=0; i<children.length; i++) {
  3539. var child = children[i]
  3540. output[key].push(parseAttributes(getAttribs(child)))
  3541. }
  3542. })
  3543. return output
  3544. }
  3545. function getAttribs(element) {
  3546. var attribs = getAttribList(element)
  3547. return attribs.reduce(function(dict, attrib) {
  3548. var key = mapName(attrib.nodeName)
  3549. dict[key] = attrib.nodeValue
  3550. return dict
  3551. }, {})
  3552. }
  3553. function getAttribList(element) {
  3554. //IE8+ and modern browsers
  3555. var attribs = []
  3556. for (var i=0; i<element.attributes.length; i++)
  3557. attribs.push(element.attributes[i])
  3558. return attribs
  3559. }
  3560. function mapName(nodeName) {
  3561. return NAME_MAP[nodeName.toLowerCase()] || nodeName
  3562. }
  3563. },{"./parse-attribs":32,"xml-parse-from-string":53}],32:[function(_dereq_,module,exports){
  3564. //Some versions of GlyphDesigner have a typo
  3565. //that causes some bugs with parsing.
  3566. //Need to confirm with recent version of the software
  3567. //to see whether this is still an issue or not.
  3568. var GLYPH_DESIGNER_ERROR = 'chasrset'
  3569. module.exports = function parseAttributes(obj) {
  3570. if (GLYPH_DESIGNER_ERROR in obj) {
  3571. obj['charset'] = obj[GLYPH_DESIGNER_ERROR]
  3572. delete obj[GLYPH_DESIGNER_ERROR]
  3573. }
  3574. for (var k in obj) {
  3575. if (k === 'face' || k === 'charset')
  3576. continue
  3577. else if (k === 'padding' || k === 'spacing')
  3578. obj[k] = parseIntList(obj[k])
  3579. else
  3580. obj[k] = parseInt(obj[k], 10)
  3581. }
  3582. return obj
  3583. }
  3584. function parseIntList(data) {
  3585. return data.split(',').map(function(val) {
  3586. return parseInt(val, 10)
  3587. })
  3588. }
  3589. },{}],33:[function(_dereq_,module,exports){
  3590. var trim = _dereq_('trim')
  3591. , forEach = _dereq_('for-each')
  3592. , isArray = function(arg) {
  3593. return Object.prototype.toString.call(arg) === '[object Array]';
  3594. }
  3595. module.exports = function (headers) {
  3596. if (!headers)
  3597. return {}
  3598. var result = {}
  3599. forEach(
  3600. trim(headers).split('\n')
  3601. , function (row) {
  3602. var index = row.indexOf(':')
  3603. , key = trim(row.slice(0, index)).toLowerCase()
  3604. , value = trim(row.slice(index + 1))
  3605. if (typeof(result[key]) === 'undefined') {
  3606. result[key] = value
  3607. } else if (isArray(result[key])) {
  3608. result[key].push(value)
  3609. } else {
  3610. result[key] = [ result[key], value ]
  3611. }
  3612. }
  3613. )
  3614. return result
  3615. }
  3616. },{"for-each":19,"trim":48}],34:[function(_dereq_,module,exports){
  3617. (function (global){
  3618. var performance = global.performance || {};
  3619. var present = (function () {
  3620. var names = ['now', 'webkitNow', 'msNow', 'mozNow', 'oNow'];
  3621. while (names.length) {
  3622. var name = names.shift();
  3623. if (name in performance) {
  3624. return performance[name].bind(performance);
  3625. }
  3626. }
  3627. var dateNow = Date.now || function () { return new Date().getTime(); };
  3628. var navigationStart = (performance.timing || {}).navigationStart || dateNow();
  3629. return function () {
  3630. return dateNow() - navigationStart;
  3631. };
  3632. }());
  3633. present.performanceNow = performance.now;
  3634. present.noConflict = function () {
  3635. performance.now = present.performanceNow;
  3636. };
  3637. present.conflict = function () {
  3638. performance.now = present;
  3639. };
  3640. present.conflict();
  3641. module.exports = present;
  3642. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  3643. },{}],35:[function(_dereq_,module,exports){
  3644. (function(root) {
  3645. // Store setTimeout reference so promise-polyfill will be unaffected by
  3646. // other code modifying setTimeout (like sinon.useFakeTimers())
  3647. var setTimeoutFunc = setTimeout;
  3648. // Use polyfill for setImmediate for performance gains
  3649. var asap = (typeof setImmediate === 'function' && setImmediate) ||
  3650. function(fn) { setTimeoutFunc(fn, 1); };
  3651. // Polyfill for Function.prototype.bind
  3652. function bind(fn, thisArg) {
  3653. return function() {
  3654. fn.apply(thisArg, arguments);
  3655. }
  3656. }
  3657. var isArray = Array.isArray || function(value) { return Object.prototype.toString.call(value) === "[object Array]" };
  3658. function Promise(fn) {
  3659. if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new');
  3660. if (typeof fn !== 'function') throw new TypeError('not a function');
  3661. this._state = null;
  3662. this._value = null;
  3663. this._deferreds = []
  3664. doResolve(fn, bind(resolve, this), bind(reject, this))
  3665. }
  3666. function handle(deferred) {
  3667. var me = this;
  3668. if (this._state === null) {
  3669. this._deferreds.push(deferred);
  3670. return
  3671. }
  3672. asap(function() {
  3673. var cb = me._state ? deferred.onFulfilled : deferred.onRejected
  3674. if (cb === null) {
  3675. (me._state ? deferred.resolve : deferred.reject)(me._value);
  3676. return;
  3677. }
  3678. var ret;
  3679. try {
  3680. ret = cb(me._value);
  3681. }
  3682. catch (e) {
  3683. deferred.reject(e);
  3684. return;
  3685. }
  3686. deferred.resolve(ret);
  3687. })
  3688. }
  3689. function resolve(newValue) {
  3690. try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  3691. if (newValue === this) throw new TypeError('A promise cannot be resolved with itself.');
  3692. if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
  3693. var then = newValue.then;
  3694. if (typeof then === 'function') {
  3695. doResolve(bind(then, newValue), bind(resolve, this), bind(reject, this));
  3696. return;
  3697. }
  3698. }
  3699. this._state = true;
  3700. this._value = newValue;
  3701. finale.call(this);
  3702. } catch (e) { reject.call(this, e); }
  3703. }
  3704. function reject(newValue) {
  3705. this._state = false;
  3706. this._value = newValue;
  3707. finale.call(this);
  3708. }
  3709. function finale() {
  3710. for (var i = 0, len = this._deferreds.length; i < len; i++) {
  3711. handle.call(this, this._deferreds[i]);
  3712. }
  3713. this._deferreds = null;
  3714. }
  3715. function Handler(onFulfilled, onRejected, resolve, reject){
  3716. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  3717. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  3718. this.resolve = resolve;
  3719. this.reject = reject;
  3720. }
  3721. /**
  3722. * Take a potentially misbehaving resolver function and make sure
  3723. * onFulfilled and onRejected are only called once.
  3724. *
  3725. * Makes no guarantees about asynchrony.
  3726. */
  3727. function doResolve(fn, onFulfilled, onRejected) {
  3728. var done = false;
  3729. try {
  3730. fn(function (value) {
  3731. if (done) return;
  3732. done = true;
  3733. onFulfilled(value);
  3734. }, function (reason) {
  3735. if (done) return;
  3736. done = true;
  3737. onRejected(reason);
  3738. })
  3739. } catch (ex) {
  3740. if (done) return;
  3741. done = true;
  3742. onRejected(ex);
  3743. }
  3744. }
  3745. Promise.prototype['catch'] = function (onRejected) {
  3746. return this.then(null, onRejected);
  3747. };
  3748. Promise.prototype.then = function(onFulfilled, onRejected) {
  3749. var me = this;
  3750. return new Promise(function(resolve, reject) {
  3751. handle.call(me, new Handler(onFulfilled, onRejected, resolve, reject));
  3752. })
  3753. };
  3754. Promise.all = function () {
  3755. var args = Array.prototype.slice.call(arguments.length === 1 && isArray(arguments[0]) ? arguments[0] : arguments);
  3756. return new Promise(function (resolve, reject) {
  3757. if (args.length === 0) return resolve([]);
  3758. var remaining = args.length;
  3759. function res(i, val) {
  3760. try {
  3761. if (val && (typeof val === 'object' || typeof val === 'function')) {
  3762. var then = val.then;
  3763. if (typeof then === 'function') {
  3764. then.call(val, function (val) { res(i, val) }, reject);
  3765. return;
  3766. }
  3767. }
  3768. args[i] = val;
  3769. if (--remaining === 0) {
  3770. resolve(args);
  3771. }
  3772. } catch (ex) {
  3773. reject(ex);
  3774. }
  3775. }
  3776. for (var i = 0; i < args.length; i++) {
  3777. res(i, args[i]);
  3778. }
  3779. });
  3780. };
  3781. Promise.resolve = function (value) {
  3782. if (value && typeof value === 'object' && value.constructor === Promise) {
  3783. return value;
  3784. }
  3785. return new Promise(function (resolve) {
  3786. resolve(value);
  3787. });
  3788. };
  3789. Promise.reject = function (value) {
  3790. return new Promise(function (resolve, reject) {
  3791. reject(value);
  3792. });
  3793. };
  3794. Promise.race = function (values) {
  3795. return new Promise(function (resolve, reject) {
  3796. for(var i = 0, len = values.length; i < len; i++) {
  3797. values[i].then(resolve, reject);
  3798. }
  3799. });
  3800. };
  3801. /**
  3802. * Set the immediate function to execute callbacks
  3803. * @param fn {function} Function to execute
  3804. * @private
  3805. */
  3806. Promise._setImmediateFn = function _setImmediateFn(fn) {
  3807. asap = fn;
  3808. };
  3809. if (typeof module !== 'undefined' && module.exports) {
  3810. module.exports = Promise;
  3811. } else if (!root.Promise) {
  3812. root.Promise = Promise;
  3813. }
  3814. })(this);
  3815. },{}],36:[function(_dereq_,module,exports){
  3816. var dtype = _dereq_('dtype')
  3817. var anArray = _dereq_('an-array')
  3818. var isBuffer = _dereq_('is-buffer')
  3819. var CW = [0, 2, 3]
  3820. var CCW = [2, 1, 3]
  3821. module.exports = function createQuadElements(array, opt) {
  3822. //if user didn't specify an output array
  3823. if (!array || !(anArray(array) || isBuffer(array))) {
  3824. opt = array || {}
  3825. array = null
  3826. }
  3827. if (typeof opt === 'number') //backwards-compatible
  3828. opt = { count: opt }
  3829. else
  3830. opt = opt || {}
  3831. var type = typeof opt.type === 'string' ? opt.type : 'uint16'
  3832. var count = typeof opt.count === 'number' ? opt.count : 1
  3833. var start = (opt.start || 0)
  3834. var dir = opt.clockwise !== false ? CW : CCW,
  3835. a = dir[0],
  3836. b = dir[1],
  3837. c = dir[2]
  3838. var numIndices = count * 6
  3839. var indices = array || new (dtype(type))(numIndices)
  3840. for (var i = 0, j = 0; i < numIndices; i += 6, j += 4) {
  3841. var x = i + start
  3842. indices[x + 0] = j + 0
  3843. indices[x + 1] = j + 1
  3844. indices[x + 2] = j + 2
  3845. indices[x + 3] = j + a
  3846. indices[x + 4] = j + b
  3847. indices[x + 5] = j + c
  3848. }
  3849. return indices
  3850. }
  3851. },{"an-array":1,"dtype":17,"is-buffer":23}],37:[function(_dereq_,module,exports){
  3852. /*:: type Attr = { [key: string]: string } */
  3853. /*
  3854. style-attr
  3855. ====
  3856. Very simple parsing and stringifying of style attributes.
  3857. `parse`
  3858. ----
  3859. Convert a style attribute string to an object.
  3860. */
  3861. /*:: declare function parse (raw: string): Attr */
  3862. function parse(raw) {
  3863. var trim = function (s) {
  3864. return s.trim();
  3865. };
  3866. var obj = {};
  3867. getKeyValueChunks(raw).map(trim).filter(Boolean).forEach(function (item) {
  3868. // split with `.indexOf` rather than `.split` because the value may also contain colons.
  3869. var pos = item.indexOf(':');
  3870. var key = item.substr(0, pos).trim();
  3871. var val = item.substr(pos + 1).trim();
  3872. obj[key] = val;
  3873. });
  3874. return obj;
  3875. }
  3876. /*
  3877. `getKeyValueChunks`
  3878. ----
  3879. Split a string into chunks matching `<key>: <value>`
  3880. */
  3881. /*:: declare function getKeyValueChunks (raw: string): Array<string> */
  3882. function getKeyValueChunks(raw) {
  3883. var chunks = [];
  3884. var offset = 0;
  3885. var sep = ';';
  3886. var hasUnclosedUrl = /url\([^\)]+$/;
  3887. var chunk = '';
  3888. var nextSplit;
  3889. while (offset < raw.length) {
  3890. nextSplit = raw.indexOf(sep, offset);
  3891. if (nextSplit === -1) {
  3892. nextSplit = raw.length;
  3893. }
  3894. chunk += raw.substring(offset, nextSplit);
  3895. // data URIs can contain semicolons, so make sure we get the whole thing
  3896. if (hasUnclosedUrl.test(chunk)) {
  3897. chunk += ';';
  3898. offset = nextSplit + 1;
  3899. continue;
  3900. }
  3901. chunks.push(chunk);
  3902. chunk = '';
  3903. offset = nextSplit + 1;
  3904. }
  3905. return chunks;
  3906. }
  3907. /*
  3908. `stringify`
  3909. ----
  3910. Convert an object into an attribute string
  3911. */
  3912. /*:: declare function stringify (obj: Attr): string */
  3913. function stringify(obj) {
  3914. return Object.keys(obj).map(function (key) {
  3915. return key + ':' + obj[key];
  3916. }).join(';');
  3917. }
  3918. /*
  3919. `normalize`
  3920. ----
  3921. Normalize an attribute string (eg. collapse duplicates)
  3922. */
  3923. /*:: declare function normalize (str: string): string */
  3924. function normalize(str) {
  3925. return stringify(parse(str));
  3926. }
  3927. module.exports.parse = parse;
  3928. module.exports.stringify = stringify;
  3929. module.exports.normalize = normalize;
  3930. },{}],38:[function(_dereq_,module,exports){
  3931. var createLayout = _dereq_('layout-bmfont-text')
  3932. var inherits = _dereq_('inherits')
  3933. var createIndices = _dereq_('quad-indices')
  3934. var buffer = _dereq_('three-buffer-vertex-data')
  3935. var assign = _dereq_('object-assign')
  3936. var vertices = _dereq_('./lib/vertices')
  3937. var utils = _dereq_('./lib/utils')
  3938. var Base = THREE.BufferGeometry
  3939. module.exports = function createTextGeometry (opt) {
  3940. return new TextGeometry(opt)
  3941. }
  3942. function TextGeometry (opt) {
  3943. Base.call(this)
  3944. if (typeof opt === 'string') {
  3945. opt = { text: opt }
  3946. }
  3947. // use these as default values for any subsequent
  3948. // calls to update()
  3949. this._opt = assign({}, opt)
  3950. // also do an initial setup...
  3951. if (opt) this.update(opt)
  3952. }
  3953. inherits(TextGeometry, Base)
  3954. TextGeometry.prototype.update = function (opt) {
  3955. if (typeof opt === 'string') {
  3956. opt = { text: opt }
  3957. }
  3958. // use constructor defaults
  3959. opt = assign({}, this._opt, opt)
  3960. if (!opt.font) {
  3961. throw new TypeError('must specify a { font } in options')
  3962. }
  3963. this.layout = createLayout(opt)
  3964. // get vec2 texcoords
  3965. var flipY = opt.flipY !== false
  3966. // the desired BMFont data
  3967. var font = opt.font
  3968. // determine texture size from font file
  3969. var texWidth = font.common.scaleW
  3970. var texHeight = font.common.scaleH
  3971. // get visible glyphs
  3972. var glyphs = this.layout.glyphs.filter(function (glyph) {
  3973. var bitmap = glyph.data
  3974. return bitmap.width * bitmap.height > 0
  3975. })
  3976. // provide visible glyphs for convenience
  3977. this.visibleGlyphs = glyphs
  3978. // get common vertex data
  3979. var positions = vertices.positions(glyphs)
  3980. var uvs = vertices.uvs(glyphs, texWidth, texHeight, flipY)
  3981. var indices = createIndices({
  3982. clockwise: true,
  3983. type: 'uint16',
  3984. count: glyphs.length
  3985. })
  3986. // update vertex data
  3987. buffer.index(this, indices, 1, 'uint16')
  3988. buffer.attr(this, 'position', positions, 2)
  3989. buffer.attr(this, 'uv', uvs, 2)
  3990. // update multipage data
  3991. if (!opt.multipage && 'page' in this.attributes) {
  3992. // disable multipage rendering
  3993. this.removeAttribute('page')
  3994. } else if (opt.multipage) {
  3995. var pages = vertices.pages(glyphs)
  3996. // enable multipage rendering
  3997. buffer.attr(this, 'page', pages, 1)
  3998. }
  3999. }
  4000. TextGeometry.prototype.computeBoundingSphere = function () {
  4001. if (this.boundingSphere === null) {
  4002. this.boundingSphere = new THREE.Sphere()
  4003. }
  4004. var positions = this.attributes.position.array
  4005. var itemSize = this.attributes.position.itemSize
  4006. if (!positions || !itemSize || positions.length < 2) {
  4007. this.boundingSphere.radius = 0
  4008. this.boundingSphere.center.set(0, 0, 0)
  4009. return
  4010. }
  4011. utils.computeSphere(positions, this.boundingSphere)
  4012. if (isNaN(this.boundingSphere.radius)) {
  4013. console.error('THREE.BufferGeometry.computeBoundingSphere(): ' +
  4014. 'Computed radius is NaN. The ' +
  4015. '"position" attribute is likely to have NaN values.')
  4016. }
  4017. }
  4018. TextGeometry.prototype.computeBoundingBox = function () {
  4019. if (this.boundingBox === null) {
  4020. this.boundingBox = new THREE.Box3()
  4021. }
  4022. var bbox = this.boundingBox
  4023. var positions = this.attributes.position.array
  4024. var itemSize = this.attributes.position.itemSize
  4025. if (!positions || !itemSize || positions.length < 2) {
  4026. bbox.makeEmpty()
  4027. return
  4028. }
  4029. utils.computeBox(positions, bbox)
  4030. }
  4031. },{"./lib/utils":39,"./lib/vertices":40,"inherits":22,"layout-bmfont-text":25,"object-assign":28,"quad-indices":36,"three-buffer-vertex-data":41}],39:[function(_dereq_,module,exports){
  4032. var itemSize = 2
  4033. var box = { min: [0, 0], max: [0, 0] }
  4034. function bounds (positions) {
  4035. var count = positions.length / itemSize
  4036. box.min[0] = positions[0]
  4037. box.min[1] = positions[1]
  4038. box.max[0] = positions[0]
  4039. box.max[1] = positions[1]
  4040. for (var i = 0; i < count; i++) {
  4041. var x = positions[i * itemSize + 0]
  4042. var y = positions[i * itemSize + 1]
  4043. box.min[0] = Math.min(x, box.min[0])
  4044. box.min[1] = Math.min(y, box.min[1])
  4045. box.max[0] = Math.max(x, box.max[0])
  4046. box.max[1] = Math.max(y, box.max[1])
  4047. }
  4048. }
  4049. module.exports.computeBox = function (positions, output) {
  4050. bounds(positions)
  4051. output.min.set(box.min[0], box.min[1], 0)
  4052. output.max.set(box.max[0], box.max[1], 0)
  4053. }
  4054. module.exports.computeSphere = function (positions, output) {
  4055. bounds(positions)
  4056. var minX = box.min[0]
  4057. var minY = box.min[1]
  4058. var maxX = box.max[0]
  4059. var maxY = box.max[1]
  4060. var width = maxX - minX
  4061. var height = maxY - minY
  4062. var length = Math.sqrt(width * width + height * height)
  4063. output.center.set(minX + width / 2, minY + height / 2, 0)
  4064. output.radius = length / 2
  4065. }
  4066. },{}],40:[function(_dereq_,module,exports){
  4067. module.exports.pages = function pages (glyphs) {
  4068. var pages = new Float32Array(glyphs.length * 4 * 1)
  4069. var i = 0
  4070. glyphs.forEach(function (glyph) {
  4071. var id = glyph.data.page || 0
  4072. pages[i++] = id
  4073. pages[i++] = id
  4074. pages[i++] = id
  4075. pages[i++] = id
  4076. })
  4077. return pages
  4078. }
  4079. module.exports.uvs = function uvs (glyphs, texWidth, texHeight, flipY) {
  4080. var uvs = new Float32Array(glyphs.length * 4 * 2)
  4081. var i = 0
  4082. glyphs.forEach(function (glyph) {
  4083. var bitmap = glyph.data
  4084. var bw = (bitmap.x + bitmap.width)
  4085. var bh = (bitmap.y + bitmap.height)
  4086. // top left position
  4087. var u0 = bitmap.x / texWidth
  4088. var v1 = bitmap.y / texHeight
  4089. var u1 = bw / texWidth
  4090. var v0 = bh / texHeight
  4091. if (flipY) {
  4092. v1 = (texHeight - bitmap.y) / texHeight
  4093. v0 = (texHeight - bh) / texHeight
  4094. }
  4095. // BL
  4096. uvs[i++] = u0
  4097. uvs[i++] = v1
  4098. // TL
  4099. uvs[i++] = u0
  4100. uvs[i++] = v0
  4101. // TR
  4102. uvs[i++] = u1
  4103. uvs[i++] = v0
  4104. // BR
  4105. uvs[i++] = u1
  4106. uvs[i++] = v1
  4107. })
  4108. return uvs
  4109. }
  4110. module.exports.positions = function positions (glyphs) {
  4111. var positions = new Float32Array(glyphs.length * 4 * 2)
  4112. var i = 0
  4113. glyphs.forEach(function (glyph) {
  4114. var bitmap = glyph.data
  4115. // bottom left position
  4116. var x = glyph.position[0] + bitmap.xoffset
  4117. var y = glyph.position[1] + bitmap.yoffset
  4118. // quad size
  4119. var w = bitmap.width
  4120. var h = bitmap.height
  4121. // BL
  4122. positions[i++] = x
  4123. positions[i++] = y
  4124. // TL
  4125. positions[i++] = x
  4126. positions[i++] = y + h
  4127. // TR
  4128. positions[i++] = x + w
  4129. positions[i++] = y + h
  4130. // BR
  4131. positions[i++] = x + w
  4132. positions[i++] = y
  4133. })
  4134. return positions
  4135. }
  4136. },{}],41:[function(_dereq_,module,exports){
  4137. var flatten = _dereq_('flatten-vertex-data')
  4138. var warned = false;
  4139. module.exports.attr = setAttribute
  4140. module.exports.index = setIndex
  4141. function setIndex (geometry, data, itemSize, dtype) {
  4142. if (typeof itemSize !== 'number') itemSize = 1
  4143. if (typeof dtype !== 'string') dtype = 'uint16'
  4144. var isR69 = !geometry.index && typeof geometry.setIndex !== 'function'
  4145. var attrib = isR69 ? geometry.getAttribute('index') : geometry.index
  4146. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4147. if (newAttrib) {
  4148. if (isR69) geometry.addAttribute('index', newAttrib)
  4149. else geometry.index = newAttrib
  4150. }
  4151. }
  4152. function setAttribute (geometry, key, data, itemSize, dtype) {
  4153. if (typeof itemSize !== 'number') itemSize = 3
  4154. if (typeof dtype !== 'string') dtype = 'float32'
  4155. if (Array.isArray(data) &&
  4156. Array.isArray(data[0]) &&
  4157. data[0].length !== itemSize) {
  4158. throw new Error('Nested vertex array has unexpected size; expected ' +
  4159. itemSize + ' but found ' + data[0].length)
  4160. }
  4161. var attrib = geometry.getAttribute(key)
  4162. var newAttrib = updateAttribute(attrib, data, itemSize, dtype)
  4163. if (newAttrib) {
  4164. geometry.addAttribute(key, newAttrib)
  4165. }
  4166. }
  4167. function updateAttribute (attrib, data, itemSize, dtype) {
  4168. data = data || []
  4169. if (!attrib || rebuildAttribute(attrib, data, itemSize)) {
  4170. // create a new array with desired type
  4171. data = flatten(data, dtype)
  4172. var needsNewBuffer = attrib && typeof attrib.setArray !== 'function'
  4173. if (!attrib || needsNewBuffer) {
  4174. // We are on an old version of ThreeJS which can't
  4175. // support growing / shrinking buffers, so we need
  4176. // to build a new buffer
  4177. if (needsNewBuffer && !warned) {
  4178. warned = true
  4179. console.warn([
  4180. 'A WebGL buffer is being updated with a new size or itemSize, ',
  4181. 'however this version of ThreeJS only supports fixed-size buffers.',
  4182. '\nThe old buffer may still be kept in memory.\n',
  4183. 'To avoid memory leaks, it is recommended that you dispose ',
  4184. 'your geometries and create new ones, or update to ThreeJS r82 or newer.\n',
  4185. 'See here for discussion:\n',
  4186. 'https://github.com/mrdoob/three.js/pull/9631'
  4187. ].join(''))
  4188. }
  4189. // Build a new attribute
  4190. attrib = new THREE.BufferAttribute(data, itemSize);
  4191. }
  4192. attrib.itemSize = itemSize
  4193. attrib.needsUpdate = true
  4194. // New versions of ThreeJS suggest using setArray
  4195. // to change the data. It will use bufferData internally,
  4196. // so you can change the array size without any issues
  4197. if (typeof attrib.setArray === 'function') {
  4198. attrib.setArray(data)
  4199. }
  4200. return attrib
  4201. } else {
  4202. // copy data into the existing array
  4203. flatten(data, attrib.array)
  4204. attrib.needsUpdate = true
  4205. return null
  4206. }
  4207. }
  4208. // Test whether the attribute needs to be re-created,
  4209. // returns false if we can re-use it as-is.
  4210. function rebuildAttribute (attrib, data, itemSize) {
  4211. if (attrib.itemSize !== itemSize) return true
  4212. if (!attrib.array) return true
  4213. var attribLength = attrib.array.length
  4214. if (Array.isArray(data) && Array.isArray(data[0])) {
  4215. // [ [ x, y, z ] ]
  4216. return attribLength !== data.length * itemSize
  4217. } else {
  4218. // [ x, y, z ]
  4219. return attribLength !== data.length
  4220. }
  4221. return false
  4222. }
  4223. },{"flatten-vertex-data":18}],42:[function(_dereq_,module,exports){
  4224. (function (global, factory) {
  4225. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  4226. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4227. (factory((global.THREE = global.THREE || {})));
  4228. }(this, (function (exports) { 'use strict';
  4229. // Polyfills
  4230. if ( Number.EPSILON === undefined ) {
  4231. Number.EPSILON = Math.pow( 2, - 52 );
  4232. }
  4233. //
  4234. if ( Math.sign === undefined ) {
  4235. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  4236. Math.sign = function ( x ) {
  4237. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : + x;
  4238. };
  4239. }
  4240. if ( Function.prototype.name === undefined ) {
  4241. // Missing in IE9-11.
  4242. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
  4243. Object.defineProperty( Function.prototype, 'name', {
  4244. get: function () {
  4245. return this.toString().match( /^\s*function\s*([^\(\s]*)/ )[ 1 ];
  4246. }
  4247. } );
  4248. }
  4249. if ( Object.assign === undefined ) {
  4250. // Missing in IE.
  4251. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
  4252. ( function () {
  4253. Object.assign = function ( target ) {
  4254. 'use strict';
  4255. if ( target === undefined || target === null ) {
  4256. throw new TypeError( 'Cannot convert undefined or null to object' );
  4257. }
  4258. var output = Object( target );
  4259. for ( var index = 1; index < arguments.length; index ++ ) {
  4260. var source = arguments[ index ];
  4261. if ( source !== undefined && source !== null ) {
  4262. for ( var nextKey in source ) {
  4263. if ( Object.prototype.hasOwnProperty.call( source, nextKey ) ) {
  4264. output[ nextKey ] = source[ nextKey ];
  4265. }
  4266. }
  4267. }
  4268. }
  4269. return output;
  4270. };
  4271. } )();
  4272. }
  4273. /**
  4274. * https://github.com/mrdoob/eventdispatcher.js/
  4275. */
  4276. function EventDispatcher() {}
  4277. Object.assign( EventDispatcher.prototype, {
  4278. addEventListener: function ( type, listener ) {
  4279. if ( this._listeners === undefined ) this._listeners = {};
  4280. var listeners = this._listeners;
  4281. if ( listeners[ type ] === undefined ) {
  4282. listeners[ type ] = [];
  4283. }
  4284. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4285. listeners[ type ].push( listener );
  4286. }
  4287. },
  4288. hasEventListener: function ( type, listener ) {
  4289. if ( this._listeners === undefined ) return false;
  4290. var listeners = this._listeners;
  4291. return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
  4292. },
  4293. removeEventListener: function ( type, listener ) {
  4294. if ( this._listeners === undefined ) return;
  4295. var listeners = this._listeners;
  4296. var listenerArray = listeners[ type ];
  4297. if ( listenerArray !== undefined ) {
  4298. var index = listenerArray.indexOf( listener );
  4299. if ( index !== - 1 ) {
  4300. listenerArray.splice( index, 1 );
  4301. }
  4302. }
  4303. },
  4304. dispatchEvent: function ( event ) {
  4305. if ( this._listeners === undefined ) return;
  4306. var listeners = this._listeners;
  4307. var listenerArray = listeners[ event.type ];
  4308. if ( listenerArray !== undefined ) {
  4309. event.target = this;
  4310. var array = [], i = 0;
  4311. var length = listenerArray.length;
  4312. for ( i = 0; i < length; i ++ ) {
  4313. array[ i ] = listenerArray[ i ];
  4314. }
  4315. for ( i = 0; i < length; i ++ ) {
  4316. array[ i ].call( this, event );
  4317. }
  4318. }
  4319. }
  4320. } );
  4321. var REVISION = '83';
  4322. var MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2 };
  4323. var CullFaceNone = 0;
  4324. var CullFaceBack = 1;
  4325. var CullFaceFront = 2;
  4326. var CullFaceFrontBack = 3;
  4327. var FrontFaceDirectionCW = 0;
  4328. var FrontFaceDirectionCCW = 1;
  4329. var BasicShadowMap = 0;
  4330. var PCFShadowMap = 1;
  4331. var PCFSoftShadowMap = 2;
  4332. var FrontSide = 0;
  4333. var BackSide = 1;
  4334. var DoubleSide = 2;
  4335. var FlatShading = 1;
  4336. var SmoothShading = 2;
  4337. var NoColors = 0;
  4338. var FaceColors = 1;
  4339. var VertexColors = 2;
  4340. var NoBlending = 0;
  4341. var NormalBlending = 1;
  4342. var AdditiveBlending = 2;
  4343. var SubtractiveBlending = 3;
  4344. var MultiplyBlending = 4;
  4345. var CustomBlending = 5;
  4346. var BlendingMode = {
  4347. NoBlending: NoBlending,
  4348. NormalBlending: NormalBlending,
  4349. AdditiveBlending: AdditiveBlending,
  4350. SubtractiveBlending: SubtractiveBlending,
  4351. MultiplyBlending: MultiplyBlending,
  4352. CustomBlending: CustomBlending
  4353. };
  4354. var AddEquation = 100;
  4355. var SubtractEquation = 101;
  4356. var ReverseSubtractEquation = 102;
  4357. var MinEquation = 103;
  4358. var MaxEquation = 104;
  4359. var ZeroFactor = 200;
  4360. var OneFactor = 201;
  4361. var SrcColorFactor = 202;
  4362. var OneMinusSrcColorFactor = 203;
  4363. var SrcAlphaFactor = 204;
  4364. var OneMinusSrcAlphaFactor = 205;
  4365. var DstAlphaFactor = 206;
  4366. var OneMinusDstAlphaFactor = 207;
  4367. var DstColorFactor = 208;
  4368. var OneMinusDstColorFactor = 209;
  4369. var SrcAlphaSaturateFactor = 210;
  4370. var NeverDepth = 0;
  4371. var AlwaysDepth = 1;
  4372. var LessDepth = 2;
  4373. var LessEqualDepth = 3;
  4374. var EqualDepth = 4;
  4375. var GreaterEqualDepth = 5;
  4376. var GreaterDepth = 6;
  4377. var NotEqualDepth = 7;
  4378. var MultiplyOperation = 0;
  4379. var MixOperation = 1;
  4380. var AddOperation = 2;
  4381. var NoToneMapping = 0;
  4382. var LinearToneMapping = 1;
  4383. var ReinhardToneMapping = 2;
  4384. var Uncharted2ToneMapping = 3;
  4385. var CineonToneMapping = 4;
  4386. var UVMapping = 300;
  4387. var CubeReflectionMapping = 301;
  4388. var CubeRefractionMapping = 302;
  4389. var EquirectangularReflectionMapping = 303;
  4390. var EquirectangularRefractionMapping = 304;
  4391. var SphericalReflectionMapping = 305;
  4392. var CubeUVReflectionMapping = 306;
  4393. var CubeUVRefractionMapping = 307;
  4394. var TextureMapping = {
  4395. UVMapping: UVMapping,
  4396. CubeReflectionMapping: CubeReflectionMapping,
  4397. CubeRefractionMapping: CubeRefractionMapping,
  4398. EquirectangularReflectionMapping: EquirectangularReflectionMapping,
  4399. EquirectangularRefractionMapping: EquirectangularRefractionMapping,
  4400. SphericalReflectionMapping: SphericalReflectionMapping,
  4401. CubeUVReflectionMapping: CubeUVReflectionMapping,
  4402. CubeUVRefractionMapping: CubeUVRefractionMapping
  4403. };
  4404. var RepeatWrapping = 1000;
  4405. var ClampToEdgeWrapping = 1001;
  4406. var MirroredRepeatWrapping = 1002;
  4407. var TextureWrapping = {
  4408. RepeatWrapping: RepeatWrapping,
  4409. ClampToEdgeWrapping: ClampToEdgeWrapping,
  4410. MirroredRepeatWrapping: MirroredRepeatWrapping
  4411. };
  4412. var NearestFilter = 1003;
  4413. var NearestMipMapNearestFilter = 1004;
  4414. var NearestMipMapLinearFilter = 1005;
  4415. var LinearFilter = 1006;
  4416. var LinearMipMapNearestFilter = 1007;
  4417. var LinearMipMapLinearFilter = 1008;
  4418. var TextureFilter = {
  4419. NearestFilter: NearestFilter,
  4420. NearestMipMapNearestFilter: NearestMipMapNearestFilter,
  4421. NearestMipMapLinearFilter: NearestMipMapLinearFilter,
  4422. LinearFilter: LinearFilter,
  4423. LinearMipMapNearestFilter: LinearMipMapNearestFilter,
  4424. LinearMipMapLinearFilter: LinearMipMapLinearFilter
  4425. };
  4426. var UnsignedByteType = 1009;
  4427. var ByteType = 1010;
  4428. var ShortType = 1011;
  4429. var UnsignedShortType = 1012;
  4430. var IntType = 1013;
  4431. var UnsignedIntType = 1014;
  4432. var FloatType = 1015;
  4433. var HalfFloatType = 1016;
  4434. var UnsignedShort4444Type = 1017;
  4435. var UnsignedShort5551Type = 1018;
  4436. var UnsignedShort565Type = 1019;
  4437. var UnsignedInt248Type = 1020;
  4438. var AlphaFormat = 1021;
  4439. var RGBFormat = 1022;
  4440. var RGBAFormat = 1023;
  4441. var LuminanceFormat = 1024;
  4442. var LuminanceAlphaFormat = 1025;
  4443. var RGBEFormat = RGBAFormat;
  4444. var DepthFormat = 1026;
  4445. var DepthStencilFormat = 1027;
  4446. var RGB_S3TC_DXT1_Format = 2001;
  4447. var RGBA_S3TC_DXT1_Format = 2002;
  4448. var RGBA_S3TC_DXT3_Format = 2003;
  4449. var RGBA_S3TC_DXT5_Format = 2004;
  4450. var RGB_PVRTC_4BPPV1_Format = 2100;
  4451. var RGB_PVRTC_2BPPV1_Format = 2101;
  4452. var RGBA_PVRTC_4BPPV1_Format = 2102;
  4453. var RGBA_PVRTC_2BPPV1_Format = 2103;
  4454. var RGB_ETC1_Format = 2151;
  4455. var LoopOnce = 2200;
  4456. var LoopRepeat = 2201;
  4457. var LoopPingPong = 2202;
  4458. var InterpolateDiscrete = 2300;
  4459. var InterpolateLinear = 2301;
  4460. var InterpolateSmooth = 2302;
  4461. var ZeroCurvatureEnding = 2400;
  4462. var ZeroSlopeEnding = 2401;
  4463. var WrapAroundEnding = 2402;
  4464. var TrianglesDrawMode = 0;
  4465. var TriangleStripDrawMode = 1;
  4466. var TriangleFanDrawMode = 2;
  4467. var LinearEncoding = 3000;
  4468. var sRGBEncoding = 3001;
  4469. var GammaEncoding = 3007;
  4470. var RGBEEncoding = 3002;
  4471. var LogLuvEncoding = 3003;
  4472. var RGBM7Encoding = 3004;
  4473. var RGBM16Encoding = 3005;
  4474. var RGBDEncoding = 3006;
  4475. var BasicDepthPacking = 3200;
  4476. var RGBADepthPacking = 3201;
  4477. /**
  4478. * @author alteredq / http://alteredqualia.com/
  4479. * @author mrdoob / http://mrdoob.com/
  4480. */
  4481. var _Math = {
  4482. DEG2RAD: Math.PI / 180,
  4483. RAD2DEG: 180 / Math.PI,
  4484. generateUUID: function () {
  4485. // http://www.broofa.com/Tools/Math.uuid.htm
  4486. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split( '' );
  4487. var uuid = new Array( 36 );
  4488. var rnd = 0, r;
  4489. return function generateUUID() {
  4490. for ( var i = 0; i < 36; i ++ ) {
  4491. if ( i === 8 || i === 13 || i === 18 || i === 23 ) {
  4492. uuid[ i ] = '-';
  4493. } else if ( i === 14 ) {
  4494. uuid[ i ] = '4';
  4495. } else {
  4496. if ( rnd <= 0x02 ) rnd = 0x2000000 + ( Math.random() * 0x1000000 ) | 0;
  4497. r = rnd & 0xf;
  4498. rnd = rnd >> 4;
  4499. uuid[ i ] = chars[ ( i === 19 ) ? ( r & 0x3 ) | 0x8 : r ];
  4500. }
  4501. }
  4502. return uuid.join( '' );
  4503. };
  4504. }(),
  4505. clamp: function ( value, min, max ) {
  4506. return Math.max( min, Math.min( max, value ) );
  4507. },
  4508. // compute euclidian modulo of m % n
  4509. // https://en.wikipedia.org/wiki/Modulo_operation
  4510. euclideanModulo: function ( n, m ) {
  4511. return ( ( n % m ) + m ) % m;
  4512. },
  4513. // Linear mapping from range <a1, a2> to range <b1, b2>
  4514. mapLinear: function ( x, a1, a2, b1, b2 ) {
  4515. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  4516. },
  4517. // https://en.wikipedia.org/wiki/Linear_interpolation
  4518. lerp: function ( x, y, t ) {
  4519. return ( 1 - t ) * x + t * y;
  4520. },
  4521. // http://en.wikipedia.org/wiki/Smoothstep
  4522. smoothstep: function ( x, min, max ) {
  4523. if ( x <= min ) return 0;
  4524. if ( x >= max ) return 1;
  4525. x = ( x - min ) / ( max - min );
  4526. return x * x * ( 3 - 2 * x );
  4527. },
  4528. smootherstep: function ( x, min, max ) {
  4529. if ( x <= min ) return 0;
  4530. if ( x >= max ) return 1;
  4531. x = ( x - min ) / ( max - min );
  4532. return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
  4533. },
  4534. // Random integer from <low, high> interval
  4535. randInt: function ( low, high ) {
  4536. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  4537. },
  4538. // Random float from <low, high> interval
  4539. randFloat: function ( low, high ) {
  4540. return low + Math.random() * ( high - low );
  4541. },
  4542. // Random float from <-range/2, range/2> interval
  4543. randFloatSpread: function ( range ) {
  4544. return range * ( 0.5 - Math.random() );
  4545. },
  4546. degToRad: function ( degrees ) {
  4547. return degrees * _Math.DEG2RAD;
  4548. },
  4549. radToDeg: function ( radians ) {
  4550. return radians * _Math.RAD2DEG;
  4551. },
  4552. isPowerOfTwo: function ( value ) {
  4553. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  4554. },
  4555. nearestPowerOfTwo: function ( value ) {
  4556. return Math.pow( 2, Math.round( Math.log( value ) / Math.LN2 ) );
  4557. },
  4558. nextPowerOfTwo: function ( value ) {
  4559. value --;
  4560. value |= value >> 1;
  4561. value |= value >> 2;
  4562. value |= value >> 4;
  4563. value |= value >> 8;
  4564. value |= value >> 16;
  4565. value ++;
  4566. return value;
  4567. }
  4568. };
  4569. /**
  4570. * @author mrdoob / http://mrdoob.com/
  4571. * @author philogb / http://blog.thejit.org/
  4572. * @author egraether / http://egraether.com/
  4573. * @author zz85 / http://www.lab4games.net/zz85/blog
  4574. */
  4575. function Vector2( x, y ) {
  4576. this.x = x || 0;
  4577. this.y = y || 0;
  4578. }
  4579. Vector2.prototype = {
  4580. constructor: Vector2,
  4581. isVector2: true,
  4582. get width() {
  4583. return this.x;
  4584. },
  4585. set width( value ) {
  4586. this.x = value;
  4587. },
  4588. get height() {
  4589. return this.y;
  4590. },
  4591. set height( value ) {
  4592. this.y = value;
  4593. },
  4594. //
  4595. set: function ( x, y ) {
  4596. this.x = x;
  4597. this.y = y;
  4598. return this;
  4599. },
  4600. setScalar: function ( scalar ) {
  4601. this.x = scalar;
  4602. this.y = scalar;
  4603. return this;
  4604. },
  4605. setX: function ( x ) {
  4606. this.x = x;
  4607. return this;
  4608. },
  4609. setY: function ( y ) {
  4610. this.y = y;
  4611. return this;
  4612. },
  4613. setComponent: function ( index, value ) {
  4614. switch ( index ) {
  4615. case 0: this.x = value; break;
  4616. case 1: this.y = value; break;
  4617. default: throw new Error( 'index is out of range: ' + index );
  4618. }
  4619. return this;
  4620. },
  4621. getComponent: function ( index ) {
  4622. switch ( index ) {
  4623. case 0: return this.x;
  4624. case 1: return this.y;
  4625. default: throw new Error( 'index is out of range: ' + index );
  4626. }
  4627. },
  4628. clone: function () {
  4629. return new this.constructor( this.x, this.y );
  4630. },
  4631. copy: function ( v ) {
  4632. this.x = v.x;
  4633. this.y = v.y;
  4634. return this;
  4635. },
  4636. add: function ( v, w ) {
  4637. if ( w !== undefined ) {
  4638. console.warn( 'THREE.Vector2: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  4639. return this.addVectors( v, w );
  4640. }
  4641. this.x += v.x;
  4642. this.y += v.y;
  4643. return this;
  4644. },
  4645. addScalar: function ( s ) {
  4646. this.x += s;
  4647. this.y += s;
  4648. return this;
  4649. },
  4650. addVectors: function ( a, b ) {
  4651. this.x = a.x + b.x;
  4652. this.y = a.y + b.y;
  4653. return this;
  4654. },
  4655. addScaledVector: function ( v, s ) {
  4656. this.x += v.x * s;
  4657. this.y += v.y * s;
  4658. return this;
  4659. },
  4660. sub: function ( v, w ) {
  4661. if ( w !== undefined ) {
  4662. console.warn( 'THREE.Vector2: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  4663. return this.subVectors( v, w );
  4664. }
  4665. this.x -= v.x;
  4666. this.y -= v.y;
  4667. return this;
  4668. },
  4669. subScalar: function ( s ) {
  4670. this.x -= s;
  4671. this.y -= s;
  4672. return this;
  4673. },
  4674. subVectors: function ( a, b ) {
  4675. this.x = a.x - b.x;
  4676. this.y = a.y - b.y;
  4677. return this;
  4678. },
  4679. multiply: function ( v ) {
  4680. this.x *= v.x;
  4681. this.y *= v.y;
  4682. return this;
  4683. },
  4684. multiplyScalar: function ( scalar ) {
  4685. if ( isFinite( scalar ) ) {
  4686. this.x *= scalar;
  4687. this.y *= scalar;
  4688. } else {
  4689. this.x = 0;
  4690. this.y = 0;
  4691. }
  4692. return this;
  4693. },
  4694. divide: function ( v ) {
  4695. this.x /= v.x;
  4696. this.y /= v.y;
  4697. return this;
  4698. },
  4699. divideScalar: function ( scalar ) {
  4700. return this.multiplyScalar( 1 / scalar );
  4701. },
  4702. min: function ( v ) {
  4703. this.x = Math.min( this.x, v.x );
  4704. this.y = Math.min( this.y, v.y );
  4705. return this;
  4706. },
  4707. max: function ( v ) {
  4708. this.x = Math.max( this.x, v.x );
  4709. this.y = Math.max( this.y, v.y );
  4710. return this;
  4711. },
  4712. clamp: function ( min, max ) {
  4713. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  4714. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  4715. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  4716. return this;
  4717. },
  4718. clampScalar: function () {
  4719. var min, max;
  4720. return function clampScalar( minVal, maxVal ) {
  4721. if ( min === undefined ) {
  4722. min = new Vector2();
  4723. max = new Vector2();
  4724. }
  4725. min.set( minVal, minVal );
  4726. max.set( maxVal, maxVal );
  4727. return this.clamp( min, max );
  4728. };
  4729. }(),
  4730. clampLength: function ( min, max ) {
  4731. var length = this.length();
  4732. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  4733. },
  4734. floor: function () {
  4735. this.x = Math.floor( this.x );
  4736. this.y = Math.floor( this.y );
  4737. return this;
  4738. },
  4739. ceil: function () {
  4740. this.x = Math.ceil( this.x );
  4741. this.y = Math.ceil( this.y );
  4742. return this;
  4743. },
  4744. round: function () {
  4745. this.x = Math.round( this.x );
  4746. this.y = Math.round( this.y );
  4747. return this;
  4748. },
  4749. roundToZero: function () {
  4750. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  4751. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  4752. return this;
  4753. },
  4754. negate: function () {
  4755. this.x = - this.x;
  4756. this.y = - this.y;
  4757. return this;
  4758. },
  4759. dot: function ( v ) {
  4760. return this.x * v.x + this.y * v.y;
  4761. },
  4762. lengthSq: function () {
  4763. return this.x * this.x + this.y * this.y;
  4764. },
  4765. length: function () {
  4766. return Math.sqrt( this.x * this.x + this.y * this.y );
  4767. },
  4768. lengthManhattan: function() {
  4769. return Math.abs( this.x ) + Math.abs( this.y );
  4770. },
  4771. normalize: function () {
  4772. return this.divideScalar( this.length() );
  4773. },
  4774. angle: function () {
  4775. // computes the angle in radians with respect to the positive x-axis
  4776. var angle = Math.atan2( this.y, this.x );
  4777. if ( angle < 0 ) angle += 2 * Math.PI;
  4778. return angle;
  4779. },
  4780. distanceTo: function ( v ) {
  4781. return Math.sqrt( this.distanceToSquared( v ) );
  4782. },
  4783. distanceToSquared: function ( v ) {
  4784. var dx = this.x - v.x, dy = this.y - v.y;
  4785. return dx * dx + dy * dy;
  4786. },
  4787. distanceToManhattan: function ( v ) {
  4788. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y );
  4789. },
  4790. setLength: function ( length ) {
  4791. return this.multiplyScalar( length / this.length() );
  4792. },
  4793. lerp: function ( v, alpha ) {
  4794. this.x += ( v.x - this.x ) * alpha;
  4795. this.y += ( v.y - this.y ) * alpha;
  4796. return this;
  4797. },
  4798. lerpVectors: function ( v1, v2, alpha ) {
  4799. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  4800. },
  4801. equals: function ( v ) {
  4802. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  4803. },
  4804. fromArray: function ( array, offset ) {
  4805. if ( offset === undefined ) offset = 0;
  4806. this.x = array[ offset ];
  4807. this.y = array[ offset + 1 ];
  4808. return this;
  4809. },
  4810. toArray: function ( array, offset ) {
  4811. if ( array === undefined ) array = [];
  4812. if ( offset === undefined ) offset = 0;
  4813. array[ offset ] = this.x;
  4814. array[ offset + 1 ] = this.y;
  4815. return array;
  4816. },
  4817. fromAttribute: function ( attribute, index, offset ) {
  4818. if ( offset !== undefined ) {
  4819. console.warn( 'THREE.Vector2: offset has been removed from .fromAttribute().' );
  4820. }
  4821. this.x = attribute.getX( index );
  4822. this.y = attribute.getY( index );
  4823. return this;
  4824. },
  4825. rotateAround: function ( center, angle ) {
  4826. var c = Math.cos( angle ), s = Math.sin( angle );
  4827. var x = this.x - center.x;
  4828. var y = this.y - center.y;
  4829. this.x = x * c - y * s + center.x;
  4830. this.y = x * s + y * c + center.y;
  4831. return this;
  4832. }
  4833. };
  4834. /**
  4835. * @author mrdoob / http://mrdoob.com/
  4836. * @author alteredq / http://alteredqualia.com/
  4837. * @author szimek / https://github.com/szimek/
  4838. */
  4839. var textureId = 0;
  4840. function Texture( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  4841. Object.defineProperty( this, 'id', { value: textureId ++ } );
  4842. this.uuid = _Math.generateUUID();
  4843. this.name = '';
  4844. this.image = image !== undefined ? image : Texture.DEFAULT_IMAGE;
  4845. this.mipmaps = [];
  4846. this.mapping = mapping !== undefined ? mapping : Texture.DEFAULT_MAPPING;
  4847. this.wrapS = wrapS !== undefined ? wrapS : ClampToEdgeWrapping;
  4848. this.wrapT = wrapT !== undefined ? wrapT : ClampToEdgeWrapping;
  4849. this.magFilter = magFilter !== undefined ? magFilter : LinearFilter;
  4850. this.minFilter = minFilter !== undefined ? minFilter : LinearMipMapLinearFilter;
  4851. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  4852. this.format = format !== undefined ? format : RGBAFormat;
  4853. this.type = type !== undefined ? type : UnsignedByteType;
  4854. this.offset = new Vector2( 0, 0 );
  4855. this.repeat = new Vector2( 1, 1 );
  4856. this.generateMipmaps = true;
  4857. this.premultiplyAlpha = false;
  4858. this.flipY = true;
  4859. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  4860. // Values of encoding !== THREE.LinearEncoding only supported on map, envMap and emissiveMap.
  4861. //
  4862. // Also changing the encoding after already used by a Material will not automatically make the Material
  4863. // update. You need to explicitly call Material.needsUpdate to trigger it to recompile.
  4864. this.encoding = encoding !== undefined ? encoding : LinearEncoding;
  4865. this.version = 0;
  4866. this.onUpdate = null;
  4867. }
  4868. Texture.DEFAULT_IMAGE = undefined;
  4869. Texture.DEFAULT_MAPPING = UVMapping;
  4870. Texture.prototype = {
  4871. constructor: Texture,
  4872. isTexture: true,
  4873. set needsUpdate( value ) {
  4874. if ( value === true ) this.version ++;
  4875. },
  4876. clone: function () {
  4877. return new this.constructor().copy( this );
  4878. },
  4879. copy: function ( source ) {
  4880. this.image = source.image;
  4881. this.mipmaps = source.mipmaps.slice( 0 );
  4882. this.mapping = source.mapping;
  4883. this.wrapS = source.wrapS;
  4884. this.wrapT = source.wrapT;
  4885. this.magFilter = source.magFilter;
  4886. this.minFilter = source.minFilter;
  4887. this.anisotropy = source.anisotropy;
  4888. this.format = source.format;
  4889. this.type = source.type;
  4890. this.offset.copy( source.offset );
  4891. this.repeat.copy( source.repeat );
  4892. this.generateMipmaps = source.generateMipmaps;
  4893. this.premultiplyAlpha = source.premultiplyAlpha;
  4894. this.flipY = source.flipY;
  4895. this.unpackAlignment = source.unpackAlignment;
  4896. this.encoding = source.encoding;
  4897. return this;
  4898. },
  4899. toJSON: function ( meta ) {
  4900. if ( meta.textures[ this.uuid ] !== undefined ) {
  4901. return meta.textures[ this.uuid ];
  4902. }
  4903. function getDataURL( image ) {
  4904. var canvas;
  4905. if ( image.toDataURL !== undefined ) {
  4906. canvas = image;
  4907. } else {
  4908. canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  4909. canvas.width = image.width;
  4910. canvas.height = image.height;
  4911. canvas.getContext( '2d' ).drawImage( image, 0, 0, image.width, image.height );
  4912. }
  4913. if ( canvas.width > 2048 || canvas.height > 2048 ) {
  4914. return canvas.toDataURL( 'image/jpeg', 0.6 );
  4915. } else {
  4916. return canvas.toDataURL( 'image/png' );
  4917. }
  4918. }
  4919. var output = {
  4920. metadata: {
  4921. version: 4.4,
  4922. type: 'Texture',
  4923. generator: 'Texture.toJSON'
  4924. },
  4925. uuid: this.uuid,
  4926. name: this.name,
  4927. mapping: this.mapping,
  4928. repeat: [ this.repeat.x, this.repeat.y ],
  4929. offset: [ this.offset.x, this.offset.y ],
  4930. wrap: [ this.wrapS, this.wrapT ],
  4931. minFilter: this.minFilter,
  4932. magFilter: this.magFilter,
  4933. anisotropy: this.anisotropy,
  4934. flipY: this.flipY
  4935. };
  4936. if ( this.image !== undefined ) {
  4937. // TODO: Move to THREE.Image
  4938. var image = this.image;
  4939. if ( image.uuid === undefined ) {
  4940. image.uuid = _Math.generateUUID(); // UGH
  4941. }
  4942. if ( meta.images[ image.uuid ] === undefined ) {
  4943. meta.images[ image.uuid ] = {
  4944. uuid: image.uuid,
  4945. url: getDataURL( image )
  4946. };
  4947. }
  4948. output.image = image.uuid;
  4949. }
  4950. meta.textures[ this.uuid ] = output;
  4951. return output;
  4952. },
  4953. dispose: function () {
  4954. this.dispatchEvent( { type: 'dispose' } );
  4955. },
  4956. transformUv: function ( uv ) {
  4957. if ( this.mapping !== UVMapping ) return;
  4958. uv.multiply( this.repeat );
  4959. uv.add( this.offset );
  4960. if ( uv.x < 0 || uv.x > 1 ) {
  4961. switch ( this.wrapS ) {
  4962. case RepeatWrapping:
  4963. uv.x = uv.x - Math.floor( uv.x );
  4964. break;
  4965. case ClampToEdgeWrapping:
  4966. uv.x = uv.x < 0 ? 0 : 1;
  4967. break;
  4968. case MirroredRepeatWrapping:
  4969. if ( Math.abs( Math.floor( uv.x ) % 2 ) === 1 ) {
  4970. uv.x = Math.ceil( uv.x ) - uv.x;
  4971. } else {
  4972. uv.x = uv.x - Math.floor( uv.x );
  4973. }
  4974. break;
  4975. }
  4976. }
  4977. if ( uv.y < 0 || uv.y > 1 ) {
  4978. switch ( this.wrapT ) {
  4979. case RepeatWrapping:
  4980. uv.y = uv.y - Math.floor( uv.y );
  4981. break;
  4982. case ClampToEdgeWrapping:
  4983. uv.y = uv.y < 0 ? 0 : 1;
  4984. break;
  4985. case MirroredRepeatWrapping:
  4986. if ( Math.abs( Math.floor( uv.y ) % 2 ) === 1 ) {
  4987. uv.y = Math.ceil( uv.y ) - uv.y;
  4988. } else {
  4989. uv.y = uv.y - Math.floor( uv.y );
  4990. }
  4991. break;
  4992. }
  4993. }
  4994. if ( this.flipY ) {
  4995. uv.y = 1 - uv.y;
  4996. }
  4997. }
  4998. };
  4999. Object.assign( Texture.prototype, EventDispatcher.prototype );
  5000. /**
  5001. * @author supereggbert / http://www.paulbrunt.co.uk/
  5002. * @author philogb / http://blog.thejit.org/
  5003. * @author mikael emtinger / http://gomo.se/
  5004. * @author egraether / http://egraether.com/
  5005. * @author WestLangley / http://github.com/WestLangley
  5006. */
  5007. function Vector4( x, y, z, w ) {
  5008. this.x = x || 0;
  5009. this.y = y || 0;
  5010. this.z = z || 0;
  5011. this.w = ( w !== undefined ) ? w : 1;
  5012. }
  5013. Vector4.prototype = {
  5014. constructor: Vector4,
  5015. isVector4: true,
  5016. set: function ( x, y, z, w ) {
  5017. this.x = x;
  5018. this.y = y;
  5019. this.z = z;
  5020. this.w = w;
  5021. return this;
  5022. },
  5023. setScalar: function ( scalar ) {
  5024. this.x = scalar;
  5025. this.y = scalar;
  5026. this.z = scalar;
  5027. this.w = scalar;
  5028. return this;
  5029. },
  5030. setX: function ( x ) {
  5031. this.x = x;
  5032. return this;
  5033. },
  5034. setY: function ( y ) {
  5035. this.y = y;
  5036. return this;
  5037. },
  5038. setZ: function ( z ) {
  5039. this.z = z;
  5040. return this;
  5041. },
  5042. setW: function ( w ) {
  5043. this.w = w;
  5044. return this;
  5045. },
  5046. setComponent: function ( index, value ) {
  5047. switch ( index ) {
  5048. case 0: this.x = value; break;
  5049. case 1: this.y = value; break;
  5050. case 2: this.z = value; break;
  5051. case 3: this.w = value; break;
  5052. default: throw new Error( 'index is out of range: ' + index );
  5053. }
  5054. return this;
  5055. },
  5056. getComponent: function ( index ) {
  5057. switch ( index ) {
  5058. case 0: return this.x;
  5059. case 1: return this.y;
  5060. case 2: return this.z;
  5061. case 3: return this.w;
  5062. default: throw new Error( 'index is out of range: ' + index );
  5063. }
  5064. },
  5065. clone: function () {
  5066. return new this.constructor( this.x, this.y, this.z, this.w );
  5067. },
  5068. copy: function ( v ) {
  5069. this.x = v.x;
  5070. this.y = v.y;
  5071. this.z = v.z;
  5072. this.w = ( v.w !== undefined ) ? v.w : 1;
  5073. return this;
  5074. },
  5075. add: function ( v, w ) {
  5076. if ( w !== undefined ) {
  5077. console.warn( 'THREE.Vector4: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5078. return this.addVectors( v, w );
  5079. }
  5080. this.x += v.x;
  5081. this.y += v.y;
  5082. this.z += v.z;
  5083. this.w += v.w;
  5084. return this;
  5085. },
  5086. addScalar: function ( s ) {
  5087. this.x += s;
  5088. this.y += s;
  5089. this.z += s;
  5090. this.w += s;
  5091. return this;
  5092. },
  5093. addVectors: function ( a, b ) {
  5094. this.x = a.x + b.x;
  5095. this.y = a.y + b.y;
  5096. this.z = a.z + b.z;
  5097. this.w = a.w + b.w;
  5098. return this;
  5099. },
  5100. addScaledVector: function ( v, s ) {
  5101. this.x += v.x * s;
  5102. this.y += v.y * s;
  5103. this.z += v.z * s;
  5104. this.w += v.w * s;
  5105. return this;
  5106. },
  5107. sub: function ( v, w ) {
  5108. if ( w !== undefined ) {
  5109. console.warn( 'THREE.Vector4: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5110. return this.subVectors( v, w );
  5111. }
  5112. this.x -= v.x;
  5113. this.y -= v.y;
  5114. this.z -= v.z;
  5115. this.w -= v.w;
  5116. return this;
  5117. },
  5118. subScalar: function ( s ) {
  5119. this.x -= s;
  5120. this.y -= s;
  5121. this.z -= s;
  5122. this.w -= s;
  5123. return this;
  5124. },
  5125. subVectors: function ( a, b ) {
  5126. this.x = a.x - b.x;
  5127. this.y = a.y - b.y;
  5128. this.z = a.z - b.z;
  5129. this.w = a.w - b.w;
  5130. return this;
  5131. },
  5132. multiplyScalar: function ( scalar ) {
  5133. if ( isFinite( scalar ) ) {
  5134. this.x *= scalar;
  5135. this.y *= scalar;
  5136. this.z *= scalar;
  5137. this.w *= scalar;
  5138. } else {
  5139. this.x = 0;
  5140. this.y = 0;
  5141. this.z = 0;
  5142. this.w = 0;
  5143. }
  5144. return this;
  5145. },
  5146. applyMatrix4: function ( m ) {
  5147. var x = this.x, y = this.y, z = this.z, w = this.w;
  5148. var e = m.elements;
  5149. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] * w;
  5150. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] * w;
  5151. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] * w;
  5152. this.w = e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] * w;
  5153. return this;
  5154. },
  5155. divideScalar: function ( scalar ) {
  5156. return this.multiplyScalar( 1 / scalar );
  5157. },
  5158. setAxisAngleFromQuaternion: function ( q ) {
  5159. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  5160. // q is assumed to be normalized
  5161. this.w = 2 * Math.acos( q.w );
  5162. var s = Math.sqrt( 1 - q.w * q.w );
  5163. if ( s < 0.0001 ) {
  5164. this.x = 1;
  5165. this.y = 0;
  5166. this.z = 0;
  5167. } else {
  5168. this.x = q.x / s;
  5169. this.y = q.y / s;
  5170. this.z = q.z / s;
  5171. }
  5172. return this;
  5173. },
  5174. setAxisAngleFromRotationMatrix: function ( m ) {
  5175. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  5176. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5177. var angle, x, y, z, // variables for result
  5178. epsilon = 0.01, // margin to allow for rounding errors
  5179. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  5180. te = m.elements,
  5181. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5182. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5183. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  5184. if ( ( Math.abs( m12 - m21 ) < epsilon ) &&
  5185. ( Math.abs( m13 - m31 ) < epsilon ) &&
  5186. ( Math.abs( m23 - m32 ) < epsilon ) ) {
  5187. // singularity found
  5188. // first check for identity matrix which must have +1 for all terms
  5189. // in leading diagonal and zero in other terms
  5190. if ( ( Math.abs( m12 + m21 ) < epsilon2 ) &&
  5191. ( Math.abs( m13 + m31 ) < epsilon2 ) &&
  5192. ( Math.abs( m23 + m32 ) < epsilon2 ) &&
  5193. ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  5194. // this singularity is identity matrix so angle = 0
  5195. this.set( 1, 0, 0, 0 );
  5196. return this; // zero angle, arbitrary axis
  5197. }
  5198. // otherwise this singularity is angle = 180
  5199. angle = Math.PI;
  5200. var xx = ( m11 + 1 ) / 2;
  5201. var yy = ( m22 + 1 ) / 2;
  5202. var zz = ( m33 + 1 ) / 2;
  5203. var xy = ( m12 + m21 ) / 4;
  5204. var xz = ( m13 + m31 ) / 4;
  5205. var yz = ( m23 + m32 ) / 4;
  5206. if ( ( xx > yy ) && ( xx > zz ) ) {
  5207. // m11 is the largest diagonal term
  5208. if ( xx < epsilon ) {
  5209. x = 0;
  5210. y = 0.707106781;
  5211. z = 0.707106781;
  5212. } else {
  5213. x = Math.sqrt( xx );
  5214. y = xy / x;
  5215. z = xz / x;
  5216. }
  5217. } else if ( yy > zz ) {
  5218. // m22 is the largest diagonal term
  5219. if ( yy < epsilon ) {
  5220. x = 0.707106781;
  5221. y = 0;
  5222. z = 0.707106781;
  5223. } else {
  5224. y = Math.sqrt( yy );
  5225. x = xy / y;
  5226. z = yz / y;
  5227. }
  5228. } else {
  5229. // m33 is the largest diagonal term so base result on this
  5230. if ( zz < epsilon ) {
  5231. x = 0.707106781;
  5232. y = 0.707106781;
  5233. z = 0;
  5234. } else {
  5235. z = Math.sqrt( zz );
  5236. x = xz / z;
  5237. y = yz / z;
  5238. }
  5239. }
  5240. this.set( x, y, z, angle );
  5241. return this; // return 180 deg rotation
  5242. }
  5243. // as we have reached here there are no singularities so we can handle normally
  5244. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 ) +
  5245. ( m13 - m31 ) * ( m13 - m31 ) +
  5246. ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  5247. if ( Math.abs( s ) < 0.001 ) s = 1;
  5248. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  5249. // caught by singularity test above, but I've left it in just in case
  5250. this.x = ( m32 - m23 ) / s;
  5251. this.y = ( m13 - m31 ) / s;
  5252. this.z = ( m21 - m12 ) / s;
  5253. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  5254. return this;
  5255. },
  5256. min: function ( v ) {
  5257. this.x = Math.min( this.x, v.x );
  5258. this.y = Math.min( this.y, v.y );
  5259. this.z = Math.min( this.z, v.z );
  5260. this.w = Math.min( this.w, v.w );
  5261. return this;
  5262. },
  5263. max: function ( v ) {
  5264. this.x = Math.max( this.x, v.x );
  5265. this.y = Math.max( this.y, v.y );
  5266. this.z = Math.max( this.z, v.z );
  5267. this.w = Math.max( this.w, v.w );
  5268. return this;
  5269. },
  5270. clamp: function ( min, max ) {
  5271. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  5272. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  5273. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  5274. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  5275. this.w = Math.max( min.w, Math.min( max.w, this.w ) );
  5276. return this;
  5277. },
  5278. clampScalar: function () {
  5279. var min, max;
  5280. return function clampScalar( minVal, maxVal ) {
  5281. if ( min === undefined ) {
  5282. min = new Vector4();
  5283. max = new Vector4();
  5284. }
  5285. min.set( minVal, minVal, minVal, minVal );
  5286. max.set( maxVal, maxVal, maxVal, maxVal );
  5287. return this.clamp( min, max );
  5288. };
  5289. }(),
  5290. floor: function () {
  5291. this.x = Math.floor( this.x );
  5292. this.y = Math.floor( this.y );
  5293. this.z = Math.floor( this.z );
  5294. this.w = Math.floor( this.w );
  5295. return this;
  5296. },
  5297. ceil: function () {
  5298. this.x = Math.ceil( this.x );
  5299. this.y = Math.ceil( this.y );
  5300. this.z = Math.ceil( this.z );
  5301. this.w = Math.ceil( this.w );
  5302. return this;
  5303. },
  5304. round: function () {
  5305. this.x = Math.round( this.x );
  5306. this.y = Math.round( this.y );
  5307. this.z = Math.round( this.z );
  5308. this.w = Math.round( this.w );
  5309. return this;
  5310. },
  5311. roundToZero: function () {
  5312. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  5313. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  5314. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  5315. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  5316. return this;
  5317. },
  5318. negate: function () {
  5319. this.x = - this.x;
  5320. this.y = - this.y;
  5321. this.z = - this.z;
  5322. this.w = - this.w;
  5323. return this;
  5324. },
  5325. dot: function ( v ) {
  5326. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  5327. },
  5328. lengthSq: function () {
  5329. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  5330. },
  5331. length: function () {
  5332. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  5333. },
  5334. lengthManhattan: function () {
  5335. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  5336. },
  5337. normalize: function () {
  5338. return this.divideScalar( this.length() );
  5339. },
  5340. setLength: function ( length ) {
  5341. return this.multiplyScalar( length / this.length() );
  5342. },
  5343. lerp: function ( v, alpha ) {
  5344. this.x += ( v.x - this.x ) * alpha;
  5345. this.y += ( v.y - this.y ) * alpha;
  5346. this.z += ( v.z - this.z ) * alpha;
  5347. this.w += ( v.w - this.w ) * alpha;
  5348. return this;
  5349. },
  5350. lerpVectors: function ( v1, v2, alpha ) {
  5351. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  5352. },
  5353. equals: function ( v ) {
  5354. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  5355. },
  5356. fromArray: function ( array, offset ) {
  5357. if ( offset === undefined ) offset = 0;
  5358. this.x = array[ offset ];
  5359. this.y = array[ offset + 1 ];
  5360. this.z = array[ offset + 2 ];
  5361. this.w = array[ offset + 3 ];
  5362. return this;
  5363. },
  5364. toArray: function ( array, offset ) {
  5365. if ( array === undefined ) array = [];
  5366. if ( offset === undefined ) offset = 0;
  5367. array[ offset ] = this.x;
  5368. array[ offset + 1 ] = this.y;
  5369. array[ offset + 2 ] = this.z;
  5370. array[ offset + 3 ] = this.w;
  5371. return array;
  5372. },
  5373. fromAttribute: function ( attribute, index, offset ) {
  5374. if ( offset !== undefined ) {
  5375. console.warn( 'THREE.Vector4: offset has been removed from .fromAttribute().' );
  5376. }
  5377. this.x = attribute.getX( index );
  5378. this.y = attribute.getY( index );
  5379. this.z = attribute.getZ( index );
  5380. this.w = attribute.getW( index );
  5381. return this;
  5382. }
  5383. };
  5384. /**
  5385. * @author szimek / https://github.com/szimek/
  5386. * @author alteredq / http://alteredqualia.com/
  5387. * @author Marius Kintel / https://github.com/kintel
  5388. */
  5389. /*
  5390. In options, we can specify:
  5391. * Texture parameters for an auto-generated target texture
  5392. * depthBuffer/stencilBuffer: Booleans to indicate if we should generate these buffers
  5393. */
  5394. function WebGLRenderTarget( width, height, options ) {
  5395. this.uuid = _Math.generateUUID();
  5396. this.width = width;
  5397. this.height = height;
  5398. this.scissor = new Vector4( 0, 0, width, height );
  5399. this.scissorTest = false;
  5400. this.viewport = new Vector4( 0, 0, width, height );
  5401. options = options || {};
  5402. if ( options.minFilter === undefined ) options.minFilter = LinearFilter;
  5403. this.texture = new Texture( undefined, undefined, options.wrapS, options.wrapT, options.magFilter, options.minFilter, options.format, options.type, options.anisotropy, options.encoding );
  5404. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  5405. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  5406. this.depthTexture = options.depthTexture !== undefined ? options.depthTexture : null;
  5407. }
  5408. Object.assign( WebGLRenderTarget.prototype, EventDispatcher.prototype, {
  5409. isWebGLRenderTarget: true,
  5410. setSize: function ( width, height ) {
  5411. if ( this.width !== width || this.height !== height ) {
  5412. this.width = width;
  5413. this.height = height;
  5414. this.dispose();
  5415. }
  5416. this.viewport.set( 0, 0, width, height );
  5417. this.scissor.set( 0, 0, width, height );
  5418. },
  5419. clone: function () {
  5420. return new this.constructor().copy( this );
  5421. },
  5422. copy: function ( source ) {
  5423. this.width = source.width;
  5424. this.height = source.height;
  5425. this.viewport.copy( source.viewport );
  5426. this.texture = source.texture.clone();
  5427. this.depthBuffer = source.depthBuffer;
  5428. this.stencilBuffer = source.stencilBuffer;
  5429. this.depthTexture = source.depthTexture;
  5430. return this;
  5431. },
  5432. dispose: function () {
  5433. this.dispatchEvent( { type: 'dispose' } );
  5434. }
  5435. } );
  5436. /**
  5437. * @author alteredq / http://alteredqualia.com
  5438. */
  5439. function WebGLRenderTargetCube( width, height, options ) {
  5440. WebGLRenderTarget.call( this, width, height, options );
  5441. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  5442. this.activeMipMapLevel = 0;
  5443. }
  5444. WebGLRenderTargetCube.prototype = Object.create( WebGLRenderTarget.prototype );
  5445. WebGLRenderTargetCube.prototype.constructor = WebGLRenderTargetCube;
  5446. WebGLRenderTargetCube.prototype.isWebGLRenderTargetCube = true;
  5447. /**
  5448. * @author mikael emtinger / http://gomo.se/
  5449. * @author alteredq / http://alteredqualia.com/
  5450. * @author WestLangley / http://github.com/WestLangley
  5451. * @author bhouston / http://clara.io
  5452. */
  5453. function Quaternion( x, y, z, w ) {
  5454. this._x = x || 0;
  5455. this._y = y || 0;
  5456. this._z = z || 0;
  5457. this._w = ( w !== undefined ) ? w : 1;
  5458. }
  5459. Quaternion.prototype = {
  5460. constructor: Quaternion,
  5461. get x () {
  5462. return this._x;
  5463. },
  5464. set x ( value ) {
  5465. this._x = value;
  5466. this.onChangeCallback();
  5467. },
  5468. get y () {
  5469. return this._y;
  5470. },
  5471. set y ( value ) {
  5472. this._y = value;
  5473. this.onChangeCallback();
  5474. },
  5475. get z () {
  5476. return this._z;
  5477. },
  5478. set z ( value ) {
  5479. this._z = value;
  5480. this.onChangeCallback();
  5481. },
  5482. get w () {
  5483. return this._w;
  5484. },
  5485. set w ( value ) {
  5486. this._w = value;
  5487. this.onChangeCallback();
  5488. },
  5489. set: function ( x, y, z, w ) {
  5490. this._x = x;
  5491. this._y = y;
  5492. this._z = z;
  5493. this._w = w;
  5494. this.onChangeCallback();
  5495. return this;
  5496. },
  5497. clone: function () {
  5498. return new this.constructor( this._x, this._y, this._z, this._w );
  5499. },
  5500. copy: function ( quaternion ) {
  5501. this._x = quaternion.x;
  5502. this._y = quaternion.y;
  5503. this._z = quaternion.z;
  5504. this._w = quaternion.w;
  5505. this.onChangeCallback();
  5506. return this;
  5507. },
  5508. setFromEuler: function ( euler, update ) {
  5509. if ( (euler && euler.isEuler) === false ) {
  5510. throw new Error( 'THREE.Quaternion: .setFromEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5511. }
  5512. // http://www.mathworks.com/matlabcentral/fileexchange/
  5513. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  5514. // content/SpinCalc.m
  5515. var c1 = Math.cos( euler._x / 2 );
  5516. var c2 = Math.cos( euler._y / 2 );
  5517. var c3 = Math.cos( euler._z / 2 );
  5518. var s1 = Math.sin( euler._x / 2 );
  5519. var s2 = Math.sin( euler._y / 2 );
  5520. var s3 = Math.sin( euler._z / 2 );
  5521. var order = euler.order;
  5522. if ( order === 'XYZ' ) {
  5523. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5524. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5525. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5526. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5527. } else if ( order === 'YXZ' ) {
  5528. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5529. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5530. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5531. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5532. } else if ( order === 'ZXY' ) {
  5533. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5534. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5535. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5536. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5537. } else if ( order === 'ZYX' ) {
  5538. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5539. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5540. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5541. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5542. } else if ( order === 'YZX' ) {
  5543. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  5544. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  5545. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  5546. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  5547. } else if ( order === 'XZY' ) {
  5548. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  5549. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  5550. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  5551. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  5552. }
  5553. if ( update !== false ) this.onChangeCallback();
  5554. return this;
  5555. },
  5556. setFromAxisAngle: function ( axis, angle ) {
  5557. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  5558. // assumes axis is normalized
  5559. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  5560. this._x = axis.x * s;
  5561. this._y = axis.y * s;
  5562. this._z = axis.z * s;
  5563. this._w = Math.cos( halfAngle );
  5564. this.onChangeCallback();
  5565. return this;
  5566. },
  5567. setFromRotationMatrix: function ( m ) {
  5568. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  5569. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  5570. var te = m.elements,
  5571. m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ],
  5572. m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ],
  5573. m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ],
  5574. trace = m11 + m22 + m33,
  5575. s;
  5576. if ( trace > 0 ) {
  5577. s = 0.5 / Math.sqrt( trace + 1.0 );
  5578. this._w = 0.25 / s;
  5579. this._x = ( m32 - m23 ) * s;
  5580. this._y = ( m13 - m31 ) * s;
  5581. this._z = ( m21 - m12 ) * s;
  5582. } else if ( m11 > m22 && m11 > m33 ) {
  5583. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  5584. this._w = ( m32 - m23 ) / s;
  5585. this._x = 0.25 * s;
  5586. this._y = ( m12 + m21 ) / s;
  5587. this._z = ( m13 + m31 ) / s;
  5588. } else if ( m22 > m33 ) {
  5589. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  5590. this._w = ( m13 - m31 ) / s;
  5591. this._x = ( m12 + m21 ) / s;
  5592. this._y = 0.25 * s;
  5593. this._z = ( m23 + m32 ) / s;
  5594. } else {
  5595. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  5596. this._w = ( m21 - m12 ) / s;
  5597. this._x = ( m13 + m31 ) / s;
  5598. this._y = ( m23 + m32 ) / s;
  5599. this._z = 0.25 * s;
  5600. }
  5601. this.onChangeCallback();
  5602. return this;
  5603. },
  5604. setFromUnitVectors: function () {
  5605. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  5606. // assumes direction vectors vFrom and vTo are normalized
  5607. var v1, r;
  5608. var EPS = 0.000001;
  5609. return function setFromUnitVectors( vFrom, vTo ) {
  5610. if ( v1 === undefined ) v1 = new Vector3();
  5611. r = vFrom.dot( vTo ) + 1;
  5612. if ( r < EPS ) {
  5613. r = 0;
  5614. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  5615. v1.set( - vFrom.y, vFrom.x, 0 );
  5616. } else {
  5617. v1.set( 0, - vFrom.z, vFrom.y );
  5618. }
  5619. } else {
  5620. v1.crossVectors( vFrom, vTo );
  5621. }
  5622. this._x = v1.x;
  5623. this._y = v1.y;
  5624. this._z = v1.z;
  5625. this._w = r;
  5626. return this.normalize();
  5627. };
  5628. }(),
  5629. inverse: function () {
  5630. return this.conjugate().normalize();
  5631. },
  5632. conjugate: function () {
  5633. this._x *= - 1;
  5634. this._y *= - 1;
  5635. this._z *= - 1;
  5636. this.onChangeCallback();
  5637. return this;
  5638. },
  5639. dot: function ( v ) {
  5640. return this._x * v._x + this._y * v._y + this._z * v._z + this._w * v._w;
  5641. },
  5642. lengthSq: function () {
  5643. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  5644. },
  5645. length: function () {
  5646. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  5647. },
  5648. normalize: function () {
  5649. var l = this.length();
  5650. if ( l === 0 ) {
  5651. this._x = 0;
  5652. this._y = 0;
  5653. this._z = 0;
  5654. this._w = 1;
  5655. } else {
  5656. l = 1 / l;
  5657. this._x = this._x * l;
  5658. this._y = this._y * l;
  5659. this._z = this._z * l;
  5660. this._w = this._w * l;
  5661. }
  5662. this.onChangeCallback();
  5663. return this;
  5664. },
  5665. multiply: function ( q, p ) {
  5666. if ( p !== undefined ) {
  5667. console.warn( 'THREE.Quaternion: .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  5668. return this.multiplyQuaternions( q, p );
  5669. }
  5670. return this.multiplyQuaternions( this, q );
  5671. },
  5672. premultiply: function ( q ) {
  5673. return this.multiplyQuaternions( q, this );
  5674. },
  5675. multiplyQuaternions: function ( a, b ) {
  5676. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  5677. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  5678. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  5679. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  5680. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  5681. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  5682. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  5683. this.onChangeCallback();
  5684. return this;
  5685. },
  5686. slerp: function ( qb, t ) {
  5687. if ( t === 0 ) return this;
  5688. if ( t === 1 ) return this.copy( qb );
  5689. var x = this._x, y = this._y, z = this._z, w = this._w;
  5690. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  5691. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  5692. if ( cosHalfTheta < 0 ) {
  5693. this._w = - qb._w;
  5694. this._x = - qb._x;
  5695. this._y = - qb._y;
  5696. this._z = - qb._z;
  5697. cosHalfTheta = - cosHalfTheta;
  5698. } else {
  5699. this.copy( qb );
  5700. }
  5701. if ( cosHalfTheta >= 1.0 ) {
  5702. this._w = w;
  5703. this._x = x;
  5704. this._y = y;
  5705. this._z = z;
  5706. return this;
  5707. }
  5708. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  5709. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  5710. this._w = 0.5 * ( w + this._w );
  5711. this._x = 0.5 * ( x + this._x );
  5712. this._y = 0.5 * ( y + this._y );
  5713. this._z = 0.5 * ( z + this._z );
  5714. return this;
  5715. }
  5716. var halfTheta = Math.atan2( sinHalfTheta, cosHalfTheta );
  5717. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  5718. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  5719. this._w = ( w * ratioA + this._w * ratioB );
  5720. this._x = ( x * ratioA + this._x * ratioB );
  5721. this._y = ( y * ratioA + this._y * ratioB );
  5722. this._z = ( z * ratioA + this._z * ratioB );
  5723. this.onChangeCallback();
  5724. return this;
  5725. },
  5726. equals: function ( quaternion ) {
  5727. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  5728. },
  5729. fromArray: function ( array, offset ) {
  5730. if ( offset === undefined ) offset = 0;
  5731. this._x = array[ offset ];
  5732. this._y = array[ offset + 1 ];
  5733. this._z = array[ offset + 2 ];
  5734. this._w = array[ offset + 3 ];
  5735. this.onChangeCallback();
  5736. return this;
  5737. },
  5738. toArray: function ( array, offset ) {
  5739. if ( array === undefined ) array = [];
  5740. if ( offset === undefined ) offset = 0;
  5741. array[ offset ] = this._x;
  5742. array[ offset + 1 ] = this._y;
  5743. array[ offset + 2 ] = this._z;
  5744. array[ offset + 3 ] = this._w;
  5745. return array;
  5746. },
  5747. onChange: function ( callback ) {
  5748. this.onChangeCallback = callback;
  5749. return this;
  5750. },
  5751. onChangeCallback: function () {}
  5752. };
  5753. Object.assign( Quaternion, {
  5754. slerp: function( qa, qb, qm, t ) {
  5755. return qm.copy( qa ).slerp( qb, t );
  5756. },
  5757. slerpFlat: function(
  5758. dst, dstOffset, src0, srcOffset0, src1, srcOffset1, t ) {
  5759. // fuzz-free, array-based Quaternion SLERP operation
  5760. var x0 = src0[ srcOffset0 + 0 ],
  5761. y0 = src0[ srcOffset0 + 1 ],
  5762. z0 = src0[ srcOffset0 + 2 ],
  5763. w0 = src0[ srcOffset0 + 3 ],
  5764. x1 = src1[ srcOffset1 + 0 ],
  5765. y1 = src1[ srcOffset1 + 1 ],
  5766. z1 = src1[ srcOffset1 + 2 ],
  5767. w1 = src1[ srcOffset1 + 3 ];
  5768. if ( w0 !== w1 || x0 !== x1 || y0 !== y1 || z0 !== z1 ) {
  5769. var s = 1 - t,
  5770. cos = x0 * x1 + y0 * y1 + z0 * z1 + w0 * w1,
  5771. dir = ( cos >= 0 ? 1 : - 1 ),
  5772. sqrSin = 1 - cos * cos;
  5773. // Skip the Slerp for tiny steps to avoid numeric problems:
  5774. if ( sqrSin > Number.EPSILON ) {
  5775. var sin = Math.sqrt( sqrSin ),
  5776. len = Math.atan2( sin, cos * dir );
  5777. s = Math.sin( s * len ) / sin;
  5778. t = Math.sin( t * len ) / sin;
  5779. }
  5780. var tDir = t * dir;
  5781. x0 = x0 * s + x1 * tDir;
  5782. y0 = y0 * s + y1 * tDir;
  5783. z0 = z0 * s + z1 * tDir;
  5784. w0 = w0 * s + w1 * tDir;
  5785. // Normalize in case we just did a lerp:
  5786. if ( s === 1 - t ) {
  5787. var f = 1 / Math.sqrt( x0 * x0 + y0 * y0 + z0 * z0 + w0 * w0 );
  5788. x0 *= f;
  5789. y0 *= f;
  5790. z0 *= f;
  5791. w0 *= f;
  5792. }
  5793. }
  5794. dst[ dstOffset ] = x0;
  5795. dst[ dstOffset + 1 ] = y0;
  5796. dst[ dstOffset + 2 ] = z0;
  5797. dst[ dstOffset + 3 ] = w0;
  5798. }
  5799. } );
  5800. /**
  5801. * @author mrdoob / http://mrdoob.com/
  5802. * @author *kile / http://kile.stravaganza.org/
  5803. * @author philogb / http://blog.thejit.org/
  5804. * @author mikael emtinger / http://gomo.se/
  5805. * @author egraether / http://egraether.com/
  5806. * @author WestLangley / http://github.com/WestLangley
  5807. */
  5808. function Vector3( x, y, z ) {
  5809. this.x = x || 0;
  5810. this.y = y || 0;
  5811. this.z = z || 0;
  5812. }
  5813. Vector3.prototype = {
  5814. constructor: Vector3,
  5815. isVector3: true,
  5816. set: function ( x, y, z ) {
  5817. this.x = x;
  5818. this.y = y;
  5819. this.z = z;
  5820. return this;
  5821. },
  5822. setScalar: function ( scalar ) {
  5823. this.x = scalar;
  5824. this.y = scalar;
  5825. this.z = scalar;
  5826. return this;
  5827. },
  5828. setX: function ( x ) {
  5829. this.x = x;
  5830. return this;
  5831. },
  5832. setY: function ( y ) {
  5833. this.y = y;
  5834. return this;
  5835. },
  5836. setZ: function ( z ) {
  5837. this.z = z;
  5838. return this;
  5839. },
  5840. setComponent: function ( index, value ) {
  5841. switch ( index ) {
  5842. case 0: this.x = value; break;
  5843. case 1: this.y = value; break;
  5844. case 2: this.z = value; break;
  5845. default: throw new Error( 'index is out of range: ' + index );
  5846. }
  5847. return this;
  5848. },
  5849. getComponent: function ( index ) {
  5850. switch ( index ) {
  5851. case 0: return this.x;
  5852. case 1: return this.y;
  5853. case 2: return this.z;
  5854. default: throw new Error( 'index is out of range: ' + index );
  5855. }
  5856. },
  5857. clone: function () {
  5858. return new this.constructor( this.x, this.y, this.z );
  5859. },
  5860. copy: function ( v ) {
  5861. this.x = v.x;
  5862. this.y = v.y;
  5863. this.z = v.z;
  5864. return this;
  5865. },
  5866. add: function ( v, w ) {
  5867. if ( w !== undefined ) {
  5868. console.warn( 'THREE.Vector3: .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  5869. return this.addVectors( v, w );
  5870. }
  5871. this.x += v.x;
  5872. this.y += v.y;
  5873. this.z += v.z;
  5874. return this;
  5875. },
  5876. addScalar: function ( s ) {
  5877. this.x += s;
  5878. this.y += s;
  5879. this.z += s;
  5880. return this;
  5881. },
  5882. addVectors: function ( a, b ) {
  5883. this.x = a.x + b.x;
  5884. this.y = a.y + b.y;
  5885. this.z = a.z + b.z;
  5886. return this;
  5887. },
  5888. addScaledVector: function ( v, s ) {
  5889. this.x += v.x * s;
  5890. this.y += v.y * s;
  5891. this.z += v.z * s;
  5892. return this;
  5893. },
  5894. sub: function ( v, w ) {
  5895. if ( w !== undefined ) {
  5896. console.warn( 'THREE.Vector3: .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  5897. return this.subVectors( v, w );
  5898. }
  5899. this.x -= v.x;
  5900. this.y -= v.y;
  5901. this.z -= v.z;
  5902. return this;
  5903. },
  5904. subScalar: function ( s ) {
  5905. this.x -= s;
  5906. this.y -= s;
  5907. this.z -= s;
  5908. return this;
  5909. },
  5910. subVectors: function ( a, b ) {
  5911. this.x = a.x - b.x;
  5912. this.y = a.y - b.y;
  5913. this.z = a.z - b.z;
  5914. return this;
  5915. },
  5916. multiply: function ( v, w ) {
  5917. if ( w !== undefined ) {
  5918. console.warn( 'THREE.Vector3: .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  5919. return this.multiplyVectors( v, w );
  5920. }
  5921. this.x *= v.x;
  5922. this.y *= v.y;
  5923. this.z *= v.z;
  5924. return this;
  5925. },
  5926. multiplyScalar: function ( scalar ) {
  5927. if ( isFinite( scalar ) ) {
  5928. this.x *= scalar;
  5929. this.y *= scalar;
  5930. this.z *= scalar;
  5931. } else {
  5932. this.x = 0;
  5933. this.y = 0;
  5934. this.z = 0;
  5935. }
  5936. return this;
  5937. },
  5938. multiplyVectors: function ( a, b ) {
  5939. this.x = a.x * b.x;
  5940. this.y = a.y * b.y;
  5941. this.z = a.z * b.z;
  5942. return this;
  5943. },
  5944. applyEuler: function () {
  5945. var quaternion;
  5946. return function applyEuler( euler ) {
  5947. if ( (euler && euler.isEuler) === false ) {
  5948. console.error( 'THREE.Vector3: .applyEuler() now expects an Euler rotation rather than a Vector3 and order.' );
  5949. }
  5950. if ( quaternion === undefined ) quaternion = new Quaternion();
  5951. return this.applyQuaternion( quaternion.setFromEuler( euler ) );
  5952. };
  5953. }(),
  5954. applyAxisAngle: function () {
  5955. var quaternion;
  5956. return function applyAxisAngle( axis, angle ) {
  5957. if ( quaternion === undefined ) quaternion = new Quaternion();
  5958. return this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  5959. };
  5960. }(),
  5961. applyMatrix3: function ( m ) {
  5962. var x = this.x, y = this.y, z = this.z;
  5963. var e = m.elements;
  5964. this.x = e[ 0 ] * x + e[ 3 ] * y + e[ 6 ] * z;
  5965. this.y = e[ 1 ] * x + e[ 4 ] * y + e[ 7 ] * z;
  5966. this.z = e[ 2 ] * x + e[ 5 ] * y + e[ 8 ] * z;
  5967. return this;
  5968. },
  5969. applyMatrix4: function ( m ) {
  5970. // input: THREE.Matrix4 affine matrix
  5971. var x = this.x, y = this.y, z = this.z;
  5972. var e = m.elements;
  5973. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ];
  5974. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ];
  5975. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ];
  5976. return this;
  5977. },
  5978. applyProjection: function ( m ) {
  5979. // input: THREE.Matrix4 projection matrix
  5980. var x = this.x, y = this.y, z = this.z;
  5981. var e = m.elements;
  5982. var d = 1 / ( e[ 3 ] * x + e[ 7 ] * y + e[ 11 ] * z + e[ 15 ] ); // perspective divide
  5983. this.x = ( e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z + e[ 12 ] ) * d;
  5984. this.y = ( e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z + e[ 13 ] ) * d;
  5985. this.z = ( e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z + e[ 14 ] ) * d;
  5986. return this;
  5987. },
  5988. applyQuaternion: function ( q ) {
  5989. var x = this.x, y = this.y, z = this.z;
  5990. var qx = q.x, qy = q.y, qz = q.z, qw = q.w;
  5991. // calculate quat * vector
  5992. var ix = qw * x + qy * z - qz * y;
  5993. var iy = qw * y + qz * x - qx * z;
  5994. var iz = qw * z + qx * y - qy * x;
  5995. var iw = - qx * x - qy * y - qz * z;
  5996. // calculate result * inverse quat
  5997. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  5998. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  5999. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  6000. return this;
  6001. },
  6002. project: function () {
  6003. var matrix;
  6004. return function project( camera ) {
  6005. if ( matrix === undefined ) matrix = new Matrix4();
  6006. matrix.multiplyMatrices( camera.projectionMatrix, matrix.getInverse( camera.matrixWorld ) );
  6007. return this.applyProjection( matrix );
  6008. };
  6009. }(),
  6010. unproject: function () {
  6011. var matrix;
  6012. return function unproject( camera ) {
  6013. if ( matrix === undefined ) matrix = new Matrix4();
  6014. matrix.multiplyMatrices( camera.matrixWorld, matrix.getInverse( camera.projectionMatrix ) );
  6015. return this.applyProjection( matrix );
  6016. };
  6017. }(),
  6018. transformDirection: function ( m ) {
  6019. // input: THREE.Matrix4 affine matrix
  6020. // vector interpreted as a direction
  6021. var x = this.x, y = this.y, z = this.z;
  6022. var e = m.elements;
  6023. this.x = e[ 0 ] * x + e[ 4 ] * y + e[ 8 ] * z;
  6024. this.y = e[ 1 ] * x + e[ 5 ] * y + e[ 9 ] * z;
  6025. this.z = e[ 2 ] * x + e[ 6 ] * y + e[ 10 ] * z;
  6026. return this.normalize();
  6027. },
  6028. divide: function ( v ) {
  6029. this.x /= v.x;
  6030. this.y /= v.y;
  6031. this.z /= v.z;
  6032. return this;
  6033. },
  6034. divideScalar: function ( scalar ) {
  6035. return this.multiplyScalar( 1 / scalar );
  6036. },
  6037. min: function ( v ) {
  6038. this.x = Math.min( this.x, v.x );
  6039. this.y = Math.min( this.y, v.y );
  6040. this.z = Math.min( this.z, v.z );
  6041. return this;
  6042. },
  6043. max: function ( v ) {
  6044. this.x = Math.max( this.x, v.x );
  6045. this.y = Math.max( this.y, v.y );
  6046. this.z = Math.max( this.z, v.z );
  6047. return this;
  6048. },
  6049. clamp: function ( min, max ) {
  6050. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  6051. this.x = Math.max( min.x, Math.min( max.x, this.x ) );
  6052. this.y = Math.max( min.y, Math.min( max.y, this.y ) );
  6053. this.z = Math.max( min.z, Math.min( max.z, this.z ) );
  6054. return this;
  6055. },
  6056. clampScalar: function () {
  6057. var min, max;
  6058. return function clampScalar( minVal, maxVal ) {
  6059. if ( min === undefined ) {
  6060. min = new Vector3();
  6061. max = new Vector3();
  6062. }
  6063. min.set( minVal, minVal, minVal );
  6064. max.set( maxVal, maxVal, maxVal );
  6065. return this.clamp( min, max );
  6066. };
  6067. }(),
  6068. clampLength: function ( min, max ) {
  6069. var length = this.length();
  6070. return this.multiplyScalar( Math.max( min, Math.min( max, length ) ) / length );
  6071. },
  6072. floor: function () {
  6073. this.x = Math.floor( this.x );
  6074. this.y = Math.floor( this.y );
  6075. this.z = Math.floor( this.z );
  6076. return this;
  6077. },
  6078. ceil: function () {
  6079. this.x = Math.ceil( this.x );
  6080. this.y = Math.ceil( this.y );
  6081. this.z = Math.ceil( this.z );
  6082. return this;
  6083. },
  6084. round: function () {
  6085. this.x = Math.round( this.x );
  6086. this.y = Math.round( this.y );
  6087. this.z = Math.round( this.z );
  6088. return this;
  6089. },
  6090. roundToZero: function () {
  6091. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  6092. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  6093. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  6094. return this;
  6095. },
  6096. negate: function () {
  6097. this.x = - this.x;
  6098. this.y = - this.y;
  6099. this.z = - this.z;
  6100. return this;
  6101. },
  6102. dot: function ( v ) {
  6103. return this.x * v.x + this.y * v.y + this.z * v.z;
  6104. },
  6105. lengthSq: function () {
  6106. return this.x * this.x + this.y * this.y + this.z * this.z;
  6107. },
  6108. length: function () {
  6109. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  6110. },
  6111. lengthManhattan: function () {
  6112. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  6113. },
  6114. normalize: function () {
  6115. return this.divideScalar( this.length() );
  6116. },
  6117. setLength: function ( length ) {
  6118. return this.multiplyScalar( length / this.length() );
  6119. },
  6120. lerp: function ( v, alpha ) {
  6121. this.x += ( v.x - this.x ) * alpha;
  6122. this.y += ( v.y - this.y ) * alpha;
  6123. this.z += ( v.z - this.z ) * alpha;
  6124. return this;
  6125. },
  6126. lerpVectors: function ( v1, v2, alpha ) {
  6127. return this.subVectors( v2, v1 ).multiplyScalar( alpha ).add( v1 );
  6128. },
  6129. cross: function ( v, w ) {
  6130. if ( w !== undefined ) {
  6131. console.warn( 'THREE.Vector3: .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  6132. return this.crossVectors( v, w );
  6133. }
  6134. var x = this.x, y = this.y, z = this.z;
  6135. this.x = y * v.z - z * v.y;
  6136. this.y = z * v.x - x * v.z;
  6137. this.z = x * v.y - y * v.x;
  6138. return this;
  6139. },
  6140. crossVectors: function ( a, b ) {
  6141. var ax = a.x, ay = a.y, az = a.z;
  6142. var bx = b.x, by = b.y, bz = b.z;
  6143. this.x = ay * bz - az * by;
  6144. this.y = az * bx - ax * bz;
  6145. this.z = ax * by - ay * bx;
  6146. return this;
  6147. },
  6148. projectOnVector: function ( vector ) {
  6149. var scalar = vector.dot( this ) / vector.lengthSq();
  6150. return this.copy( vector ).multiplyScalar( scalar );
  6151. },
  6152. projectOnPlane: function () {
  6153. var v1;
  6154. return function projectOnPlane( planeNormal ) {
  6155. if ( v1 === undefined ) v1 = new Vector3();
  6156. v1.copy( this ).projectOnVector( planeNormal );
  6157. return this.sub( v1 );
  6158. };
  6159. }(),
  6160. reflect: function () {
  6161. // reflect incident vector off plane orthogonal to normal
  6162. // normal is assumed to have unit length
  6163. var v1;
  6164. return function reflect( normal ) {
  6165. if ( v1 === undefined ) v1 = new Vector3();
  6166. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  6167. };
  6168. }(),
  6169. angleTo: function ( v ) {
  6170. var theta = this.dot( v ) / ( Math.sqrt( this.lengthSq() * v.lengthSq() ) );
  6171. // clamp, to handle numerical problems
  6172. return Math.acos( _Math.clamp( theta, - 1, 1 ) );
  6173. },
  6174. distanceTo: function ( v ) {
  6175. return Math.sqrt( this.distanceToSquared( v ) );
  6176. },
  6177. distanceToSquared: function ( v ) {
  6178. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  6179. return dx * dx + dy * dy + dz * dz;
  6180. },
  6181. distanceToManhattan: function ( v ) {
  6182. return Math.abs( this.x - v.x ) + Math.abs( this.y - v.y ) + Math.abs( this.z - v.z );
  6183. },
  6184. setFromSpherical: function( s ) {
  6185. var sinPhiRadius = Math.sin( s.phi ) * s.radius;
  6186. this.x = sinPhiRadius * Math.sin( s.theta );
  6187. this.y = Math.cos( s.phi ) * s.radius;
  6188. this.z = sinPhiRadius * Math.cos( s.theta );
  6189. return this;
  6190. },
  6191. setFromCylindrical: function( c ) {
  6192. this.x = c.radius * Math.sin( c.theta );
  6193. this.y = c.y;
  6194. this.z = c.radius * Math.cos( c.theta );
  6195. return this;
  6196. },
  6197. setFromMatrixPosition: function ( m ) {
  6198. return this.setFromMatrixColumn( m, 3 );
  6199. },
  6200. setFromMatrixScale: function ( m ) {
  6201. var sx = this.setFromMatrixColumn( m, 0 ).length();
  6202. var sy = this.setFromMatrixColumn( m, 1 ).length();
  6203. var sz = this.setFromMatrixColumn( m, 2 ).length();
  6204. this.x = sx;
  6205. this.y = sy;
  6206. this.z = sz;
  6207. return this;
  6208. },
  6209. setFromMatrixColumn: function ( m, index ) {
  6210. if ( typeof m === 'number' ) {
  6211. console.warn( 'THREE.Vector3: setFromMatrixColumn now expects ( matrix, index ).' );
  6212. var temp = m;
  6213. m = index;
  6214. index = temp;
  6215. }
  6216. return this.fromArray( m.elements, index * 4 );
  6217. },
  6218. equals: function ( v ) {
  6219. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  6220. },
  6221. fromArray: function ( array, offset ) {
  6222. if ( offset === undefined ) offset = 0;
  6223. this.x = array[ offset ];
  6224. this.y = array[ offset + 1 ];
  6225. this.z = array[ offset + 2 ];
  6226. return this;
  6227. },
  6228. toArray: function ( array, offset ) {
  6229. if ( array === undefined ) array = [];
  6230. if ( offset === undefined ) offset = 0;
  6231. array[ offset ] = this.x;
  6232. array[ offset + 1 ] = this.y;
  6233. array[ offset + 2 ] = this.z;
  6234. return array;
  6235. },
  6236. fromAttribute: function ( attribute, index, offset ) {
  6237. if ( offset !== undefined ) {
  6238. console.warn( 'THREE.Vector3: offset has been removed from .fromAttribute().' );
  6239. }
  6240. this.x = attribute.getX( index );
  6241. this.y = attribute.getY( index );
  6242. this.z = attribute.getZ( index );
  6243. return this;
  6244. }
  6245. };
  6246. /**
  6247. * @author mrdoob / http://mrdoob.com/
  6248. * @author supereggbert / http://www.paulbrunt.co.uk/
  6249. * @author philogb / http://blog.thejit.org/
  6250. * @author jordi_ros / http://plattsoft.com
  6251. * @author D1plo1d / http://github.com/D1plo1d
  6252. * @author alteredq / http://alteredqualia.com/
  6253. * @author mikael emtinger / http://gomo.se/
  6254. * @author timknip / http://www.floorplanner.com/
  6255. * @author bhouston / http://clara.io
  6256. * @author WestLangley / http://github.com/WestLangley
  6257. */
  6258. function Matrix4() {
  6259. this.elements = new Float32Array( [
  6260. 1, 0, 0, 0,
  6261. 0, 1, 0, 0,
  6262. 0, 0, 1, 0,
  6263. 0, 0, 0, 1
  6264. ] );
  6265. if ( arguments.length > 0 ) {
  6266. console.error( 'THREE.Matrix4: the constructor no longer reads arguments. use .set() instead.' );
  6267. }
  6268. }
  6269. Matrix4.prototype = {
  6270. constructor: Matrix4,
  6271. isMatrix4: true,
  6272. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  6273. var te = this.elements;
  6274. te[ 0 ] = n11; te[ 4 ] = n12; te[ 8 ] = n13; te[ 12 ] = n14;
  6275. te[ 1 ] = n21; te[ 5 ] = n22; te[ 9 ] = n23; te[ 13 ] = n24;
  6276. te[ 2 ] = n31; te[ 6 ] = n32; te[ 10 ] = n33; te[ 14 ] = n34;
  6277. te[ 3 ] = n41; te[ 7 ] = n42; te[ 11 ] = n43; te[ 15 ] = n44;
  6278. return this;
  6279. },
  6280. identity: function () {
  6281. this.set(
  6282. 1, 0, 0, 0,
  6283. 0, 1, 0, 0,
  6284. 0, 0, 1, 0,
  6285. 0, 0, 0, 1
  6286. );
  6287. return this;
  6288. },
  6289. clone: function () {
  6290. return new Matrix4().fromArray( this.elements );
  6291. },
  6292. copy: function ( m ) {
  6293. this.elements.set( m.elements );
  6294. return this;
  6295. },
  6296. copyPosition: function ( m ) {
  6297. var te = this.elements;
  6298. var me = m.elements;
  6299. te[ 12 ] = me[ 12 ];
  6300. te[ 13 ] = me[ 13 ];
  6301. te[ 14 ] = me[ 14 ];
  6302. return this;
  6303. },
  6304. extractBasis: function ( xAxis, yAxis, zAxis ) {
  6305. xAxis.setFromMatrixColumn( this, 0 );
  6306. yAxis.setFromMatrixColumn( this, 1 );
  6307. zAxis.setFromMatrixColumn( this, 2 );
  6308. return this;
  6309. },
  6310. makeBasis: function ( xAxis, yAxis, zAxis ) {
  6311. this.set(
  6312. xAxis.x, yAxis.x, zAxis.x, 0,
  6313. xAxis.y, yAxis.y, zAxis.y, 0,
  6314. xAxis.z, yAxis.z, zAxis.z, 0,
  6315. 0, 0, 0, 1
  6316. );
  6317. return this;
  6318. },
  6319. extractRotation: function () {
  6320. var v1;
  6321. return function extractRotation( m ) {
  6322. if ( v1 === undefined ) v1 = new Vector3();
  6323. var te = this.elements;
  6324. var me = m.elements;
  6325. var scaleX = 1 / v1.setFromMatrixColumn( m, 0 ).length();
  6326. var scaleY = 1 / v1.setFromMatrixColumn( m, 1 ).length();
  6327. var scaleZ = 1 / v1.setFromMatrixColumn( m, 2 ).length();
  6328. te[ 0 ] = me[ 0 ] * scaleX;
  6329. te[ 1 ] = me[ 1 ] * scaleX;
  6330. te[ 2 ] = me[ 2 ] * scaleX;
  6331. te[ 4 ] = me[ 4 ] * scaleY;
  6332. te[ 5 ] = me[ 5 ] * scaleY;
  6333. te[ 6 ] = me[ 6 ] * scaleY;
  6334. te[ 8 ] = me[ 8 ] * scaleZ;
  6335. te[ 9 ] = me[ 9 ] * scaleZ;
  6336. te[ 10 ] = me[ 10 ] * scaleZ;
  6337. return this;
  6338. };
  6339. }(),
  6340. makeRotationFromEuler: function ( euler ) {
  6341. if ( (euler && euler.isEuler) === false ) {
  6342. console.error( 'THREE.Matrix: .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order.' );
  6343. }
  6344. var te = this.elements;
  6345. var x = euler.x, y = euler.y, z = euler.z;
  6346. var a = Math.cos( x ), b = Math.sin( x );
  6347. var c = Math.cos( y ), d = Math.sin( y );
  6348. var e = Math.cos( z ), f = Math.sin( z );
  6349. if ( euler.order === 'XYZ' ) {
  6350. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6351. te[ 0 ] = c * e;
  6352. te[ 4 ] = - c * f;
  6353. te[ 8 ] = d;
  6354. te[ 1 ] = af + be * d;
  6355. te[ 5 ] = ae - bf * d;
  6356. te[ 9 ] = - b * c;
  6357. te[ 2 ] = bf - ae * d;
  6358. te[ 6 ] = be + af * d;
  6359. te[ 10 ] = a * c;
  6360. } else if ( euler.order === 'YXZ' ) {
  6361. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6362. te[ 0 ] = ce + df * b;
  6363. te[ 4 ] = de * b - cf;
  6364. te[ 8 ] = a * d;
  6365. te[ 1 ] = a * f;
  6366. te[ 5 ] = a * e;
  6367. te[ 9 ] = - b;
  6368. te[ 2 ] = cf * b - de;
  6369. te[ 6 ] = df + ce * b;
  6370. te[ 10 ] = a * c;
  6371. } else if ( euler.order === 'ZXY' ) {
  6372. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  6373. te[ 0 ] = ce - df * b;
  6374. te[ 4 ] = - a * f;
  6375. te[ 8 ] = de + cf * b;
  6376. te[ 1 ] = cf + de * b;
  6377. te[ 5 ] = a * e;
  6378. te[ 9 ] = df - ce * b;
  6379. te[ 2 ] = - a * d;
  6380. te[ 6 ] = b;
  6381. te[ 10 ] = a * c;
  6382. } else if ( euler.order === 'ZYX' ) {
  6383. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  6384. te[ 0 ] = c * e;
  6385. te[ 4 ] = be * d - af;
  6386. te[ 8 ] = ae * d + bf;
  6387. te[ 1 ] = c * f;
  6388. te[ 5 ] = bf * d + ae;
  6389. te[ 9 ] = af * d - be;
  6390. te[ 2 ] = - d;
  6391. te[ 6 ] = b * c;
  6392. te[ 10 ] = a * c;
  6393. } else if ( euler.order === 'YZX' ) {
  6394. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6395. te[ 0 ] = c * e;
  6396. te[ 4 ] = bd - ac * f;
  6397. te[ 8 ] = bc * f + ad;
  6398. te[ 1 ] = f;
  6399. te[ 5 ] = a * e;
  6400. te[ 9 ] = - b * e;
  6401. te[ 2 ] = - d * e;
  6402. te[ 6 ] = ad * f + bc;
  6403. te[ 10 ] = ac - bd * f;
  6404. } else if ( euler.order === 'XZY' ) {
  6405. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  6406. te[ 0 ] = c * e;
  6407. te[ 4 ] = - f;
  6408. te[ 8 ] = d * e;
  6409. te[ 1 ] = ac * f + bd;
  6410. te[ 5 ] = a * e;
  6411. te[ 9 ] = ad * f - bc;
  6412. te[ 2 ] = bc * f - ad;
  6413. te[ 6 ] = b * e;
  6414. te[ 10 ] = bd * f + ac;
  6415. }
  6416. // last column
  6417. te[ 3 ] = 0;
  6418. te[ 7 ] = 0;
  6419. te[ 11 ] = 0;
  6420. // bottom row
  6421. te[ 12 ] = 0;
  6422. te[ 13 ] = 0;
  6423. te[ 14 ] = 0;
  6424. te[ 15 ] = 1;
  6425. return this;
  6426. },
  6427. makeRotationFromQuaternion: function ( q ) {
  6428. var te = this.elements;
  6429. var x = q.x, y = q.y, z = q.z, w = q.w;
  6430. var x2 = x + x, y2 = y + y, z2 = z + z;
  6431. var xx = x * x2, xy = x * y2, xz = x * z2;
  6432. var yy = y * y2, yz = y * z2, zz = z * z2;
  6433. var wx = w * x2, wy = w * y2, wz = w * z2;
  6434. te[ 0 ] = 1 - ( yy + zz );
  6435. te[ 4 ] = xy - wz;
  6436. te[ 8 ] = xz + wy;
  6437. te[ 1 ] = xy + wz;
  6438. te[ 5 ] = 1 - ( xx + zz );
  6439. te[ 9 ] = yz - wx;
  6440. te[ 2 ] = xz - wy;
  6441. te[ 6 ] = yz + wx;
  6442. te[ 10 ] = 1 - ( xx + yy );
  6443. // last column
  6444. te[ 3 ] = 0;
  6445. te[ 7 ] = 0;
  6446. te[ 11 ] = 0;
  6447. // bottom row
  6448. te[ 12 ] = 0;
  6449. te[ 13 ] = 0;
  6450. te[ 14 ] = 0;
  6451. te[ 15 ] = 1;
  6452. return this;
  6453. },
  6454. lookAt: function () {
  6455. var x, y, z;
  6456. return function lookAt( eye, target, up ) {
  6457. if ( x === undefined ) {
  6458. x = new Vector3();
  6459. y = new Vector3();
  6460. z = new Vector3();
  6461. }
  6462. var te = this.elements;
  6463. z.subVectors( eye, target ).normalize();
  6464. if ( z.lengthSq() === 0 ) {
  6465. z.z = 1;
  6466. }
  6467. x.crossVectors( up, z ).normalize();
  6468. if ( x.lengthSq() === 0 ) {
  6469. z.z += 0.0001;
  6470. x.crossVectors( up, z ).normalize();
  6471. }
  6472. y.crossVectors( z, x );
  6473. te[ 0 ] = x.x; te[ 4 ] = y.x; te[ 8 ] = z.x;
  6474. te[ 1 ] = x.y; te[ 5 ] = y.y; te[ 9 ] = z.y;
  6475. te[ 2 ] = x.z; te[ 6 ] = y.z; te[ 10 ] = z.z;
  6476. return this;
  6477. };
  6478. }(),
  6479. multiply: function ( m, n ) {
  6480. if ( n !== undefined ) {
  6481. console.warn( 'THREE.Matrix4: .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  6482. return this.multiplyMatrices( m, n );
  6483. }
  6484. return this.multiplyMatrices( this, m );
  6485. },
  6486. premultiply: function ( m ) {
  6487. return this.multiplyMatrices( m, this );
  6488. },
  6489. multiplyMatrices: function ( a, b ) {
  6490. var ae = a.elements;
  6491. var be = b.elements;
  6492. var te = this.elements;
  6493. var a11 = ae[ 0 ], a12 = ae[ 4 ], a13 = ae[ 8 ], a14 = ae[ 12 ];
  6494. var a21 = ae[ 1 ], a22 = ae[ 5 ], a23 = ae[ 9 ], a24 = ae[ 13 ];
  6495. var a31 = ae[ 2 ], a32 = ae[ 6 ], a33 = ae[ 10 ], a34 = ae[ 14 ];
  6496. var a41 = ae[ 3 ], a42 = ae[ 7 ], a43 = ae[ 11 ], a44 = ae[ 15 ];
  6497. var b11 = be[ 0 ], b12 = be[ 4 ], b13 = be[ 8 ], b14 = be[ 12 ];
  6498. var b21 = be[ 1 ], b22 = be[ 5 ], b23 = be[ 9 ], b24 = be[ 13 ];
  6499. var b31 = be[ 2 ], b32 = be[ 6 ], b33 = be[ 10 ], b34 = be[ 14 ];
  6500. var b41 = be[ 3 ], b42 = be[ 7 ], b43 = be[ 11 ], b44 = be[ 15 ];
  6501. te[ 0 ] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  6502. te[ 4 ] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  6503. te[ 8 ] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  6504. te[ 12 ] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  6505. te[ 1 ] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  6506. te[ 5 ] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  6507. te[ 9 ] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  6508. te[ 13 ] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  6509. te[ 2 ] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  6510. te[ 6 ] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  6511. te[ 10 ] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  6512. te[ 14 ] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  6513. te[ 3 ] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  6514. te[ 7 ] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  6515. te[ 11 ] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  6516. te[ 15 ] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  6517. return this;
  6518. },
  6519. multiplyToArray: function ( a, b, r ) {
  6520. var te = this.elements;
  6521. this.multiplyMatrices( a, b );
  6522. r[ 0 ] = te[ 0 ]; r[ 1 ] = te[ 1 ]; r[ 2 ] = te[ 2 ]; r[ 3 ] = te[ 3 ];
  6523. r[ 4 ] = te[ 4 ]; r[ 5 ] = te[ 5 ]; r[ 6 ] = te[ 6 ]; r[ 7 ] = te[ 7 ];
  6524. r[ 8 ] = te[ 8 ]; r[ 9 ] = te[ 9 ]; r[ 10 ] = te[ 10 ]; r[ 11 ] = te[ 11 ];
  6525. r[ 12 ] = te[ 12 ]; r[ 13 ] = te[ 13 ]; r[ 14 ] = te[ 14 ]; r[ 15 ] = te[ 15 ];
  6526. return this;
  6527. },
  6528. multiplyScalar: function ( s ) {
  6529. var te = this.elements;
  6530. te[ 0 ] *= s; te[ 4 ] *= s; te[ 8 ] *= s; te[ 12 ] *= s;
  6531. te[ 1 ] *= s; te[ 5 ] *= s; te[ 9 ] *= s; te[ 13 ] *= s;
  6532. te[ 2 ] *= s; te[ 6 ] *= s; te[ 10 ] *= s; te[ 14 ] *= s;
  6533. te[ 3 ] *= s; te[ 7 ] *= s; te[ 11 ] *= s; te[ 15 ] *= s;
  6534. return this;
  6535. },
  6536. applyToVector3Array: function () {
  6537. var v1;
  6538. return function applyToVector3Array( array, offset, length ) {
  6539. if ( v1 === undefined ) v1 = new Vector3();
  6540. if ( offset === undefined ) offset = 0;
  6541. if ( length === undefined ) length = array.length;
  6542. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  6543. v1.fromArray( array, j );
  6544. v1.applyMatrix4( this );
  6545. v1.toArray( array, j );
  6546. }
  6547. return array;
  6548. };
  6549. }(),
  6550. applyToBufferAttribute: function () {
  6551. var v1;
  6552. return function applyToBufferAttribute( attribute ) {
  6553. if ( v1 === undefined ) v1 = new Vector3();
  6554. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  6555. v1.x = attribute.getX( i );
  6556. v1.y = attribute.getY( i );
  6557. v1.z = attribute.getZ( i );
  6558. v1.applyMatrix4( this );
  6559. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  6560. }
  6561. return attribute;
  6562. };
  6563. }(),
  6564. determinant: function () {
  6565. var te = this.elements;
  6566. var n11 = te[ 0 ], n12 = te[ 4 ], n13 = te[ 8 ], n14 = te[ 12 ];
  6567. var n21 = te[ 1 ], n22 = te[ 5 ], n23 = te[ 9 ], n24 = te[ 13 ];
  6568. var n31 = te[ 2 ], n32 = te[ 6 ], n33 = te[ 10 ], n34 = te[ 14 ];
  6569. var n41 = te[ 3 ], n42 = te[ 7 ], n43 = te[ 11 ], n44 = te[ 15 ];
  6570. //TODO: make this more efficient
  6571. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  6572. return (
  6573. n41 * (
  6574. + n14 * n23 * n32
  6575. - n13 * n24 * n32
  6576. - n14 * n22 * n33
  6577. + n12 * n24 * n33
  6578. + n13 * n22 * n34
  6579. - n12 * n23 * n34
  6580. ) +
  6581. n42 * (
  6582. + n11 * n23 * n34
  6583. - n11 * n24 * n33
  6584. + n14 * n21 * n33
  6585. - n13 * n21 * n34
  6586. + n13 * n24 * n31
  6587. - n14 * n23 * n31
  6588. ) +
  6589. n43 * (
  6590. + n11 * n24 * n32
  6591. - n11 * n22 * n34
  6592. - n14 * n21 * n32
  6593. + n12 * n21 * n34
  6594. + n14 * n22 * n31
  6595. - n12 * n24 * n31
  6596. ) +
  6597. n44 * (
  6598. - n13 * n22 * n31
  6599. - n11 * n23 * n32
  6600. + n11 * n22 * n33
  6601. + n13 * n21 * n32
  6602. - n12 * n21 * n33
  6603. + n12 * n23 * n31
  6604. )
  6605. );
  6606. },
  6607. transpose: function () {
  6608. var te = this.elements;
  6609. var tmp;
  6610. tmp = te[ 1 ]; te[ 1 ] = te[ 4 ]; te[ 4 ] = tmp;
  6611. tmp = te[ 2 ]; te[ 2 ] = te[ 8 ]; te[ 8 ] = tmp;
  6612. tmp = te[ 6 ]; te[ 6 ] = te[ 9 ]; te[ 9 ] = tmp;
  6613. tmp = te[ 3 ]; te[ 3 ] = te[ 12 ]; te[ 12 ] = tmp;
  6614. tmp = te[ 7 ]; te[ 7 ] = te[ 13 ]; te[ 13 ] = tmp;
  6615. tmp = te[ 11 ]; te[ 11 ] = te[ 14 ]; te[ 14 ] = tmp;
  6616. return this;
  6617. },
  6618. setPosition: function ( v ) {
  6619. var te = this.elements;
  6620. te[ 12 ] = v.x;
  6621. te[ 13 ] = v.y;
  6622. te[ 14 ] = v.z;
  6623. return this;
  6624. },
  6625. getInverse: function ( m, throwOnDegenerate ) {
  6626. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  6627. var te = this.elements,
  6628. me = m.elements,
  6629. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ], n41 = me[ 3 ],
  6630. n12 = me[ 4 ], n22 = me[ 5 ], n32 = me[ 6 ], n42 = me[ 7 ],
  6631. n13 = me[ 8 ], n23 = me[ 9 ], n33 = me[ 10 ], n43 = me[ 11 ],
  6632. n14 = me[ 12 ], n24 = me[ 13 ], n34 = me[ 14 ], n44 = me[ 15 ],
  6633. t11 = n23 * n34 * n42 - n24 * n33 * n42 + n24 * n32 * n43 - n22 * n34 * n43 - n23 * n32 * n44 + n22 * n33 * n44,
  6634. t12 = n14 * n33 * n42 - n13 * n34 * n42 - n14 * n32 * n43 + n12 * n34 * n43 + n13 * n32 * n44 - n12 * n33 * n44,
  6635. t13 = n13 * n24 * n42 - n14 * n23 * n42 + n14 * n22 * n43 - n12 * n24 * n43 - n13 * n22 * n44 + n12 * n23 * n44,
  6636. t14 = n14 * n23 * n32 - n13 * n24 * n32 - n14 * n22 * n33 + n12 * n24 * n33 + n13 * n22 * n34 - n12 * n23 * n34;
  6637. var det = n11 * t11 + n21 * t12 + n31 * t13 + n41 * t14;
  6638. if ( det === 0 ) {
  6639. var msg = "THREE.Matrix4.getInverse(): can't invert matrix, determinant is 0";
  6640. if ( throwOnDegenerate === true ) {
  6641. throw new Error( msg );
  6642. } else {
  6643. console.warn( msg );
  6644. }
  6645. return this.identity();
  6646. }
  6647. var detInv = 1 / det;
  6648. te[ 0 ] = t11 * detInv;
  6649. te[ 1 ] = ( n24 * n33 * n41 - n23 * n34 * n41 - n24 * n31 * n43 + n21 * n34 * n43 + n23 * n31 * n44 - n21 * n33 * n44 ) * detInv;
  6650. te[ 2 ] = ( n22 * n34 * n41 - n24 * n32 * n41 + n24 * n31 * n42 - n21 * n34 * n42 - n22 * n31 * n44 + n21 * n32 * n44 ) * detInv;
  6651. te[ 3 ] = ( n23 * n32 * n41 - n22 * n33 * n41 - n23 * n31 * n42 + n21 * n33 * n42 + n22 * n31 * n43 - n21 * n32 * n43 ) * detInv;
  6652. te[ 4 ] = t12 * detInv;
  6653. te[ 5 ] = ( n13 * n34 * n41 - n14 * n33 * n41 + n14 * n31 * n43 - n11 * n34 * n43 - n13 * n31 * n44 + n11 * n33 * n44 ) * detInv;
  6654. te[ 6 ] = ( n14 * n32 * n41 - n12 * n34 * n41 - n14 * n31 * n42 + n11 * n34 * n42 + n12 * n31 * n44 - n11 * n32 * n44 ) * detInv;
  6655. te[ 7 ] = ( n12 * n33 * n41 - n13 * n32 * n41 + n13 * n31 * n42 - n11 * n33 * n42 - n12 * n31 * n43 + n11 * n32 * n43 ) * detInv;
  6656. te[ 8 ] = t13 * detInv;
  6657. te[ 9 ] = ( n14 * n23 * n41 - n13 * n24 * n41 - n14 * n21 * n43 + n11 * n24 * n43 + n13 * n21 * n44 - n11 * n23 * n44 ) * detInv;
  6658. te[ 10 ] = ( n12 * n24 * n41 - n14 * n22 * n41 + n14 * n21 * n42 - n11 * n24 * n42 - n12 * n21 * n44 + n11 * n22 * n44 ) * detInv;
  6659. te[ 11 ] = ( n13 * n22 * n41 - n12 * n23 * n41 - n13 * n21 * n42 + n11 * n23 * n42 + n12 * n21 * n43 - n11 * n22 * n43 ) * detInv;
  6660. te[ 12 ] = t14 * detInv;
  6661. te[ 13 ] = ( n13 * n24 * n31 - n14 * n23 * n31 + n14 * n21 * n33 - n11 * n24 * n33 - n13 * n21 * n34 + n11 * n23 * n34 ) * detInv;
  6662. te[ 14 ] = ( n14 * n22 * n31 - n12 * n24 * n31 - n14 * n21 * n32 + n11 * n24 * n32 + n12 * n21 * n34 - n11 * n22 * n34 ) * detInv;
  6663. te[ 15 ] = ( n12 * n23 * n31 - n13 * n22 * n31 + n13 * n21 * n32 - n11 * n23 * n32 - n12 * n21 * n33 + n11 * n22 * n33 ) * detInv;
  6664. return this;
  6665. },
  6666. scale: function ( v ) {
  6667. var te = this.elements;
  6668. var x = v.x, y = v.y, z = v.z;
  6669. te[ 0 ] *= x; te[ 4 ] *= y; te[ 8 ] *= z;
  6670. te[ 1 ] *= x; te[ 5 ] *= y; te[ 9 ] *= z;
  6671. te[ 2 ] *= x; te[ 6 ] *= y; te[ 10 ] *= z;
  6672. te[ 3 ] *= x; te[ 7 ] *= y; te[ 11 ] *= z;
  6673. return this;
  6674. },
  6675. getMaxScaleOnAxis: function () {
  6676. var te = this.elements;
  6677. var scaleXSq = te[ 0 ] * te[ 0 ] + te[ 1 ] * te[ 1 ] + te[ 2 ] * te[ 2 ];
  6678. var scaleYSq = te[ 4 ] * te[ 4 ] + te[ 5 ] * te[ 5 ] + te[ 6 ] * te[ 6 ];
  6679. var scaleZSq = te[ 8 ] * te[ 8 ] + te[ 9 ] * te[ 9 ] + te[ 10 ] * te[ 10 ];
  6680. return Math.sqrt( Math.max( scaleXSq, scaleYSq, scaleZSq ) );
  6681. },
  6682. makeTranslation: function ( x, y, z ) {
  6683. this.set(
  6684. 1, 0, 0, x,
  6685. 0, 1, 0, y,
  6686. 0, 0, 1, z,
  6687. 0, 0, 0, 1
  6688. );
  6689. return this;
  6690. },
  6691. makeRotationX: function ( theta ) {
  6692. var c = Math.cos( theta ), s = Math.sin( theta );
  6693. this.set(
  6694. 1, 0, 0, 0,
  6695. 0, c, - s, 0,
  6696. 0, s, c, 0,
  6697. 0, 0, 0, 1
  6698. );
  6699. return this;
  6700. },
  6701. makeRotationY: function ( theta ) {
  6702. var c = Math.cos( theta ), s = Math.sin( theta );
  6703. this.set(
  6704. c, 0, s, 0,
  6705. 0, 1, 0, 0,
  6706. - s, 0, c, 0,
  6707. 0, 0, 0, 1
  6708. );
  6709. return this;
  6710. },
  6711. makeRotationZ: function ( theta ) {
  6712. var c = Math.cos( theta ), s = Math.sin( theta );
  6713. this.set(
  6714. c, - s, 0, 0,
  6715. s, c, 0, 0,
  6716. 0, 0, 1, 0,
  6717. 0, 0, 0, 1
  6718. );
  6719. return this;
  6720. },
  6721. makeRotationAxis: function ( axis, angle ) {
  6722. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  6723. var c = Math.cos( angle );
  6724. var s = Math.sin( angle );
  6725. var t = 1 - c;
  6726. var x = axis.x, y = axis.y, z = axis.z;
  6727. var tx = t * x, ty = t * y;
  6728. this.set(
  6729. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  6730. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  6731. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  6732. 0, 0, 0, 1
  6733. );
  6734. return this;
  6735. },
  6736. makeScale: function ( x, y, z ) {
  6737. this.set(
  6738. x, 0, 0, 0,
  6739. 0, y, 0, 0,
  6740. 0, 0, z, 0,
  6741. 0, 0, 0, 1
  6742. );
  6743. return this;
  6744. },
  6745. makeShear: function ( x, y, z ) {
  6746. this.set(
  6747. 1, y, z, 0,
  6748. x, 1, z, 0,
  6749. x, y, 1, 0,
  6750. 0, 0, 0, 1
  6751. );
  6752. return this;
  6753. },
  6754. compose: function ( position, quaternion, scale ) {
  6755. this.makeRotationFromQuaternion( quaternion );
  6756. this.scale( scale );
  6757. this.setPosition( position );
  6758. return this;
  6759. },
  6760. decompose: function () {
  6761. var vector, matrix;
  6762. return function decompose( position, quaternion, scale ) {
  6763. if ( vector === undefined ) {
  6764. vector = new Vector3();
  6765. matrix = new Matrix4();
  6766. }
  6767. var te = this.elements;
  6768. var sx = vector.set( te[ 0 ], te[ 1 ], te[ 2 ] ).length();
  6769. var sy = vector.set( te[ 4 ], te[ 5 ], te[ 6 ] ).length();
  6770. var sz = vector.set( te[ 8 ], te[ 9 ], te[ 10 ] ).length();
  6771. // if determine is negative, we need to invert one scale
  6772. var det = this.determinant();
  6773. if ( det < 0 ) {
  6774. sx = - sx;
  6775. }
  6776. position.x = te[ 12 ];
  6777. position.y = te[ 13 ];
  6778. position.z = te[ 14 ];
  6779. // scale the rotation part
  6780. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  6781. var invSX = 1 / sx;
  6782. var invSY = 1 / sy;
  6783. var invSZ = 1 / sz;
  6784. matrix.elements[ 0 ] *= invSX;
  6785. matrix.elements[ 1 ] *= invSX;
  6786. matrix.elements[ 2 ] *= invSX;
  6787. matrix.elements[ 4 ] *= invSY;
  6788. matrix.elements[ 5 ] *= invSY;
  6789. matrix.elements[ 6 ] *= invSY;
  6790. matrix.elements[ 8 ] *= invSZ;
  6791. matrix.elements[ 9 ] *= invSZ;
  6792. matrix.elements[ 10 ] *= invSZ;
  6793. quaternion.setFromRotationMatrix( matrix );
  6794. scale.x = sx;
  6795. scale.y = sy;
  6796. scale.z = sz;
  6797. return this;
  6798. };
  6799. }(),
  6800. makeFrustum: function ( left, right, bottom, top, near, far ) {
  6801. var te = this.elements;
  6802. var x = 2 * near / ( right - left );
  6803. var y = 2 * near / ( top - bottom );
  6804. var a = ( right + left ) / ( right - left );
  6805. var b = ( top + bottom ) / ( top - bottom );
  6806. var c = - ( far + near ) / ( far - near );
  6807. var d = - 2 * far * near / ( far - near );
  6808. te[ 0 ] = x; te[ 4 ] = 0; te[ 8 ] = a; te[ 12 ] = 0;
  6809. te[ 1 ] = 0; te[ 5 ] = y; te[ 9 ] = b; te[ 13 ] = 0;
  6810. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = c; te[ 14 ] = d;
  6811. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = - 1; te[ 15 ] = 0;
  6812. return this;
  6813. },
  6814. makePerspective: function ( fov, aspect, near, far ) {
  6815. var ymax = near * Math.tan( _Math.DEG2RAD * fov * 0.5 );
  6816. var ymin = - ymax;
  6817. var xmin = ymin * aspect;
  6818. var xmax = ymax * aspect;
  6819. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  6820. },
  6821. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  6822. var te = this.elements;
  6823. var w = 1.0 / ( right - left );
  6824. var h = 1.0 / ( top - bottom );
  6825. var p = 1.0 / ( far - near );
  6826. var x = ( right + left ) * w;
  6827. var y = ( top + bottom ) * h;
  6828. var z = ( far + near ) * p;
  6829. te[ 0 ] = 2 * w; te[ 4 ] = 0; te[ 8 ] = 0; te[ 12 ] = - x;
  6830. te[ 1 ] = 0; te[ 5 ] = 2 * h; te[ 9 ] = 0; te[ 13 ] = - y;
  6831. te[ 2 ] = 0; te[ 6 ] = 0; te[ 10 ] = - 2 * p; te[ 14 ] = - z;
  6832. te[ 3 ] = 0; te[ 7 ] = 0; te[ 11 ] = 0; te[ 15 ] = 1;
  6833. return this;
  6834. },
  6835. equals: function ( matrix ) {
  6836. var te = this.elements;
  6837. var me = matrix.elements;
  6838. for ( var i = 0; i < 16; i ++ ) {
  6839. if ( te[ i ] !== me[ i ] ) return false;
  6840. }
  6841. return true;
  6842. },
  6843. fromArray: function ( array, offset ) {
  6844. if ( offset === undefined ) offset = 0;
  6845. for( var i = 0; i < 16; i ++ ) {
  6846. this.elements[ i ] = array[ i + offset ];
  6847. }
  6848. return this;
  6849. },
  6850. toArray: function ( array, offset ) {
  6851. if ( array === undefined ) array = [];
  6852. if ( offset === undefined ) offset = 0;
  6853. var te = this.elements;
  6854. array[ offset ] = te[ 0 ];
  6855. array[ offset + 1 ] = te[ 1 ];
  6856. array[ offset + 2 ] = te[ 2 ];
  6857. array[ offset + 3 ] = te[ 3 ];
  6858. array[ offset + 4 ] = te[ 4 ];
  6859. array[ offset + 5 ] = te[ 5 ];
  6860. array[ offset + 6 ] = te[ 6 ];
  6861. array[ offset + 7 ] = te[ 7 ];
  6862. array[ offset + 8 ] = te[ 8 ];
  6863. array[ offset + 9 ] = te[ 9 ];
  6864. array[ offset + 10 ] = te[ 10 ];
  6865. array[ offset + 11 ] = te[ 11 ];
  6866. array[ offset + 12 ] = te[ 12 ];
  6867. array[ offset + 13 ] = te[ 13 ];
  6868. array[ offset + 14 ] = te[ 14 ];
  6869. array[ offset + 15 ] = te[ 15 ];
  6870. return array;
  6871. }
  6872. };
  6873. /**
  6874. * @author mrdoob / http://mrdoob.com/
  6875. */
  6876. function CubeTexture( images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding ) {
  6877. images = images !== undefined ? images : [];
  6878. mapping = mapping !== undefined ? mapping : CubeReflectionMapping;
  6879. Texture.call( this, images, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  6880. this.flipY = false;
  6881. }
  6882. CubeTexture.prototype = Object.create( Texture.prototype );
  6883. CubeTexture.prototype.constructor = CubeTexture;
  6884. CubeTexture.prototype.isCubeTexture = true;
  6885. Object.defineProperty( CubeTexture.prototype, 'images', {
  6886. get: function () {
  6887. return this.image;
  6888. },
  6889. set: function ( value ) {
  6890. this.image = value;
  6891. }
  6892. } );
  6893. /**
  6894. * @author tschw
  6895. *
  6896. * Uniforms of a program.
  6897. * Those form a tree structure with a special top-level container for the root,
  6898. * which you get by calling 'new WebGLUniforms( gl, program, renderer )'.
  6899. *
  6900. *
  6901. * Properties of inner nodes including the top-level container:
  6902. *
  6903. * .seq - array of nested uniforms
  6904. * .map - nested uniforms by name
  6905. *
  6906. *
  6907. * Methods of all nodes except the top-level container:
  6908. *
  6909. * .setValue( gl, value, [renderer] )
  6910. *
  6911. * uploads a uniform value(s)
  6912. * the 'renderer' parameter is needed for sampler uniforms
  6913. *
  6914. *
  6915. * Static methods of the top-level container (renderer factorizations):
  6916. *
  6917. * .upload( gl, seq, values, renderer )
  6918. *
  6919. * sets uniforms in 'seq' to 'values[id].value'
  6920. *
  6921. * .seqWithValue( seq, values ) : filteredSeq
  6922. *
  6923. * filters 'seq' entries with corresponding entry in values
  6924. *
  6925. *
  6926. * Methods of the top-level container (renderer factorizations):
  6927. *
  6928. * .setValue( gl, name, value )
  6929. *
  6930. * sets uniform with name 'name' to 'value'
  6931. *
  6932. * .set( gl, obj, prop )
  6933. *
  6934. * sets uniform from object and property with same name than uniform
  6935. *
  6936. * .setOptional( gl, obj, prop )
  6937. *
  6938. * like .set for an optional property of the object
  6939. *
  6940. */
  6941. var emptyTexture = new Texture();
  6942. var emptyCubeTexture = new CubeTexture();
  6943. // --- Base for inner nodes (including the root) ---
  6944. function UniformContainer() {
  6945. this.seq = [];
  6946. this.map = {};
  6947. }
  6948. // --- Utilities ---
  6949. // Array Caches (provide typed arrays for temporary by size)
  6950. var arrayCacheF32 = [];
  6951. var arrayCacheI32 = [];
  6952. // Flattening for arrays of vectors and matrices
  6953. function flatten( array, nBlocks, blockSize ) {
  6954. var firstElem = array[ 0 ];
  6955. if ( firstElem <= 0 || firstElem > 0 ) return array;
  6956. // unoptimized: ! isNaN( firstElem )
  6957. // see http://jacksondunstan.com/articles/983
  6958. var n = nBlocks * blockSize,
  6959. r = arrayCacheF32[ n ];
  6960. if ( r === undefined ) {
  6961. r = new Float32Array( n );
  6962. arrayCacheF32[ n ] = r;
  6963. }
  6964. if ( nBlocks !== 0 ) {
  6965. firstElem.toArray( r, 0 );
  6966. for ( var i = 1, offset = 0; i !== nBlocks; ++ i ) {
  6967. offset += blockSize;
  6968. array[ i ].toArray( r, offset );
  6969. }
  6970. }
  6971. return r;
  6972. }
  6973. // Texture unit allocation
  6974. function allocTexUnits( renderer, n ) {
  6975. var r = arrayCacheI32[ n ];
  6976. if ( r === undefined ) {
  6977. r = new Int32Array( n );
  6978. arrayCacheI32[ n ] = r;
  6979. }
  6980. for ( var i = 0; i !== n; ++ i )
  6981. r[ i ] = renderer.allocTextureUnit();
  6982. return r;
  6983. }
  6984. // --- Setters ---
  6985. // Note: Defining these methods externally, because they come in a bunch
  6986. // and this way their names minify.
  6987. // Single scalar
  6988. function setValue1f( gl, v ) { gl.uniform1f( this.addr, v ); }
  6989. function setValue1i( gl, v ) { gl.uniform1i( this.addr, v ); }
  6990. // Single float vector (from flat array or THREE.VectorN)
  6991. function setValue2fv( gl, v ) {
  6992. if ( v.x === undefined ) gl.uniform2fv( this.addr, v );
  6993. else gl.uniform2f( this.addr, v.x, v.y );
  6994. }
  6995. function setValue3fv( gl, v ) {
  6996. if ( v.x !== undefined )
  6997. gl.uniform3f( this.addr, v.x, v.y, v.z );
  6998. else if ( v.r !== undefined )
  6999. gl.uniform3f( this.addr, v.r, v.g, v.b );
  7000. else
  7001. gl.uniform3fv( this.addr, v );
  7002. }
  7003. function setValue4fv( gl, v ) {
  7004. if ( v.x === undefined ) gl.uniform4fv( this.addr, v );
  7005. else gl.uniform4f( this.addr, v.x, v.y, v.z, v.w );
  7006. }
  7007. // Single matrix (from flat array or MatrixN)
  7008. function setValue2fm( gl, v ) {
  7009. gl.uniformMatrix2fv( this.addr, false, v.elements || v );
  7010. }
  7011. function setValue3fm( gl, v ) {
  7012. gl.uniformMatrix3fv( this.addr, false, v.elements || v );
  7013. }
  7014. function setValue4fm( gl, v ) {
  7015. gl.uniformMatrix4fv( this.addr, false, v.elements || v );
  7016. }
  7017. // Single texture (2D / Cube)
  7018. function setValueT1( gl, v, renderer ) {
  7019. var unit = renderer.allocTextureUnit();
  7020. gl.uniform1i( this.addr, unit );
  7021. renderer.setTexture2D( v || emptyTexture, unit );
  7022. }
  7023. function setValueT6( gl, v, renderer ) {
  7024. var unit = renderer.allocTextureUnit();
  7025. gl.uniform1i( this.addr, unit );
  7026. renderer.setTextureCube( v || emptyCubeTexture, unit );
  7027. }
  7028. // Integer / Boolean vectors or arrays thereof (always flat arrays)
  7029. function setValue2iv( gl, v ) { gl.uniform2iv( this.addr, v ); }
  7030. function setValue3iv( gl, v ) { gl.uniform3iv( this.addr, v ); }
  7031. function setValue4iv( gl, v ) { gl.uniform4iv( this.addr, v ); }
  7032. // Helper to pick the right setter for the singular case
  7033. function getSingularSetter( type ) {
  7034. switch ( type ) {
  7035. case 0x1406: return setValue1f; // FLOAT
  7036. case 0x8b50: return setValue2fv; // _VEC2
  7037. case 0x8b51: return setValue3fv; // _VEC3
  7038. case 0x8b52: return setValue4fv; // _VEC4
  7039. case 0x8b5a: return setValue2fm; // _MAT2
  7040. case 0x8b5b: return setValue3fm; // _MAT3
  7041. case 0x8b5c: return setValue4fm; // _MAT4
  7042. case 0x8b5e: return setValueT1; // SAMPLER_2D
  7043. case 0x8b60: return setValueT6; // SAMPLER_CUBE
  7044. case 0x1404: case 0x8b56: return setValue1i; // INT, BOOL
  7045. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7046. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7047. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7048. }
  7049. }
  7050. // Array of scalars
  7051. function setValue1fv( gl, v ) { gl.uniform1fv( this.addr, v ); }
  7052. function setValue1iv( gl, v ) { gl.uniform1iv( this.addr, v ); }
  7053. // Array of vectors (flat or from THREE classes)
  7054. function setValueV2a( gl, v ) {
  7055. gl.uniform2fv( this.addr, flatten( v, this.size, 2 ) );
  7056. }
  7057. function setValueV3a( gl, v ) {
  7058. gl.uniform3fv( this.addr, flatten( v, this.size, 3 ) );
  7059. }
  7060. function setValueV4a( gl, v ) {
  7061. gl.uniform4fv( this.addr, flatten( v, this.size, 4 ) );
  7062. }
  7063. // Array of matrices (flat or from THREE clases)
  7064. function setValueM2a( gl, v ) {
  7065. gl.uniformMatrix2fv( this.addr, false, flatten( v, this.size, 4 ) );
  7066. }
  7067. function setValueM3a( gl, v ) {
  7068. gl.uniformMatrix3fv( this.addr, false, flatten( v, this.size, 9 ) );
  7069. }
  7070. function setValueM4a( gl, v ) {
  7071. gl.uniformMatrix4fv( this.addr, false, flatten( v, this.size, 16 ) );
  7072. }
  7073. // Array of textures (2D / Cube)
  7074. function setValueT1a( gl, v, renderer ) {
  7075. var n = v.length,
  7076. units = allocTexUnits( renderer, n );
  7077. gl.uniform1iv( this.addr, units );
  7078. for ( var i = 0; i !== n; ++ i ) {
  7079. renderer.setTexture2D( v[ i ] || emptyTexture, units[ i ] );
  7080. }
  7081. }
  7082. function setValueT6a( gl, v, renderer ) {
  7083. var n = v.length,
  7084. units = allocTexUnits( renderer, n );
  7085. gl.uniform1iv( this.addr, units );
  7086. for ( var i = 0; i !== n; ++ i ) {
  7087. renderer.setTextureCube( v[ i ] || emptyCubeTexture, units[ i ] );
  7088. }
  7089. }
  7090. // Helper to pick the right setter for a pure (bottom-level) array
  7091. function getPureArraySetter( type ) {
  7092. switch ( type ) {
  7093. case 0x1406: return setValue1fv; // FLOAT
  7094. case 0x8b50: return setValueV2a; // _VEC2
  7095. case 0x8b51: return setValueV3a; // _VEC3
  7096. case 0x8b52: return setValueV4a; // _VEC4
  7097. case 0x8b5a: return setValueM2a; // _MAT2
  7098. case 0x8b5b: return setValueM3a; // _MAT3
  7099. case 0x8b5c: return setValueM4a; // _MAT4
  7100. case 0x8b5e: return setValueT1a; // SAMPLER_2D
  7101. case 0x8b60: return setValueT6a; // SAMPLER_CUBE
  7102. case 0x1404: case 0x8b56: return setValue1iv; // INT, BOOL
  7103. case 0x8b53: case 0x8b57: return setValue2iv; // _VEC2
  7104. case 0x8b54: case 0x8b58: return setValue3iv; // _VEC3
  7105. case 0x8b55: case 0x8b59: return setValue4iv; // _VEC4
  7106. }
  7107. }
  7108. // --- Uniform Classes ---
  7109. function SingleUniform( id, activeInfo, addr ) {
  7110. this.id = id;
  7111. this.addr = addr;
  7112. this.setValue = getSingularSetter( activeInfo.type );
  7113. // this.path = activeInfo.name; // DEBUG
  7114. }
  7115. function PureArrayUniform( id, activeInfo, addr ) {
  7116. this.id = id;
  7117. this.addr = addr;
  7118. this.size = activeInfo.size;
  7119. this.setValue = getPureArraySetter( activeInfo.type );
  7120. // this.path = activeInfo.name; // DEBUG
  7121. }
  7122. function StructuredUniform( id ) {
  7123. this.id = id;
  7124. UniformContainer.call( this ); // mix-in
  7125. }
  7126. StructuredUniform.prototype.setValue = function( gl, value ) {
  7127. // Note: Don't need an extra 'renderer' parameter, since samplers
  7128. // are not allowed in structured uniforms.
  7129. var seq = this.seq;
  7130. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7131. var u = seq[ i ];
  7132. u.setValue( gl, value[ u.id ] );
  7133. }
  7134. };
  7135. // --- Top-level ---
  7136. // Parser - builds up the property tree from the path strings
  7137. var RePathPart = /([\w\d_]+)(\])?(\[|\.)?/g;
  7138. // extracts
  7139. // - the identifier (member name or array index)
  7140. // - followed by an optional right bracket (found when array index)
  7141. // - followed by an optional left bracket or dot (type of subscript)
  7142. //
  7143. // Note: These portions can be read in a non-overlapping fashion and
  7144. // allow straightforward parsing of the hierarchy that WebGL encodes
  7145. // in the uniform names.
  7146. function addUniform( container, uniformObject ) {
  7147. container.seq.push( uniformObject );
  7148. container.map[ uniformObject.id ] = uniformObject;
  7149. }
  7150. function parseUniform( activeInfo, addr, container ) {
  7151. var path = activeInfo.name,
  7152. pathLength = path.length;
  7153. // reset RegExp object, because of the early exit of a previous run
  7154. RePathPart.lastIndex = 0;
  7155. for (; ;) {
  7156. var match = RePathPart.exec( path ),
  7157. matchEnd = RePathPart.lastIndex,
  7158. id = match[ 1 ],
  7159. idIsIndex = match[ 2 ] === ']',
  7160. subscript = match[ 3 ];
  7161. if ( idIsIndex ) id = id | 0; // convert to integer
  7162. if ( subscript === undefined ||
  7163. subscript === '[' && matchEnd + 2 === pathLength ) {
  7164. // bare name or "pure" bottom-level array "[0]" suffix
  7165. addUniform( container, subscript === undefined ?
  7166. new SingleUniform( id, activeInfo, addr ) :
  7167. new PureArrayUniform( id, activeInfo, addr ) );
  7168. break;
  7169. } else {
  7170. // step into inner node / create it in case it doesn't exist
  7171. var map = container.map,
  7172. next = map[ id ];
  7173. if ( next === undefined ) {
  7174. next = new StructuredUniform( id );
  7175. addUniform( container, next );
  7176. }
  7177. container = next;
  7178. }
  7179. }
  7180. }
  7181. // Root Container
  7182. function WebGLUniforms( gl, program, renderer ) {
  7183. UniformContainer.call( this );
  7184. this.renderer = renderer;
  7185. var n = gl.getProgramParameter( program, gl.ACTIVE_UNIFORMS );
  7186. for ( var i = 0; i !== n; ++ i ) {
  7187. var info = gl.getActiveUniform( program, i ),
  7188. path = info.name,
  7189. addr = gl.getUniformLocation( program, path );
  7190. parseUniform( info, addr, this );
  7191. }
  7192. }
  7193. WebGLUniforms.prototype.setValue = function( gl, name, value ) {
  7194. var u = this.map[ name ];
  7195. if ( u !== undefined ) u.setValue( gl, value, this.renderer );
  7196. };
  7197. WebGLUniforms.prototype.set = function( gl, object, name ) {
  7198. var u = this.map[ name ];
  7199. if ( u !== undefined ) u.setValue( gl, object[ name ], this.renderer );
  7200. };
  7201. WebGLUniforms.prototype.setOptional = function( gl, object, name ) {
  7202. var v = object[ name ];
  7203. if ( v !== undefined ) this.setValue( gl, name, v );
  7204. };
  7205. // Static interface
  7206. WebGLUniforms.upload = function( gl, seq, values, renderer ) {
  7207. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7208. var u = seq[ i ],
  7209. v = values[ u.id ];
  7210. if ( v.needsUpdate !== false ) {
  7211. // note: always updating when .needsUpdate is undefined
  7212. u.setValue( gl, v.value, renderer );
  7213. }
  7214. }
  7215. };
  7216. WebGLUniforms.seqWithValue = function( seq, values ) {
  7217. var r = [];
  7218. for ( var i = 0, n = seq.length; i !== n; ++ i ) {
  7219. var u = seq[ i ];
  7220. if ( u.id in values ) r.push( u );
  7221. }
  7222. return r;
  7223. };
  7224. /**
  7225. * Uniform Utilities
  7226. */
  7227. var UniformsUtils = {
  7228. merge: function ( uniforms ) {
  7229. var merged = {};
  7230. for ( var u = 0; u < uniforms.length; u ++ ) {
  7231. var tmp = this.clone( uniforms[ u ] );
  7232. for ( var p in tmp ) {
  7233. merged[ p ] = tmp[ p ];
  7234. }
  7235. }
  7236. return merged;
  7237. },
  7238. clone: function ( uniforms_src ) {
  7239. var uniforms_dst = {};
  7240. for ( var u in uniforms_src ) {
  7241. uniforms_dst[ u ] = {};
  7242. for ( var p in uniforms_src[ u ] ) {
  7243. var parameter_src = uniforms_src[ u ][ p ];
  7244. if ( parameter_src && ( parameter_src.isColor ||
  7245. parameter_src.isMatrix3 || parameter_src.isMatrix4 ||
  7246. parameter_src.isVector2 || parameter_src.isVector3 || parameter_src.isVector4 ||
  7247. parameter_src.isTexture ) ) {
  7248. uniforms_dst[ u ][ p ] = parameter_src.clone();
  7249. } else if ( Array.isArray( parameter_src ) ) {
  7250. uniforms_dst[ u ][ p ] = parameter_src.slice();
  7251. } else {
  7252. uniforms_dst[ u ][ p ] = parameter_src;
  7253. }
  7254. }
  7255. }
  7256. return uniforms_dst;
  7257. }
  7258. };
  7259. var alphamap_fragment = "#ifdef USE_ALPHAMAP\n\tdiffuseColor.a *= texture2D( alphaMap, vUv ).g;\n#endif\n";
  7260. var alphamap_pars_fragment = "#ifdef USE_ALPHAMAP\n\tuniform sampler2D alphaMap;\n#endif\n";
  7261. var alphatest_fragment = "#ifdef ALPHATEST\n\tif ( diffuseColor.a < ALPHATEST ) discard;\n#endif\n";
  7262. var aomap_fragment = "#ifdef USE_AOMAP\n\tfloat ambientOcclusion = ( texture2D( aoMap, vUv2 ).r - 1.0 ) * aoMapIntensity + 1.0;\n\treflectedLight.indirectDiffuse *= ambientOcclusion;\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\treflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.specularRoughness );\n\t#endif\n#endif\n";
  7263. var aomap_pars_fragment = "#ifdef USE_AOMAP\n\tuniform sampler2D aoMap;\n\tuniform float aoMapIntensity;\n#endif";
  7264. var begin_vertex = "\nvec3 transformed = vec3( position );\n";
  7265. var beginnormal_vertex = "\nvec3 objectNormal = vec3( normal );\n";
  7266. var bsdfs = "float punctualLightIntensityToIrradianceFactor( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) {\n\t\tif( decayExponent > 0.0 ) {\n#if defined ( PHYSICALLY_CORRECT_LIGHTS )\n\t\t\tfloat distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 );\n\t\t\tfloat maxDistanceCutoffFactor = pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) );\n\t\t\treturn distanceFalloff * maxDistanceCutoffFactor;\n#else\n\t\t\treturn pow( saturate( -lightDistance / cutoffDistance + 1.0 ), decayExponent );\n#endif\n\t\t}\n\t\treturn 1.0;\n}\nvec3 BRDF_Diffuse_Lambert( const in vec3 diffuseColor ) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\nvec3 F_Schlick( const in vec3 specularColor, const in float dotLH ) {\n\tfloat fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );\n\treturn ( 1.0 - specularColor ) * fresnel + specularColor;\n}\nfloat G_GGX_Smith( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\tfloat gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\treturn 1.0 / ( gl * gv );\n}\nfloat G_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) {\n\tfloat a2 = pow2( alpha );\n\tfloat gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) );\n\tfloat gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) );\n\treturn 0.5 / max( gv + gl, EPSILON );\n}\nfloat D_GGX( const in float alpha, const in float dotNH ) {\n\tfloat a2 = pow2( alpha );\n\tfloat denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0;\n\treturn RECIPROCAL_PI * a2 / pow2( denom );\n}\nvec3 BRDF_Specular_GGX( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat alpha = pow2( roughness );\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNL = saturate( dot( geometry.normal, incidentLight.direction ) );\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );\n\tfloat D = D_GGX( alpha, dotNH );\n\treturn F * ( G * D );\n}\nvec2 ltcTextureCoords( const in GeometricContext geometry, const in float roughness ) {\n\tconst float LUT_SIZE = 64.0;\n\tconst float LUT_SCALE = (LUT_SIZE - 1.0)/LUT_SIZE;\n\tconst float LUT_BIAS = 0.5/LUT_SIZE;\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tfloat theta = acos( dot( N, V ) );\n\tvec2 uv = vec2(\n\t\tsqrt( saturate( roughness ) ),\n\t\tsaturate( theta / ( 0.5 * PI ) ) );\n\tuv = uv * LUT_SCALE + LUT_BIAS;\n\treturn uv;\n}\nvoid clipQuadToHorizon( inout vec3 L[5], out int n ) {\n\tint config = 0;\n\tif ( L[0].z > 0.0 ) config += 1;\n\tif ( L[1].z > 0.0 ) config += 2;\n\tif ( L[2].z > 0.0 ) config += 4;\n\tif ( L[3].z > 0.0 ) config += 8;\n\tn = 0;\n\tif ( config == 0 ) {\n\t} else if ( config == 1 ) {\n\t\tn = 3;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 2 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 3 ) {\n\t\tn = 4;\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t\tL[3] = -L[3].z * L[0] + L[0].z * L[3];\n\t} else if ( config == 4 ) {\n\t\tn = 3;\n\t\tL[0] = -L[3].z * L[2] + L[2].z * L[3];\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t} else if ( config == 5 ) {\n\t\tn = 0;\n\t} else if ( config == 6 ) {\n\t\tn = 4;\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 7 ) {\n\t\tn = 5;\n\t\tL[4] = -L[3].z * L[0] + L[0].z * L[3];\n\t\tL[3] = -L[3].z * L[2] + L[2].z * L[3];\n\t} else if ( config == 8 ) {\n\t\tn = 3;\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[1] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = L[3];\n\t} else if ( config == 9 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t\tL[2] = -L[2].z * L[3] + L[3].z * L[2];\n\t} else if ( config == 10 ) {\n\t\tn = 0;\n\t} else if ( config == 11 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = -L[2].z * L[3] + L[3].z * L[2];\n\t\tL[2] = -L[2].z * L[1] + L[1].z * L[2];\n\t} else if ( config == 12 ) {\n\t\tn = 4;\n\t\tL[1] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[0] = -L[0].z * L[3] + L[3].z * L[0];\n\t} else if ( config == 13 ) {\n\t\tn = 5;\n\t\tL[4] = L[3];\n\t\tL[3] = L[2];\n\t\tL[2] = -L[1].z * L[2] + L[2].z * L[1];\n\t\tL[1] = -L[1].z * L[0] + L[0].z * L[1];\n\t} else if ( config == 14 ) {\n\t\tn = 5;\n\t\tL[4] = -L[0].z * L[3] + L[3].z * L[0];\n\t\tL[0] = -L[0].z * L[1] + L[1].z * L[0];\n\t} else if ( config == 15 ) {\n\t\tn = 4;\n\t}\n\tif ( n == 3 )\n\t\tL[3] = L[0];\n\tif ( n == 4 )\n\t\tL[4] = L[0];\n}\nfloat integrateLtcBrdfOverRectEdge( vec3 v1, vec3 v2 ) {\n\tfloat cosTheta = dot( v1, v2 );\n\tfloat theta = acos( cosTheta );\n\tfloat res = cross( v1, v2 ).z * ( ( theta > 0.001 ) ? theta / sin( theta ) : 1.0 );\n\treturn res;\n}\nvoid initRectPoints( const in vec3 pos, const in vec3 halfWidth, const in vec3 halfHeight, out vec3 rectPoints[4] ) {\n\trectPoints[0] = pos - halfWidth - halfHeight;\n\trectPoints[1] = pos + halfWidth - halfHeight;\n\trectPoints[2] = pos + halfWidth + halfHeight;\n\trectPoints[3] = pos - halfWidth + halfHeight;\n}\nvec3 integrateLtcBrdfOverRect( const in GeometricContext geometry, const in mat3 brdfMat, const in vec3 rectPoints[4] ) {\n\tvec3 N = geometry.normal;\n\tvec3 V = geometry.viewDir;\n\tvec3 P = geometry.position;\n\tvec3 T1, T2;\n\tT1 = normalize(V - N * dot( V, N ));\n\tT2 = - cross( N, T1 );\n\tmat3 brdfWrtSurface = brdfMat * transpose( mat3( T1, T2, N ) );\n\tvec3 clippedRect[5];\n\tclippedRect[0] = brdfWrtSurface * ( rectPoints[0] - P );\n\tclippedRect[1] = brdfWrtSurface * ( rectPoints[1] - P );\n\tclippedRect[2] = brdfWrtSurface * ( rectPoints[2] - P );\n\tclippedRect[3] = brdfWrtSurface * ( rectPoints[3] - P );\n\tint n;\n\tclipQuadToHorizon(clippedRect, n);\n\tif ( n == 0 )\n\t\treturn vec3( 0, 0, 0 );\n\tclippedRect[0] = normalize( clippedRect[0] );\n\tclippedRect[1] = normalize( clippedRect[1] );\n\tclippedRect[2] = normalize( clippedRect[2] );\n\tclippedRect[3] = normalize( clippedRect[3] );\n\tclippedRect[4] = normalize( clippedRect[4] );\n\tfloat sum = 0.0;\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[0], clippedRect[1] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[1], clippedRect[2] );\n\tsum += integrateLtcBrdfOverRectEdge( clippedRect[2], clippedRect[3] );\n\tif (n >= 4)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[3], clippedRect[4] );\n\tif (n == 5)\n\t\tsum += integrateLtcBrdfOverRectEdge( clippedRect[4], clippedRect[0] );\n\tsum = max( 0.0, sum );\n\tvec3 Lo_i = vec3( sum, sum, sum );\n\treturn Lo_i;\n}\nvec3 Rect_Area_Light_Specular_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight,\n\t\tconst in float roughness,\n\t\tconst in sampler2D ltcMat, const in sampler2D ltcMag ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tvec2 uv = ltcTextureCoords( geometry, roughness );\n\tvec4 brdfLtcApproxParams, t;\n\tbrdfLtcApproxParams = texture2D( ltcMat, uv );\n\tt = texture2D( ltcMat, uv );\n\tfloat brdfLtcScalar = texture2D( ltcMag, uv ).a;\n\tmat3 brdfLtcApproxMat = mat3(\n\t\tvec3( 1, 0, t.y ),\n\t\tvec3( 0, t.z, 0 ),\n\t\tvec3( t.w, 0, t.x )\n\t);\n\tvec3 specularReflectance = integrateLtcBrdfOverRect( geometry, brdfLtcApproxMat, rectPoints );\n\tspecularReflectance *= brdfLtcScalar;\n\treturn specularReflectance;\n}\nvec3 Rect_Area_Light_Diffuse_Reflectance(\n\t\tconst in GeometricContext geometry,\n\t\tconst in vec3 lightPos, const in vec3 lightHalfWidth, const in vec3 lightHalfHeight ) {\n\tvec3 rectPoints[4];\n\tinitRectPoints( lightPos, lightHalfWidth, lightHalfHeight, rectPoints );\n\tmat3 diffuseBrdfMat = mat3(1);\n\tvec3 diffuseReflectance = integrateLtcBrdfOverRect( geometry, diffuseBrdfMat, rectPoints );\n\treturn diffuseReflectance;\n}\nvec3 BRDF_Specular_GGX_Environment( const in GeometricContext geometry, const in vec3 specularColor, const in float roughness ) {\n\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\tconst vec4 c0 = vec4( - 1, - 0.0275, - 0.572, 0.022 );\n\tconst vec4 c1 = vec4( 1, 0.0425, 1.04, - 0.04 );\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min( r.x * r.x, exp2( - 9.28 * dotNV ) ) * r.x + r.y;\n\tvec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\nfloat G_BlinnPhong_Implicit( ) {\n\treturn 0.25;\n}\nfloat D_BlinnPhong( const in float shininess, const in float dotNH ) {\n\treturn RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess );\n}\nvec3 BRDF_Specular_BlinnPhong( const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float shininess ) {\n\tvec3 halfDir = normalize( incidentLight.direction + geometry.viewDir );\n\tfloat dotNH = saturate( dot( geometry.normal, halfDir ) );\n\tfloat dotLH = saturate( dot( incidentLight.direction, halfDir ) );\n\tvec3 F = F_Schlick( specularColor, dotLH );\n\tfloat G = G_BlinnPhong_Implicit( );\n\tfloat D = D_BlinnPhong( shininess, dotNH );\n\treturn F * ( G * D );\n}\nfloat GGXRoughnessToBlinnExponent( const in float ggxRoughness ) {\n\treturn ( 2.0 / pow2( ggxRoughness + 0.0001 ) - 2.0 );\n}\nfloat BlinnExponentToGGXRoughness( const in float blinnExponent ) {\n\treturn sqrt( 2.0 / ( blinnExponent + 2.0 ) );\n}\n";
  7267. var bumpmap_pars_fragment = "#ifdef USE_BUMPMAP\n\tuniform sampler2D bumpMap;\n\tuniform float bumpScale;\n\tvec2 dHdxy_fwd() {\n\t\tvec2 dSTdx = dFdx( vUv );\n\t\tvec2 dSTdy = dFdy( vUv );\n\t\tfloat Hll = bumpScale * texture2D( bumpMap, vUv ).x;\n\t\tfloat dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;\n\t\tfloat dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;\n\t\treturn vec2( dBx, dBy );\n\t}\n\tvec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {\n\t\tvec3 vSigmaX = dFdx( surf_pos );\n\t\tvec3 vSigmaY = dFdy( surf_pos );\n\t\tvec3 vN = surf_norm;\n\t\tvec3 R1 = cross( vSigmaY, vN );\n\t\tvec3 R2 = cross( vN, vSigmaX );\n\t\tfloat fDet = dot( vSigmaX, R1 );\n\t\tvec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );\n\t\treturn normalize( abs( fDet ) * surf_norm - vGrad );\n\t}\n#endif\n";
  7268. var clipping_planes_fragment = "#if NUM_CLIPPING_PLANES > 0\n\tfor ( int i = 0; i < UNION_CLIPPING_PLANES; ++ i ) {\n\t\tvec4 plane = clippingPlanes[ i ];\n\t\tif ( dot( vViewPosition, plane.xyz ) > plane.w ) discard;\n\t}\n\t\t\n\t#if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES\n\t\tbool clipped = true;\n\t\tfor ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; ++ i ) {\n\t\t\tvec4 plane = clippingPlanes[ i ];\n\t\t\tclipped = ( dot( vViewPosition, plane.xyz ) > plane.w ) && clipped;\n\t\t}\n\t\tif ( clipped ) discard;\n\t\n\t#endif\n#endif\n";
  7269. var clipping_planes_pars_fragment = "#if NUM_CLIPPING_PLANES > 0\n\t#if ! defined( PHYSICAL ) && ! defined( PHONG )\n\t\tvarying vec3 vViewPosition;\n\t#endif\n\tuniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ];\n#endif\n";
  7270. var clipping_planes_pars_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvarying vec3 vViewPosition;\n#endif\n";
  7271. var clipping_planes_vertex = "#if NUM_CLIPPING_PLANES > 0 && ! defined( PHYSICAL ) && ! defined( PHONG )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n";
  7272. var color_fragment = "#ifdef USE_COLOR\n\tdiffuseColor.rgb *= vColor;\n#endif";
  7273. var color_pars_fragment = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif\n";
  7274. var color_pars_vertex = "#ifdef USE_COLOR\n\tvarying vec3 vColor;\n#endif";
  7275. var color_vertex = "#ifdef USE_COLOR\n\tvColor.xyz = color.xyz;\n#endif";
  7276. var common = "#define PI 3.14159265359\n#define PI2 6.28318530718\n#define PI_HALF 1.5707963267949\n#define RECIPROCAL_PI 0.31830988618\n#define RECIPROCAL_PI2 0.15915494\n#define LOG2 1.442695\n#define EPSILON 1e-6\n#define saturate(a) clamp( a, 0.0, 1.0 )\n#define whiteCompliment(a) ( 1.0 - saturate( a ) )\nfloat pow2( const in float x ) { return x*x; }\nfloat pow3( const in float x ) { return x*x*x; }\nfloat pow4( const in float x ) { float x2 = x*x; return x2*x2; }\nfloat average( const in vec3 color ) { return dot( color, vec3( 0.3333 ) ); }\nhighp float rand( const in vec2 uv ) {\n\tconst highp float a = 12.9898, b = 78.233, c = 43758.5453;\n\thighp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n\treturn fract(sin(sn) * c);\n}\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n\tbool visible;\n};\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n\tvec3 indirectSpecular;\n};\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\nvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n}\nvec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) {\n\treturn normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );\n}\nvec3 projectOnPlane(in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\tfloat distance = dot( planeNormal, point - pointOnPlane );\n\treturn - distance * planeNormal + point;\n}\nfloat sideOfPlane( in vec3 point, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn sign( dot( point - pointOnPlane, planeNormal ) );\n}\nvec3 linePlaneIntersect( in vec3 pointOnLine, in vec3 lineDirection, in vec3 pointOnPlane, in vec3 planeNormal ) {\n\treturn lineDirection * ( dot( planeNormal, pointOnPlane - pointOnLine ) / dot( planeNormal, lineDirection ) ) + pointOnLine;\n}\nmat3 transpose( const in mat3 v ) {\n\tmat3 tmp;\n\ttmp[0] = vec3(v[0].x, v[1].x, v[2].x);\n\ttmp[1] = vec3(v[0].y, v[1].y, v[2].y);\n\ttmp[2] = vec3(v[0].z, v[1].z, v[2].z);\n\treturn tmp;\n}\n";
  7277. var cube_uv_reflection_fragment = "#ifdef ENVMAP_TYPE_CUBE_UV\n#define cubeUV_textureSize (1024.0)\nint getFaceFromDirection(vec3 direction) {\n\tvec3 absDirection = abs(direction);\n\tint face = -1;\n\tif( absDirection.x > absDirection.z ) {\n\t\tif(absDirection.x > absDirection.y )\n\t\t\tface = direction.x > 0.0 ? 0 : 3;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\telse {\n\t\tif(absDirection.z > absDirection.y )\n\t\t\tface = direction.z > 0.0 ? 2 : 5;\n\t\telse\n\t\t\tface = direction.y > 0.0 ? 1 : 4;\n\t}\n\treturn face;\n}\n#define cubeUV_maxLods1 (log2(cubeUV_textureSize*0.25) - 1.0)\n#define cubeUV_rangeClamp (exp2((6.0 - 1.0) * 2.0))\nvec2 MipLevelInfo( vec3 vec, float roughnessLevel, float roughness ) {\n\tfloat scale = exp2(cubeUV_maxLods1 - roughnessLevel);\n\tfloat dxRoughness = dFdx(roughness);\n\tfloat dyRoughness = dFdy(roughness);\n\tvec3 dx = dFdx( vec * scale * dxRoughness );\n\tvec3 dy = dFdy( vec * scale * dyRoughness );\n\tfloat d = max( dot( dx, dx ), dot( dy, dy ) );\n\td = clamp(d, 1.0, cubeUV_rangeClamp);\n\tfloat mipLevel = 0.5 * log2(d);\n\treturn vec2(floor(mipLevel), fract(mipLevel));\n}\n#define cubeUV_maxLods2 (log2(cubeUV_textureSize*0.25) - 2.0)\n#define cubeUV_rcpTextureSize (1.0 / cubeUV_textureSize)\nvec2 getCubeUV(vec3 direction, float roughnessLevel, float mipLevel) {\n\tmipLevel = roughnessLevel > cubeUV_maxLods2 - 3.0 ? 0.0 : mipLevel;\n\tfloat a = 16.0 * cubeUV_rcpTextureSize;\n\tvec2 exp2_packed = exp2( vec2( roughnessLevel, mipLevel ) );\n\tvec2 rcp_exp2_packed = vec2( 1.0 ) / exp2_packed;\n\tfloat powScale = exp2_packed.x * exp2_packed.y;\n\tfloat scale = rcp_exp2_packed.x * rcp_exp2_packed.y * 0.25;\n\tfloat mipOffset = 0.75*(1.0 - rcp_exp2_packed.y) * rcp_exp2_packed.x;\n\tbool bRes = mipLevel == 0.0;\n\tscale = bRes && (scale < a) ? a : scale;\n\tvec3 r;\n\tvec2 offset;\n\tint face = getFaceFromDirection(direction);\n\tfloat rcpPowScale = 1.0 / powScale;\n\tif( face == 0) {\n\t\tr = vec3(direction.x, -direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 1) {\n\t\tr = vec3(direction.y, direction.x, direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 2) {\n\t\tr = vec3(direction.z, direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.75 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? a : offset.y;\n\t}\n\telse if( face == 3) {\n\t\tr = vec3(direction.x, direction.z, direction.y);\n\t\toffset = vec2(0.0+mipOffset,0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse if( face == 4) {\n\t\tr = vec3(direction.y, direction.x, -direction.z);\n\t\toffset = vec2(scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\telse {\n\t\tr = vec3(direction.z, -direction.x, direction.y);\n\t\toffset = vec2(2.0*scale+mipOffset, 0.5 * rcpPowScale);\n\t\toffset.y = bRes && (offset.y < 2.0*a) ? 0.0 : offset.y;\n\t}\n\tr = normalize(r);\n\tfloat texelOffset = 0.5 * cubeUV_rcpTextureSize;\n\tvec2 s = ( r.yz / abs( r.x ) + vec2( 1.0 ) ) * 0.5;\n\tvec2 base = offset + vec2( texelOffset );\n\treturn base + s * ( scale - 2.0 * texelOffset );\n}\n#define cubeUV_maxLods3 (log2(cubeUV_textureSize*0.25) - 3.0)\nvec4 textureCubeUV(vec3 reflectedDirection, float roughness ) {\n\tfloat roughnessVal = roughness* cubeUV_maxLods3;\n\tfloat r1 = floor(roughnessVal);\n\tfloat r2 = r1 + 1.0;\n\tfloat t = fract(roughnessVal);\n\tvec2 mipInfo = MipLevelInfo(reflectedDirection, r1, roughness);\n\tfloat s = mipInfo.y;\n\tfloat level0 = mipInfo.x;\n\tfloat level1 = level0 + 1.0;\n\tlevel1 = level1 > 5.0 ? 5.0 : level1;\n\tlevel0 += min( floor( s + 0.5 ), 5.0 );\n\tvec2 uv_10 = getCubeUV(reflectedDirection, r1, level0);\n\tvec4 color10 = envMapTexelToLinear(texture2D(envMap, uv_10));\n\tvec2 uv_20 = getCubeUV(reflectedDirection, r2, level0);\n\tvec4 color20 = envMapTexelToLinear(texture2D(envMap, uv_20));\n\tvec4 result = mix(color10, color20, t);\n\treturn vec4(result.rgb, 1.0);\n}\n#endif\n";
  7278. var defaultnormal_vertex = "#ifdef FLIP_SIDED\n\tobjectNormal = -objectNormal;\n#endif\nvec3 transformedNormal = normalMatrix * objectNormal;\n";
  7279. var displacementmap_pars_vertex = "#ifdef USE_DISPLACEMENTMAP\n\tuniform sampler2D displacementMap;\n\tuniform float displacementScale;\n\tuniform float displacementBias;\n#endif\n";
  7280. var displacementmap_vertex = "#ifdef USE_DISPLACEMENTMAP\n\ttransformed += normal * ( texture2D( displacementMap, uv ).x * displacementScale + displacementBias );\n#endif\n";
  7281. var emissivemap_fragment = "#ifdef USE_EMISSIVEMAP\n\tvec4 emissiveColor = texture2D( emissiveMap, vUv );\n\temissiveColor.rgb = emissiveMapTexelToLinear( emissiveColor ).rgb;\n\ttotalEmissiveRadiance *= emissiveColor.rgb;\n#endif\n";
  7282. var emissivemap_pars_fragment = "#ifdef USE_EMISSIVEMAP\n\tuniform sampler2D emissiveMap;\n#endif\n";
  7283. var encodings_fragment = " gl_FragColor = linearToOutputTexel( gl_FragColor );\n";
  7284. var encodings_pars_fragment = "\nvec4 LinearToLinear( in vec4 value ) {\n return value;\n}\nvec4 GammaToLinear( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );\n}\nvec4 LinearToGamma( in vec4 value, in float gammaFactor ) {\n return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );\n}\nvec4 sRGBToLinear( in vec4 value ) {\n return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );\n}\nvec4 LinearTosRGB( in vec4 value ) {\n return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.w );\n}\nvec4 RGBEToLinear( in vec4 value ) {\n return vec4( value.rgb * exp2( value.a * 255.0 - 128.0 ), 1.0 );\n}\nvec4 LinearToRGBE( in vec4 value ) {\n float maxComponent = max( max( value.r, value.g ), value.b );\n float fExp = clamp( ceil( log2( maxComponent ) ), -128.0, 127.0 );\n return vec4( value.rgb / exp2( fExp ), ( fExp + 128.0 ) / 255.0 );\n}\nvec4 RGBMToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.xyz * value.w * maxRange, 1.0 );\n}\nvec4 LinearToRGBM( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float M = clamp( maxRGB / maxRange, 0.0, 1.0 );\n M = ceil( M * 255.0 ) / 255.0;\n return vec4( value.rgb / ( M * maxRange ), M );\n}\nvec4 RGBDToLinear( in vec4 value, in float maxRange ) {\n return vec4( value.rgb * ( ( maxRange / 255.0 ) / value.a ), 1.0 );\n}\nvec4 LinearToRGBD( in vec4 value, in float maxRange ) {\n float maxRGB = max( value.x, max( value.g, value.b ) );\n float D = max( maxRange / maxRGB, 1.0 );\n D = min( floor( D ) / 255.0, 1.0 );\n return vec4( value.rgb * ( D * ( 255.0 / maxRange ) ), D );\n}\nconst mat3 cLogLuvM = mat3( 0.2209, 0.3390, 0.4184, 0.1138, 0.6780, 0.7319, 0.0102, 0.1130, 0.2969 );\nvec4 LinearToLogLuv( in vec4 value ) {\n vec3 Xp_Y_XYZp = value.rgb * cLogLuvM;\n Xp_Y_XYZp = max(Xp_Y_XYZp, vec3(1e-6, 1e-6, 1e-6));\n vec4 vResult;\n vResult.xy = Xp_Y_XYZp.xy / Xp_Y_XYZp.z;\n float Le = 2.0 * log2(Xp_Y_XYZp.y) + 127.0;\n vResult.w = fract(Le);\n vResult.z = (Le - (floor(vResult.w*255.0))/255.0)/255.0;\n return vResult;\n}\nconst mat3 cLogLuvInverseM = mat3( 6.0014, -2.7008, -1.7996, -1.3320, 3.1029, -5.7721, 0.3008, -1.0882, 5.6268 );\nvec4 LogLuvToLinear( in vec4 value ) {\n float Le = value.z * 255.0 + value.w;\n vec3 Xp_Y_XYZp;\n Xp_Y_XYZp.y = exp2((Le - 127.0) / 2.0);\n Xp_Y_XYZp.z = Xp_Y_XYZp.y / value.y;\n Xp_Y_XYZp.x = value.x * Xp_Y_XYZp.z;\n vec3 vRGB = Xp_Y_XYZp.rgb * cLogLuvInverseM;\n return vec4( max(vRGB, 0.0), 1.0 );\n}\n";
  7285. var envmap_fragment = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( normal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#else\n\t\tvec3 reflectVec = vReflect;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tvec4 envColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );\n\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\tvec2 sampleUV;\n\t\tsampleUV.y = saturate( flipNormal * reflectVec.y * 0.5 + 0.5 );\n\t\tsampleUV.x = atan( flipNormal * reflectVec.z, flipNormal * reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\tvec4 envColor = texture2D( envMap, sampleUV );\n\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\tvec3 reflectView = flipNormal * normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0, 0.0, 1.0 ) );\n\t\tvec4 envColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5 );\n\t#else\n\t\tvec4 envColor = vec4( 0.0 );\n\t#endif\n\tenvColor = envMapTexelToLinear( envColor );\n\t#ifdef ENVMAP_BLENDING_MULTIPLY\n\t\toutgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_MIX )\n\t\toutgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity );\n\t#elif defined( ENVMAP_BLENDING_ADD )\n\t\toutgoingLight += envColor.xyz * specularStrength * reflectivity;\n\t#endif\n#endif\n";
  7286. var envmap_pars_fragment = "#if defined( USE_ENVMAP ) || defined( PHYSICAL )\n\tuniform float reflectivity;\n\tuniform float envMapIntensity;\n#endif\n#ifdef USE_ENVMAP\n\t#if ! defined( PHYSICAL ) && ( defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) )\n\t\tvarying vec3 vWorldPosition;\n\t#endif\n\t#ifdef ENVMAP_TYPE_CUBE\n\t\tuniform samplerCube envMap;\n\t#else\n\t\tuniform sampler2D envMap;\n\t#endif\n\tuniform float flipEnvMap;\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( PHYSICAL )\n\t\tuniform float refractionRatio;\n\t#else\n\t\tvarying vec3 vReflect;\n\t#endif\n#endif\n";
  7287. var envmap_pars_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvarying vec3 vWorldPosition;\n\t#else\n\t\tvarying vec3 vReflect;\n\t\tuniform float refractionRatio;\n\t#endif\n#endif\n";
  7288. var envmap_vertex = "#ifdef USE_ENVMAP\n\t#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG )\n\t\tvWorldPosition = worldPosition.xyz;\n\t#else\n\t\tvec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );\n\t\tvec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix );\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvReflect = reflect( cameraToVertex, worldNormal );\n\t\t#else\n\t\t\tvReflect = refract( cameraToVertex, worldNormal, refractionRatio );\n\t\t#endif\n\t#endif\n#endif\n";
  7289. var fog_fragment = "#ifdef USE_FOG\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tfloat depth = gl_FragDepthEXT / gl_FragCoord.w;\n\t#else\n\t\tfloat depth = gl_FragCoord.z / gl_FragCoord.w;\n\t#endif\n\t#ifdef FOG_EXP2\n\t\tfloat fogFactor = whiteCompliment( exp2( - fogDensity * fogDensity * depth * depth * LOG2 ) );\n\t#else\n\t\tfloat fogFactor = smoothstep( fogNear, fogFar, depth );\n\t#endif\n\tgl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor );\n#endif\n";
  7290. var fog_pars_fragment = "#ifdef USE_FOG\n\tuniform vec3 fogColor;\n\t#ifdef FOG_EXP2\n\t\tuniform float fogDensity;\n\t#else\n\t\tuniform float fogNear;\n\t\tuniform float fogFar;\n\t#endif\n#endif";
  7291. var gradientmap_pars_fragment = "#ifdef TOON\n\tuniform sampler2D gradientMap;\n\tvec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) {\n\t\tfloat dotNL = dot( normal, lightDirection );\n\t\tvec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 );\n\t\t#ifdef USE_GRADIENTMAP\n\t\t\treturn texture2D( gradientMap, coord ).rgb;\n\t\t#else\n\t\t\treturn ( coord.x < 0.7 ) ? vec3( 0.7 ) : vec3( 1.0 );\n\t\t#endif\n\t}\n#endif\n";
  7292. var lightmap_fragment = "#ifdef USE_LIGHTMAP\n\treflectedLight.indirectDiffuse += PI * texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n#endif\n";
  7293. var lightmap_pars_fragment = "#ifdef USE_LIGHTMAP\n\tuniform sampler2D lightMap;\n\tuniform float lightMapIntensity;\n#endif";
  7294. var lights_lambert_vertex = "vec3 diffuse = vec3( 1.0 );\nGeometricContext geometry;\ngeometry.position = mvPosition.xyz;\ngeometry.normal = normalize( transformedNormal );\ngeometry.viewDir = normalize( -mvPosition.xyz );\nGeometricContext backGeometry;\nbackGeometry.position = geometry.position;\nbackGeometry.normal = -geometry.normal;\nbackGeometry.viewDir = geometry.viewDir;\nvLightFront = vec3( 0.0 );\n#ifdef DOUBLE_SIDED\n\tvLightBack = vec3( 0.0 );\n#endif\nIncidentLight directLight;\nfloat dotNL;\nvec3 directLightColor_Diffuse;\n#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tgetPointDirectLightIrradiance( pointLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tgetSpotDirectLightIrradiance( spotLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t}\n#endif\n#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tgetDirectionalDirectLightIrradiance( directionalLights[ i ], geometry, directLight );\n\t\tdotNL = dot( geometry.normal, directLight.direction );\n\t\tdirectLightColor_Diffuse = PI * directLight.color;\n\t\tvLightFront += saturate( dotNL ) * directLightColor_Diffuse;\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += saturate( -dotNL ) * directLightColor_Diffuse;\n\t\t#endif\n\t}\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\tvLightFront += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t#ifdef DOUBLE_SIDED\n\t\t\tvLightBack += getHemisphereLightIrradiance( hemisphereLights[ i ], backGeometry );\n\t\t#endif\n\t}\n#endif\n";
  7295. var lights_pars = "uniform vec3 ambientLightColor;\nvec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) {\n\tvec3 irradiance = ambientLightColor;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treturn irradiance;\n}\n#if NUM_DIR_LIGHTS > 0\n\tstruct DirectionalLight {\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ];\n\tvoid getDirectionalDirectLightIrradiance( const in DirectionalLight directionalLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tdirectLight.color = directionalLight.color;\n\t\tdirectLight.direction = directionalLight.direction;\n\t\tdirectLight.visible = true;\n\t}\n#endif\n#if NUM_POINT_LIGHTS > 0\n\tstruct PointLight {\n\t\tvec3 position;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform PointLight pointLights[ NUM_POINT_LIGHTS ];\n\tvoid getPointDirectLightIrradiance( const in PointLight pointLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = pointLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tdirectLight.color = pointLight.color;\n\t\tdirectLight.color *= punctualLightIntensityToIrradianceFactor( lightDistance, pointLight.distance, pointLight.decay );\n\t\tdirectLight.visible = ( directLight.color != vec3( 0.0 ) );\n\t}\n#endif\n#if NUM_SPOT_LIGHTS > 0\n\tstruct SpotLight {\n\t\tvec3 position;\n\t\tvec3 direction;\n\t\tvec3 color;\n\t\tfloat distance;\n\t\tfloat decay;\n\t\tfloat coneCos;\n\t\tfloat penumbraCos;\n\t\tint shadow;\n\t\tfloat shadowBias;\n\t\tfloat shadowRadius;\n\t\tvec2 shadowMapSize;\n\t};\n\tuniform SpotLight spotLights[ NUM_SPOT_LIGHTS ];\n\tvoid getSpotDirectLightIrradiance( const in SpotLight spotLight, const in GeometricContext geometry, out IncidentLight directLight ) {\n\t\tvec3 lVector = spotLight.position - geometry.position;\n\t\tdirectLight.direction = normalize( lVector );\n\t\tfloat lightDistance = length( lVector );\n\t\tfloat angleCos = dot( directLight.direction, spotLight.direction );\n\t\tif ( angleCos > spotLight.coneCos ) {\n\t\t\tfloat spotEffect = smoothstep( spotLight.coneCos, spotLight.penumbraCos, angleCos );\n\t\t\tdirectLight.color = spotLight.color;\n\t\t\tdirectLight.color *= spotEffect * punctualLightIntensityToIrradianceFactor( lightDistance, spotLight.distance, spotLight.decay );\n\t\t\tdirectLight.visible = true;\n\t\t} else {\n\t\t\tdirectLight.color = vec3( 0.0 );\n\t\t\tdirectLight.visible = false;\n\t\t}\n\t}\n#endif\n#if NUM_RECT_AREA_LIGHTS > 0\n\tstruct RectAreaLight {\n\t\tvec3 color;\n\t\tvec3 position;\n\t\tvec3 halfWidth;\n\t\tvec3 halfHeight;\n\t};\n\tuniform sampler2D ltcMat;\tuniform sampler2D ltcMag;\n\tuniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ];\n#endif\n#if NUM_HEMI_LIGHTS > 0\n\tstruct HemisphereLight {\n\t\tvec3 direction;\n\t\tvec3 skyColor;\n\t\tvec3 groundColor;\n\t};\n\tuniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ];\n\tvec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in GeometricContext geometry ) {\n\t\tfloat dotNL = dot( geometry.normal, hemiLight.direction );\n\t\tfloat hemiDiffuseWeight = 0.5 * dotNL + 0.5;\n\t\tvec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight );\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tirradiance *= PI;\n\t\t#endif\n\t\treturn irradiance;\n\t}\n#endif\n#if defined( USE_ENVMAP ) && defined( PHYSICAL )\n\tvec3 getLightProbeIndirectIrradiance( const in GeometricContext geometry, const in int maxMIPLevel ) {\n\t\tvec3 worldNormal = inverseTransformDirection( geometry.normal, viewMatrix );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryVec, float( maxMIPLevel ) );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryVec = vec3( flipEnvMap * worldNormal.x, worldNormal.yz );\n\t\t\tvec4 envMapColor = textureCubeUV( queryVec, 1.0 );\n\t\t#else\n\t\t\tvec4 envMapColor = vec4( 0.0 );\n\t\t#endif\n\t\treturn PI * envMapColor.rgb * envMapIntensity;\n\t}\n\tfloat getSpecularMIPLevel( const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\tfloat maxMIPLevelScalar = float( maxMIPLevel );\n\t\tfloat desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( pow2( blinnShininessExponent ) + 1.0 );\n\t\treturn clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );\n\t}\n\tvec3 getLightProbeIndirectRadiance( const in GeometricContext geometry, const in float blinnShininessExponent, const in int maxMIPLevel ) {\n\t\t#ifdef ENVMAP_MODE_REFLECTION\n\t\t\tvec3 reflectVec = reflect( -geometry.viewDir, geometry.normal );\n\t\t#else\n\t\t\tvec3 reflectVec = refract( -geometry.viewDir, geometry.normal, refractionRatio );\n\t\t#endif\n\t\treflectVec = inverseTransformDirection( reflectVec, viewMatrix );\n\t\tfloat specularMIPLevel = getSpecularMIPLevel( blinnShininessExponent, maxMIPLevel );\n\t\t#ifdef ENVMAP_TYPE_CUBE\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = textureCubeLodEXT( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = textureCube( envMap, queryReflectVec, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_CUBE_UV )\n\t\t\tvec3 queryReflectVec = vec3( flipEnvMap * reflectVec.x, reflectVec.yz );\n\t\t\tvec4 envMapColor = textureCubeUV(queryReflectVec, BlinnExponentToGGXRoughness(blinnShininessExponent));\n\t\t#elif defined( ENVMAP_TYPE_EQUIREC )\n\t\t\tvec2 sampleUV;\n\t\t\tsampleUV.y = saturate( reflectVec.y * 0.5 + 0.5 );\n\t\t\tsampleUV.x = atan( reflectVec.z, reflectVec.x ) * RECIPROCAL_PI2 + 0.5;\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, sampleUV, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, sampleUV, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#elif defined( ENVMAP_TYPE_SPHERE )\n\t\t\tvec3 reflectView = normalize( ( viewMatrix * vec4( reflectVec, 0.0 ) ).xyz + vec3( 0.0,0.0,1.0 ) );\n\t\t\t#ifdef TEXTURE_LOD_EXT\n\t\t\t\tvec4 envMapColor = texture2DLodEXT( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#else\n\t\t\t\tvec4 envMapColor = texture2D( envMap, reflectView.xy * 0.5 + 0.5, specularMIPLevel );\n\t\t\t#endif\n\t\t\tenvMapColor.rgb = envMapTexelToLinear( envMapColor ).rgb;\n\t\t#endif\n\t\treturn envMapColor.rgb * envMapIntensity;\n\t}\n#endif\n";
  7296. var lights_phong_fragment = "BlinnPhongMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb;\nmaterial.specularColor = specular;\nmaterial.specularShininess = shininess;\nmaterial.specularStrength = specularStrength;\n";
  7297. var lights_phong_pars_fragment = "varying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\nstruct BlinnPhongMaterial {\n\tvec3\tdiffuseColor;\n\tvec3\tspecularColor;\n\tfloat\tspecularShininess;\n\tfloat\tspecularStrength;\n};\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_BlinnPhong( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = BlinnExponentToGGXRoughness( material.specularShininess );\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec / PI2;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff / PI2;\n }\n#endif\nvoid RE_Direct_BlinnPhong( const in IncidentLight directLight, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifdef TOON\n\t\tvec3 irradiance = getGradientIrradiance( geometry.normal, directLight.direction ) * directLight.color;\n\t#else\n\t\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\t\tvec3 irradiance = dotNL * directLight.color;\n\t#endif\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_BlinnPhong( directLight, geometry, material.specularColor, material.specularShininess ) * material.specularStrength;\n}\nvoid RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in GeometricContext geometry, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\n#define RE_Direct\t\t\t\tRE_Direct_BlinnPhong\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_BlinnPhong\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_BlinnPhong\n#define Material_LightProbeLOD( material )\t(0)\n";
  7298. var lights_physical_fragment = "PhysicalMaterial material;\nmaterial.diffuseColor = diffuseColor.rgb * ( 1.0 - metalnessFactor );\nmaterial.specularRoughness = clamp( roughnessFactor, 0.04, 1.0 );\n#ifdef STANDARD\n\tmaterial.specularColor = mix( vec3( DEFAULT_SPECULAR_COEFFICIENT ), diffuseColor.rgb, metalnessFactor );\n#else\n\tmaterial.specularColor = mix( vec3( MAXIMUM_SPECULAR_COEFFICIENT * pow2( reflectivity ) ), diffuseColor.rgb, metalnessFactor );\n\tmaterial.clearCoat = saturate( clearCoat );\tmaterial.clearCoatRoughness = clamp( clearCoatRoughness, 0.04, 1.0 );\n#endif\n";
  7299. var lights_physical_pars_fragment = "struct PhysicalMaterial {\n\tvec3\tdiffuseColor;\n\tfloat\tspecularRoughness;\n\tvec3\tspecularColor;\n\t#ifndef STANDARD\n\t\tfloat clearCoat;\n\t\tfloat clearCoatRoughness;\n\t#endif\n};\n#define MAXIMUM_SPECULAR_COEFFICIENT 0.16\n#define DEFAULT_SPECULAR_COEFFICIENT 0.04\nfloat clearCoatDHRApprox( const in float roughness, const in float dotNL ) {\n\treturn DEFAULT_SPECULAR_COEFFICIENT + ( 1.0 - DEFAULT_SPECULAR_COEFFICIENT ) * ( pow( 1.0 - dotNL, 5.0 ) * pow( 1.0 - roughness, 2.0 ) );\n}\n#if NUM_RECT_AREA_LIGHTS > 0\n void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n vec3 matDiffColor = material.diffuseColor;\n vec3 matSpecColor = material.specularColor;\n vec3 lightColor = rectAreaLight.color;\n float roughness = material.specularRoughness;\n vec3 spec = Rect_Area_Light_Specular_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight,\n roughness,\n ltcMat, ltcMag );\n vec3 diff = Rect_Area_Light_Diffuse_Reflectance(\n geometry,\n rectAreaLight.position, rectAreaLight.halfWidth, rectAreaLight.halfHeight );\n reflectedLight.directSpecular += lightColor * matSpecColor * spec;\n reflectedLight.directDiffuse += lightColor * matDiffColor * diff;\n }\n#endif\nvoid RE_Direct_Physical( const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\tfloat dotNL = saturate( dot( geometry.normal, directLight.direction ) );\n\tvec3 irradiance = dotNL * directLight.color;\n\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\tirradiance *= PI;\n\t#endif\n\t#ifndef STANDARD\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.directSpecular += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Specular_GGX( directLight, geometry, material.specularColor, material.specularRoughness );\n\treflectedLight.directDiffuse += ( 1.0 - clearCoatDHR ) * irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n\t#ifndef STANDARD\n\t\treflectedLight.directSpecular += irradiance * material.clearCoat * BRDF_Specular_GGX( directLight, geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\nvoid RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert( material.diffuseColor );\n}\nvoid RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 clearCoatRadiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) {\n\t#ifndef STANDARD\n\t\tfloat dotNV = saturate( dot( geometry.normal, geometry.viewDir ) );\n\t\tfloat dotNL = dotNV;\n\t\tfloat clearCoatDHR = material.clearCoat * clearCoatDHRApprox( material.clearCoatRoughness, dotNL );\n\t#else\n\t\tfloat clearCoatDHR = 0.0;\n\t#endif\n\treflectedLight.indirectSpecular += ( 1.0 - clearCoatDHR ) * radiance * BRDF_Specular_GGX_Environment( geometry, material.specularColor, material.specularRoughness );\n\t#ifndef STANDARD\n\t\treflectedLight.indirectSpecular += clearCoatRadiance * material.clearCoat * BRDF_Specular_GGX_Environment( geometry, vec3( DEFAULT_SPECULAR_COEFFICIENT ), material.clearCoatRoughness );\n\t#endif\n}\n#define RE_Direct\t\t\t\tRE_Direct_Physical\n#define RE_Direct_RectArea\t\tRE_Direct_RectArea_Physical\n#define RE_IndirectDiffuse\t\tRE_IndirectDiffuse_Physical\n#define RE_IndirectSpecular\t\tRE_IndirectSpecular_Physical\n#define Material_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.specularRoughness )\n#define Material_ClearCoat_BlinnShininessExponent( material ) GGXRoughnessToBlinnExponent( material.clearCoatRoughness )\nfloat computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) {\n\treturn saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion );\n}\n";
  7300. var lights_template = "\nGeometricContext geometry;\ngeometry.position = - vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize( vViewPosition );\nIncidentLight directLight;\n#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct )\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tgetPointDirectLightIrradiance( pointLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( pointLight.shadow, directLight.visible ) ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct )\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tgetSpotDirectLightIrradiance( spotLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( spotLight.shadow, directLight.visible ) ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tgetDirectionalDirectLightIrradiance( directionalLight, geometry, directLight );\n\t\t#ifdef USE_SHADOWMAP\n\t\tdirectLight.color *= all( bvec2( directionalLight.shadow, directLight.visible ) ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t\t#endif\n\t\tRE_Direct( directLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea )\n\tRectAreaLight rectAreaLight;\n\tfor ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) {\n\t\trectAreaLight = rectAreaLights[ i ];\n\t\tRE_Direct_RectArea( rectAreaLight, geometry, material, reflectedLight );\n\t}\n#endif\n#if defined( RE_IndirectDiffuse )\n\tvec3 irradiance = getAmbientLightIrradiance( ambientLightColor );\n\t#ifdef USE_LIGHTMAP\n\t\tvec3 lightMapIrradiance = texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t\t#ifndef PHYSICALLY_CORRECT_LIGHTS\n\t\t\tlightMapIrradiance *= PI;\n\t\t#endif\n\t\tirradiance += lightMapIrradiance;\n\t#endif\n\t#if ( NUM_HEMI_LIGHTS > 0 )\n\t\tfor ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) {\n\t\t\tirradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometry );\n\t\t}\n\t#endif\n\t#if defined( USE_ENVMAP ) && defined( PHYSICAL ) && defined( ENVMAP_TYPE_CUBE_UV )\n\t \tirradiance += getLightProbeIndirectIrradiance( geometry, 8 );\n\t#endif\n\tRE_IndirectDiffuse( irradiance, geometry, material, reflectedLight );\n#endif\n#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular )\n\tvec3 radiance = getLightProbeIndirectRadiance( geometry, Material_BlinnShininessExponent( material ), 8 );\n\t#ifndef STANDARD\n\t\tvec3 clearCoatRadiance = getLightProbeIndirectRadiance( geometry, Material_ClearCoat_BlinnShininessExponent( material ), 8 );\n\t#else\n\t\tvec3 clearCoatRadiance = vec3( 0.0 );\n\t#endif\n\t\t\n\tRE_IndirectSpecular( radiance, clearCoatRadiance, geometry, material, reflectedLight );\n#endif\n";
  7301. var logdepthbuf_fragment = "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)\n\tgl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;\n#endif";
  7302. var logdepthbuf_pars_fragment = "#ifdef USE_LOGDEPTHBUF\n\tuniform float logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n#endif\n";
  7303. var logdepthbuf_pars_vertex = "#ifdef USE_LOGDEPTHBUF\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvarying float vFragDepth;\n\t#endif\n\tuniform float logDepthBufFC;\n#endif";
  7304. var logdepthbuf_vertex = "#ifdef USE_LOGDEPTHBUF\n\tgl_Position.z = log2(max( EPSILON, gl_Position.w + 1.0 )) * logDepthBufFC;\n\t#ifdef USE_LOGDEPTHBUF_EXT\n\t\tvFragDepth = 1.0 + gl_Position.w;\n\t#else\n\t\tgl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;\n\t#endif\n#endif\n";
  7305. var map_fragment = "#ifdef USE_MAP\n\tvec4 texelColor = texture2D( map, vUv );\n\ttexelColor = mapTexelToLinear( texelColor );\n\tdiffuseColor *= texelColor;\n#endif\n";
  7306. var map_pars_fragment = "#ifdef USE_MAP\n\tuniform sampler2D map;\n#endif\n";
  7307. var map_particle_fragment = "#ifdef USE_MAP\n\tvec4 mapTexel = texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) * offsetRepeat.zw + offsetRepeat.xy );\n\tdiffuseColor *= mapTexelToLinear( mapTexel );\n#endif\n";
  7308. var map_particle_pars_fragment = "#ifdef USE_MAP\n\tuniform vec4 offsetRepeat;\n\tuniform sampler2D map;\n#endif\n";
  7309. var metalnessmap_fragment = "float metalnessFactor = metalness;\n#ifdef USE_METALNESSMAP\n\tvec4 texelMetalness = texture2D( metalnessMap, vUv );\n\tmetalnessFactor *= texelMetalness.r;\n#endif\n";
  7310. var metalnessmap_pars_fragment = "#ifdef USE_METALNESSMAP\n\tuniform sampler2D metalnessMap;\n#endif";
  7311. var morphnormal_vertex = "#ifdef USE_MORPHNORMALS\n\tobjectNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];\n\tobjectNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];\n\tobjectNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];\n\tobjectNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];\n#endif\n";
  7312. var morphtarget_pars_vertex = "#ifdef USE_MORPHTARGETS\n\t#ifndef USE_MORPHNORMALS\n\tuniform float morphTargetInfluences[ 8 ];\n\t#else\n\tuniform float morphTargetInfluences[ 4 ];\n\t#endif\n#endif";
  7313. var morphtarget_vertex = "#ifdef USE_MORPHTARGETS\n\ttransformed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];\n\ttransformed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];\n\ttransformed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];\n\ttransformed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];\n\t#ifndef USE_MORPHNORMALS\n\ttransformed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];\n\ttransformed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];\n\ttransformed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];\n\ttransformed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];\n\t#endif\n#endif\n";
  7314. var normal_flip = "#ifdef DOUBLE_SIDED\n\tfloat flipNormal = ( float( gl_FrontFacing ) * 2.0 - 1.0 );\n#else\n\tfloat flipNormal = 1.0;\n#endif\n";
  7315. var normal_fragment = "#ifdef FLAT_SHADED\n\tvec3 fdx = vec3( dFdx( vViewPosition.x ), dFdx( vViewPosition.y ), dFdx( vViewPosition.z ) );\n\tvec3 fdy = vec3( dFdy( vViewPosition.x ), dFdy( vViewPosition.y ), dFdy( vViewPosition.z ) );\n\tvec3 normal = normalize( cross( fdx, fdy ) );\n#else\n\tvec3 normal = normalize( vNormal ) * flipNormal;\n#endif\n#ifdef USE_NORMALMAP\n\tnormal = perturbNormal2Arb( -vViewPosition, normal );\n#elif defined( USE_BUMPMAP )\n\tnormal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );\n#endif\n";
  7316. var normalmap_pars_fragment = "#ifdef USE_NORMALMAP\n\tuniform sampler2D normalMap;\n\tuniform vec2 normalScale;\n\tvec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {\n\t\tvec3 q0 = dFdx( eye_pos.xyz );\n\t\tvec3 q1 = dFdy( eye_pos.xyz );\n\t\tvec2 st0 = dFdx( vUv.st );\n\t\tvec2 st1 = dFdy( vUv.st );\n\t\tvec3 S = normalize( q0 * st1.t - q1 * st0.t );\n\t\tvec3 T = normalize( -q0 * st1.s + q1 * st0.s );\n\t\tvec3 N = normalize( surf_norm );\n\t\tvec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;\n\t\tmapN.xy = normalScale * mapN.xy;\n\t\tmat3 tsn = mat3( S, T, N );\n\t\treturn normalize( tsn * mapN );\n\t}\n#endif\n";
  7317. var packing = "vec3 packNormalToRGB( const in vec3 normal ) {\n return normalize( normal ) * 0.5 + 0.5;\n}\nvec3 unpackRGBToNormal( const in vec3 rgb ) {\n return 1.0 - 2.0 * rgb.xyz;\n}\nconst float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;\nconst vec3 PackFactors = vec3( 256. * 256. * 256., 256. * 256., 256. );\nconst vec4 UnpackFactors = UnpackDownscale / vec4( PackFactors, 1. );\nconst float ShiftRight8 = 1. / 256.;\nvec4 packDepthToRGBA( const in float v ) {\n\tvec4 r = vec4( fract( v * PackFactors ), v );\n\tr.yzw -= r.xyz * ShiftRight8;\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth( const in vec4 v ) {\n\treturn dot( v, UnpackFactors );\n}\nfloat viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) {\n return ( viewZ + near ) / ( near - far );\n}\nfloat orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n return linearClipZ * ( near - far ) - near;\n}\nfloat viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) {\n return (( near + viewZ ) * far ) / (( far - near ) * viewZ );\n}\nfloat perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n return ( near * far ) / ( ( far - near ) * invClipZ - far );\n}\n";
  7318. var premultiplied_alpha_fragment = "#ifdef PREMULTIPLIED_ALPHA\n\tgl_FragColor.rgb *= gl_FragColor.a;\n#endif\n";
  7319. var project_vertex = "#ifdef USE_SKINNING\n\tvec4 mvPosition = modelViewMatrix * skinned;\n#else\n\tvec4 mvPosition = modelViewMatrix * vec4( transformed, 1.0 );\n#endif\ngl_Position = projectionMatrix * mvPosition;\n";
  7320. var roughnessmap_fragment = "float roughnessFactor = roughness;\n#ifdef USE_ROUGHNESSMAP\n\tvec4 texelRoughness = texture2D( roughnessMap, vUv );\n\troughnessFactor *= texelRoughness.r;\n#endif\n";
  7321. var roughnessmap_pars_fragment = "#ifdef USE_ROUGHNESSMAP\n\tuniform sampler2D roughnessMap;\n#endif";
  7322. var shadowmap_pars_fragment = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform sampler2D directionalShadowMap[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform sampler2D spotShadowMap[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform sampler2D pointShadowMap[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n\tfloat texture2DCompare( sampler2D depths, vec2 uv, float compare ) {\n\t\treturn step( compare, unpackRGBAToDepth( texture2D( depths, uv ) ) );\n\t}\n\tfloat texture2DShadowLerp( sampler2D depths, vec2 size, vec2 uv, float compare ) {\n\t\tconst vec2 offset = vec2( 0.0, 1.0 );\n\t\tvec2 texelSize = vec2( 1.0 ) / size;\n\t\tvec2 centroidUV = floor( uv * size + 0.5 ) / size;\n\t\tfloat lb = texture2DCompare( depths, centroidUV + texelSize * offset.xx, compare );\n\t\tfloat lt = texture2DCompare( depths, centroidUV + texelSize * offset.xy, compare );\n\t\tfloat rb = texture2DCompare( depths, centroidUV + texelSize * offset.yx, compare );\n\t\tfloat rt = texture2DCompare( depths, centroidUV + texelSize * offset.yy, compare );\n\t\tvec2 f = fract( uv * size + 0.5 );\n\t\tfloat a = mix( lb, lt, f.y );\n\t\tfloat b = mix( rb, rt, f.y );\n\t\tfloat c = mix( a, b, f.x );\n\t\treturn c;\n\t}\n\tfloat getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tshadowCoord.xyz /= shadowCoord.w;\n\t\tshadowCoord.z += shadowBias;\n\t\tbvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );\n\t\tbool inFrustum = all( inFrustumVec );\n\t\tbvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );\n\t\tbool frustumTest = all( frustumTestVec );\n\t\tif ( frustumTest ) {\n\t\t#if defined( SHADOWMAP_TYPE_PCF )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DCompare( shadowMap, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#elif defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 texelSize = vec2( 1.0 ) / shadowMapSize;\n\t\t\tfloat dx0 = - texelSize.x * shadowRadius;\n\t\t\tfloat dy0 = - texelSize.y * shadowRadius;\n\t\t\tfloat dx1 = + texelSize.x * shadowRadius;\n\t\t\tfloat dy1 = + texelSize.y * shadowRadius;\n\t\t\treturn (\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy, shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, 0.0 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( 0.0, dy1 ), shadowCoord.z ) +\n\t\t\t\ttexture2DShadowLerp( shadowMap, shadowMapSize, shadowCoord.xy + vec2( dx1, dy1 ), shadowCoord.z )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, shadowCoord.xy, shadowCoord.z );\n\t\t#endif\n\t\t}\n\t\treturn 1.0;\n\t}\n\tvec2 cubeToUV( vec3 v, float texelSizeY ) {\n\t\tvec3 absV = abs( v );\n\t\tfloat scaleToCube = 1.0 / max( absV.x, max( absV.y, absV.z ) );\n\t\tabsV *= scaleToCube;\n\t\tv *= scaleToCube * ( 1.0 - 2.0 * texelSizeY );\n\t\tvec2 planar = v.xy;\n\t\tfloat almostATexel = 1.5 * texelSizeY;\n\t\tfloat almostOne = 1.0 - almostATexel;\n\t\tif ( absV.z >= almostOne ) {\n\t\t\tif ( v.z > 0.0 )\n\t\t\t\tplanar.x = 4.0 - v.x;\n\t\t} else if ( absV.x >= almostOne ) {\n\t\t\tfloat signX = sign( v.x );\n\t\t\tplanar.x = v.z * signX + 2.0 * signX;\n\t\t} else if ( absV.y >= almostOne ) {\n\t\t\tfloat signY = sign( v.y );\n\t\t\tplanar.x = v.x + 2.0 * signY + 2.0;\n\t\t\tplanar.y = v.z * signY - 2.0;\n\t\t}\n\t\treturn vec2( 0.125, 0.25 ) * planar + vec2( 0.375, 0.75 );\n\t}\n\tfloat getPointShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowBias, float shadowRadius, vec4 shadowCoord ) {\n\t\tvec2 texelSize = vec2( 1.0 ) / ( shadowMapSize * vec2( 4.0, 2.0 ) );\n\t\tvec3 lightToPosition = shadowCoord.xyz;\n\t\tvec3 bd3D = normalize( lightToPosition );\n\t\tfloat dp = ( length( lightToPosition ) - shadowBias ) / 1000.0;\n\t\t#if defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_PCF_SOFT )\n\t\t\tvec2 offset = vec2( - 1, 1 ) * shadowRadius * texelSize.y;\n\t\t\treturn (\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yyx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxy, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.xxx, texelSize.y ), dp ) +\n\t\t\t\ttexture2DCompare( shadowMap, cubeToUV( bd3D + offset.yxx, texelSize.y ), dp )\n\t\t\t) * ( 1.0 / 9.0 );\n\t\t#else\n\t\t\treturn texture2DCompare( shadowMap, cubeToUV( bd3D, texelSize.y ), dp );\n\t\t#endif\n\t}\n#endif\n";
  7323. var shadowmap_pars_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\t\tuniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHTS ];\n\t\tvarying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHTS ];\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\t\tuniform mat4 spotShadowMatrix[ NUM_SPOT_LIGHTS ];\n\t\tvarying vec4 vSpotShadowCoord[ NUM_SPOT_LIGHTS ];\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\t\tuniform mat4 pointShadowMatrix[ NUM_POINT_LIGHTS ];\n\t\tvarying vec4 vPointShadowCoord[ NUM_POINT_LIGHTS ];\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  7324. var shadowmap_vertex = "#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tvDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tvSpotShadowCoord[ i ] = spotShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tvPointShadowCoord[ i ] = pointShadowMatrix[ i ] * worldPosition;\n\t}\n\t#endif\n #if NUM_RECT_AREA_LIGHTS > 0\n #endif\n#endif\n";
  7325. var shadowmask_pars_fragment = "float getShadowMask() {\n\tfloat shadow = 1.0;\n\t#ifdef USE_SHADOWMAP\n\t#if NUM_DIR_LIGHTS > 0\n\tDirectionalLight directionalLight;\n\tfor ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {\n\t\tdirectionalLight = directionalLights[ i ];\n\t\tshadow *= bool( directionalLight.shadow ) ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_SPOT_LIGHTS > 0\n\tSpotLight spotLight;\n\tfor ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) {\n\t\tspotLight = spotLights[ i ];\n\t\tshadow *= bool( spotLight.shadow ) ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowBias, spotLight.shadowRadius, vSpotShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_POINT_LIGHTS > 0\n\tPointLight pointLight;\n\tfor ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) {\n\t\tpointLight = pointLights[ i ];\n\t\tshadow *= bool( pointLight.shadow ) ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ] ) : 1.0;\n\t}\n\t#endif\n\t#if NUM_RECT_AREA_LIGHTS > 0\n\t#endif\n\t#endif\n\treturn shadow;\n}\n";
  7326. var skinbase_vertex = "#ifdef USE_SKINNING\n\tmat4 boneMatX = getBoneMatrix( skinIndex.x );\n\tmat4 boneMatY = getBoneMatrix( skinIndex.y );\n\tmat4 boneMatZ = getBoneMatrix( skinIndex.z );\n\tmat4 boneMatW = getBoneMatrix( skinIndex.w );\n#endif";
  7327. var skinning_pars_vertex = "#ifdef USE_SKINNING\n\tuniform mat4 bindMatrix;\n\tuniform mat4 bindMatrixInverse;\n\t#ifdef BONE_TEXTURE\n\t\tuniform sampler2D boneTexture;\n\t\tuniform int boneTextureWidth;\n\t\tuniform int boneTextureHeight;\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tfloat j = i * 4.0;\n\t\t\tfloat x = mod( j, float( boneTextureWidth ) );\n\t\t\tfloat y = floor( j / float( boneTextureWidth ) );\n\t\t\tfloat dx = 1.0 / float( boneTextureWidth );\n\t\t\tfloat dy = 1.0 / float( boneTextureHeight );\n\t\t\ty = dy * ( y + 0.5 );\n\t\t\tvec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );\n\t\t\tvec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );\n\t\t\tvec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );\n\t\t\tvec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );\n\t\t\tmat4 bone = mat4( v1, v2, v3, v4 );\n\t\t\treturn bone;\n\t\t}\n\t#else\n\t\tuniform mat4 boneMatrices[ MAX_BONES ];\n\t\tmat4 getBoneMatrix( const in float i ) {\n\t\t\tmat4 bone = boneMatrices[ int(i) ];\n\t\t\treturn bone;\n\t\t}\n\t#endif\n#endif\n";
  7328. var skinning_vertex = "#ifdef USE_SKINNING\n\tvec4 skinVertex = bindMatrix * vec4( transformed, 1.0 );\n\tvec4 skinned = vec4( 0.0 );\n\tskinned += boneMatX * skinVertex * skinWeight.x;\n\tskinned += boneMatY * skinVertex * skinWeight.y;\n\tskinned += boneMatZ * skinVertex * skinWeight.z;\n\tskinned += boneMatW * skinVertex * skinWeight.w;\n\tskinned = bindMatrixInverse * skinned;\n#endif\n";
  7329. var skinnormal_vertex = "#ifdef USE_SKINNING\n\tmat4 skinMatrix = mat4( 0.0 );\n\tskinMatrix += skinWeight.x * boneMatX;\n\tskinMatrix += skinWeight.y * boneMatY;\n\tskinMatrix += skinWeight.z * boneMatZ;\n\tskinMatrix += skinWeight.w * boneMatW;\n\tskinMatrix = bindMatrixInverse * skinMatrix * bindMatrix;\n\tobjectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz;\n#endif\n";
  7330. var specularmap_fragment = "float specularStrength;\n#ifdef USE_SPECULARMAP\n\tvec4 texelSpecular = texture2D( specularMap, vUv );\n\tspecularStrength = texelSpecular.r;\n#else\n\tspecularStrength = 1.0;\n#endif";
  7331. var specularmap_pars_fragment = "#ifdef USE_SPECULARMAP\n\tuniform sampler2D specularMap;\n#endif";
  7332. var tonemapping_fragment = "#if defined( TONE_MAPPING )\n gl_FragColor.rgb = toneMapping( gl_FragColor.rgb );\n#endif\n";
  7333. var tonemapping_pars_fragment = "#define saturate(a) clamp( a, 0.0, 1.0 )\nuniform float toneMappingExposure;\nuniform float toneMappingWhitePoint;\nvec3 LinearToneMapping( vec3 color ) {\n return toneMappingExposure * color;\n}\nvec3 ReinhardToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( color / ( vec3( 1.0 ) + color ) );\n}\n#define Uncharted2Helper( x ) max( ( ( x * ( 0.15 * x + 0.10 * 0.50 ) + 0.20 * 0.02 ) / ( x * ( 0.15 * x + 0.50 ) + 0.20 * 0.30 ) ) - 0.02 / 0.30, vec3( 0.0 ) )\nvec3 Uncharted2ToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n return saturate( Uncharted2Helper( color ) / Uncharted2Helper( vec3( toneMappingWhitePoint ) ) );\n}\nvec3 OptimizedCineonToneMapping( vec3 color ) {\n color *= toneMappingExposure;\n color = max( vec3( 0.0 ), color - 0.004 );\n return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) );\n}\n";
  7334. var uv_pars_fragment = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n#endif";
  7335. var uv_pars_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvarying vec2 vUv;\n\tuniform vec4 offsetRepeat;\n#endif\n";
  7336. var uv_vertex = "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP ) || defined( USE_ALPHAMAP ) || defined( USE_EMISSIVEMAP ) || defined( USE_ROUGHNESSMAP ) || defined( USE_METALNESSMAP )\n\tvUv = uv * offsetRepeat.zw + offsetRepeat.xy;\n#endif";
  7337. var uv2_pars_fragment = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvarying vec2 vUv2;\n#endif";
  7338. var uv2_pars_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tattribute vec2 uv2;\n\tvarying vec2 vUv2;\n#endif";
  7339. var uv2_vertex = "#if defined( USE_LIGHTMAP ) || defined( USE_AOMAP )\n\tvUv2 = uv2;\n#endif";
  7340. var worldpos_vertex = "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( PHYSICAL ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )\n\t#ifdef USE_SKINNING\n\t\tvec4 worldPosition = modelMatrix * skinned;\n\t#else\n\t\tvec4 worldPosition = modelMatrix * vec4( transformed, 1.0 );\n\t#endif\n#endif\n";
  7341. var cube_frag = "uniform samplerCube tCube;\nuniform float tFlip;\nuniform float opacity;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tgl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );\n\tgl_FragColor.a *= opacity;\n}\n";
  7342. var cube_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  7343. var depth_frag = "#if DEPTH_PACKING == 3200\n\tuniform float opacity;\n#endif\n#include <common>\n#include <packing>\n#include <uv_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( 1.0 );\n\t#if DEPTH_PACKING == 3200\n\t\tdiffuseColor.a = opacity;\n\t#endif\n\t#include <map_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <logdepthbuf_fragment>\n\t#if DEPTH_PACKING == 3200\n\t\tgl_FragColor = vec4( vec3( gl_FragCoord.z ), opacity );\n\t#elif DEPTH_PACKING == 3201\n\t\tgl_FragColor = packDepthToRGBA( gl_FragCoord.z );\n\t#endif\n}\n";
  7344. var depth_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  7345. var distanceRGBA_frag = "uniform vec3 lightPos;\nvarying vec4 vWorldPosition;\n#include <common>\n#include <packing>\n#include <clipping_planes_pars_fragment>\nvoid main () {\n\t#include <clipping_planes_fragment>\n\tgl_FragColor = packDepthToRGBA( length( vWorldPosition.xyz - lightPos.xyz ) / 1000.0 );\n}\n";
  7346. var distanceRGBA_vert = "varying vec4 vWorldPosition;\n#include <common>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <skinbase_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\tvWorldPosition = worldPosition;\n}\n";
  7347. var equirect_frag = "uniform sampler2D tEquirect;\nuniform float tFlip;\nvarying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvec3 direction = normalize( vWorldPosition );\n\tvec2 sampleUV;\n\tsampleUV.y = saturate( tFlip * direction.y * -0.5 + 0.5 );\n\tsampleUV.x = atan( direction.z, direction.x ) * RECIPROCAL_PI2 + 0.5;\n\tgl_FragColor = texture2D( tEquirect, sampleUV );\n}\n";
  7348. var equirect_vert = "varying vec3 vWorldPosition;\n#include <common>\nvoid main() {\n\tvWorldPosition = transformDirection( position, modelMatrix );\n\t#include <begin_vertex>\n\t#include <project_vertex>\n}\n";
  7349. var linedashed_frag = "uniform vec3 diffuse;\nuniform float opacity;\nuniform float dashSize;\nuniform float totalSize;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_fragment>\n#include <fog_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tif ( mod( vLineDistance, totalSize ) > dashSize ) {\n\t\tdiscard;\n\t}\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <color_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7350. var linedashed_vert = "uniform float scale;\nattribute float lineDistance;\nvarying float vLineDistance;\n#include <common>\n#include <color_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\tvLineDistance = scale * lineDistance;\n\tvec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );\n\tgl_Position = projectionMatrix * mvPosition;\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n}\n";
  7351. var meshbasic_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\t#ifdef USE_LIGHTMAP\n\t\treflectedLight.indirectDiffuse += texture2D( lightMap, vUv2 ).xyz * lightMapIntensity;\n\t#else\n\t\treflectedLight.indirectDiffuse += vec3( 1.0 );\n\t#endif\n\t#include <aomap_fragment>\n\treflectedLight.indirectDiffuse *= diffuseColor.rgb;\n\tvec3 outgoingLight = reflectedLight.indirectDiffuse;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7352. var meshbasic_vert = "#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <skinbase_vertex>\n\t#ifdef USE_ENVMAP\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#endif\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <worldpos_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <envmap_vertex>\n}\n";
  7353. var meshlambert_frag = "uniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float opacity;\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <emissivemap_fragment>\n\treflectedLight.indirectDiffuse = getAmbientLightIrradiance( ambientLightColor );\n\t#include <lightmap_fragment>\n\treflectedLight.indirectDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb );\n\t#ifdef DOUBLE_SIDED\n\t\treflectedLight.directDiffuse = ( gl_FrontFacing ) ? vLightFront : vLightBack;\n\t#else\n\t\treflectedLight.directDiffuse = vLightFront;\n\t#endif\n\treflectedLight.directDiffuse *= BRDF_Diffuse_Lambert( diffuseColor.rgb ) * getShadowMask();\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance;\n\t#include <normal_flip>\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7354. var meshlambert_vert = "#define LAMBERT\nvarying vec3 vLightFront;\n#ifdef DOUBLE_SIDED\n\tvarying vec3 vLightBack;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <envmap_pars_vertex>\n#include <bsdfs>\n#include <lights_pars>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n\t#include <begin_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <lights_lambert_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  7355. var meshphong_frag = "#define PHONG\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform vec3 specular;\nuniform float shininess;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <gradientmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <lights_pars>\n#include <lights_phong_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_phong_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\t#include <envmap_fragment>\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7356. var meshphong_vert = "#define PHONG\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <envmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <envmap_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  7357. var meshphysical_frag = "#define PHYSICAL\nuniform vec3 diffuse;\nuniform vec3 emissive;\nuniform float roughness;\nuniform float metalness;\nuniform float opacity;\n#ifndef STANDARD\n\tuniform float clearCoat;\n\tuniform float clearCoatRoughness;\n#endif\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <uv_pars_fragment>\n#include <uv2_pars_fragment>\n#include <map_pars_fragment>\n#include <alphamap_pars_fragment>\n#include <aomap_pars_fragment>\n#include <lightmap_pars_fragment>\n#include <emissivemap_pars_fragment>\n#include <envmap_pars_fragment>\n#include <fog_pars_fragment>\n#include <bsdfs>\n#include <cube_uv_reflection_fragment>\n#include <lights_pars>\n#include <lights_physical_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <roughnessmap_pars_fragment>\n#include <metalnessmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\tReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\tvec3 totalEmissiveRadiance = emissive;\n\t#include <logdepthbuf_fragment>\n\t#include <map_fragment>\n\t#include <color_fragment>\n\t#include <alphamap_fragment>\n\t#include <alphatest_fragment>\n\t#include <specularmap_fragment>\n\t#include <roughnessmap_fragment>\n\t#include <metalnessmap_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\t#include <emissivemap_fragment>\n\t#include <lights_physical_fragment>\n\t#include <lights_template>\n\t#include <aomap_fragment>\n\tvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7358. var meshphysical_vert = "#define PHYSICAL\nvarying vec3 vViewPosition;\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <common>\n#include <uv_pars_vertex>\n#include <uv2_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <color_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <specularmap_pars_fragment>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <uv2_vertex>\n\t#include <color_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\tvViewPosition = - mvPosition.xyz;\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  7359. var normal_frag = "#define NORMAL\nuniform float opacity;\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <packing>\n#include <uv_pars_fragment>\n#include <bumpmap_pars_fragment>\n#include <normalmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\nvoid main() {\n\t#include <logdepthbuf_fragment>\n\t#include <normal_flip>\n\t#include <normal_fragment>\n\tgl_FragColor = vec4( packNormalToRGB( normal ), opacity );\n\t#include <premultiplied_alpha_fragment>\n\t#include <encodings_fragment>\n}\n";
  7360. var normal_vert = "#define NORMAL\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvarying vec3 vViewPosition;\n#endif\n#ifndef FLAT_SHADED\n\tvarying vec3 vNormal;\n#endif\n#include <uv_pars_vertex>\n#include <displacementmap_pars_vertex>\n#include <morphtarget_pars_vertex>\n#include <skinning_pars_vertex>\n#include <logdepthbuf_pars_vertex>\nvoid main() {\n\t#include <uv_vertex>\n\t#include <beginnormal_vertex>\n\t#include <morphnormal_vertex>\n\t#include <skinbase_vertex>\n\t#include <skinnormal_vertex>\n\t#include <defaultnormal_vertex>\n#ifndef FLAT_SHADED\n\tvNormal = normalize( transformedNormal );\n#endif\n\t#include <begin_vertex>\n\t#include <displacementmap_vertex>\n\t#include <morphtarget_vertex>\n\t#include <skinning_vertex>\n\t#include <project_vertex>\n\t#include <logdepthbuf_vertex>\n#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )\n\tvViewPosition = - mvPosition.xyz;\n#endif\n}\n";
  7361. var points_frag = "uniform vec3 diffuse;\nuniform float opacity;\n#include <common>\n#include <packing>\n#include <color_pars_fragment>\n#include <map_particle_pars_fragment>\n#include <fog_pars_fragment>\n#include <shadowmap_pars_fragment>\n#include <logdepthbuf_pars_fragment>\n#include <clipping_planes_pars_fragment>\nvoid main() {\n\t#include <clipping_planes_fragment>\n\tvec3 outgoingLight = vec3( 0.0 );\n\tvec4 diffuseColor = vec4( diffuse, opacity );\n\t#include <logdepthbuf_fragment>\n\t#include <map_particle_fragment>\n\t#include <color_fragment>\n\t#include <alphatest_fragment>\n\toutgoingLight = diffuseColor.rgb;\n\tgl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\t#include <premultiplied_alpha_fragment>\n\t#include <tonemapping_fragment>\n\t#include <encodings_fragment>\n\t#include <fog_fragment>\n}\n";
  7362. var points_vert = "uniform float size;\nuniform float scale;\n#include <common>\n#include <color_pars_vertex>\n#include <shadowmap_pars_vertex>\n#include <logdepthbuf_pars_vertex>\n#include <clipping_planes_pars_vertex>\nvoid main() {\n\t#include <color_vertex>\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#ifdef USE_SIZEATTENUATION\n\t\tgl_PointSize = size * ( scale / - mvPosition.z );\n\t#else\n\t\tgl_PointSize = size;\n\t#endif\n\t#include <logdepthbuf_vertex>\n\t#include <clipping_planes_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  7363. var shadow_frag = "uniform float opacity;\n#include <common>\n#include <packing>\n#include <bsdfs>\n#include <lights_pars>\n#include <shadowmap_pars_fragment>\n#include <shadowmask_pars_fragment>\nvoid main() {\n\tgl_FragColor = vec4( 0.0, 0.0, 0.0, opacity * ( 1.0 - getShadowMask() ) );\n}\n";
  7364. var shadow_vert = "#include <shadowmap_pars_vertex>\nvoid main() {\n\t#include <begin_vertex>\n\t#include <project_vertex>\n\t#include <worldpos_vertex>\n\t#include <shadowmap_vertex>\n}\n";
  7365. var ShaderChunk = {
  7366. alphamap_fragment: alphamap_fragment,
  7367. alphamap_pars_fragment: alphamap_pars_fragment,
  7368. alphatest_fragment: alphatest_fragment,
  7369. aomap_fragment: aomap_fragment,
  7370. aomap_pars_fragment: aomap_pars_fragment,
  7371. begin_vertex: begin_vertex,
  7372. beginnormal_vertex: beginnormal_vertex,
  7373. bsdfs: bsdfs,
  7374. bumpmap_pars_fragment: bumpmap_pars_fragment,
  7375. clipping_planes_fragment: clipping_planes_fragment,
  7376. clipping_planes_pars_fragment: clipping_planes_pars_fragment,
  7377. clipping_planes_pars_vertex: clipping_planes_pars_vertex,
  7378. clipping_planes_vertex: clipping_planes_vertex,
  7379. color_fragment: color_fragment,
  7380. color_pars_fragment: color_pars_fragment,
  7381. color_pars_vertex: color_pars_vertex,
  7382. color_vertex: color_vertex,
  7383. common: common,
  7384. cube_uv_reflection_fragment: cube_uv_reflection_fragment,
  7385. defaultnormal_vertex: defaultnormal_vertex,
  7386. displacementmap_pars_vertex: displacementmap_pars_vertex,
  7387. displacementmap_vertex: displacementmap_vertex,
  7388. emissivemap_fragment: emissivemap_fragment,
  7389. emissivemap_pars_fragment: emissivemap_pars_fragment,
  7390. encodings_fragment: encodings_fragment,
  7391. encodings_pars_fragment: encodings_pars_fragment,
  7392. envmap_fragment: envmap_fragment,
  7393. envmap_pars_fragment: envmap_pars_fragment,
  7394. envmap_pars_vertex: envmap_pars_vertex,
  7395. envmap_vertex: envmap_vertex,
  7396. fog_fragment: fog_fragment,
  7397. fog_pars_fragment: fog_pars_fragment,
  7398. gradientmap_pars_fragment: gradientmap_pars_fragment,
  7399. lightmap_fragment: lightmap_fragment,
  7400. lightmap_pars_fragment: lightmap_pars_fragment,
  7401. lights_lambert_vertex: lights_lambert_vertex,
  7402. lights_pars: lights_pars,
  7403. lights_phong_fragment: lights_phong_fragment,
  7404. lights_phong_pars_fragment: lights_phong_pars_fragment,
  7405. lights_physical_fragment: lights_physical_fragment,
  7406. lights_physical_pars_fragment: lights_physical_pars_fragment,
  7407. lights_template: lights_template,
  7408. logdepthbuf_fragment: logdepthbuf_fragment,
  7409. logdepthbuf_pars_fragment: logdepthbuf_pars_fragment,
  7410. logdepthbuf_pars_vertex: logdepthbuf_pars_vertex,
  7411. logdepthbuf_vertex: logdepthbuf_vertex,
  7412. map_fragment: map_fragment,
  7413. map_pars_fragment: map_pars_fragment,
  7414. map_particle_fragment: map_particle_fragment,
  7415. map_particle_pars_fragment: map_particle_pars_fragment,
  7416. metalnessmap_fragment: metalnessmap_fragment,
  7417. metalnessmap_pars_fragment: metalnessmap_pars_fragment,
  7418. morphnormal_vertex: morphnormal_vertex,
  7419. morphtarget_pars_vertex: morphtarget_pars_vertex,
  7420. morphtarget_vertex: morphtarget_vertex,
  7421. normal_flip: normal_flip,
  7422. normal_fragment: normal_fragment,
  7423. normalmap_pars_fragment: normalmap_pars_fragment,
  7424. packing: packing,
  7425. premultiplied_alpha_fragment: premultiplied_alpha_fragment,
  7426. project_vertex: project_vertex,
  7427. roughnessmap_fragment: roughnessmap_fragment,
  7428. roughnessmap_pars_fragment: roughnessmap_pars_fragment,
  7429. shadowmap_pars_fragment: shadowmap_pars_fragment,
  7430. shadowmap_pars_vertex: shadowmap_pars_vertex,
  7431. shadowmap_vertex: shadowmap_vertex,
  7432. shadowmask_pars_fragment: shadowmask_pars_fragment,
  7433. skinbase_vertex: skinbase_vertex,
  7434. skinning_pars_vertex: skinning_pars_vertex,
  7435. skinning_vertex: skinning_vertex,
  7436. skinnormal_vertex: skinnormal_vertex,
  7437. specularmap_fragment: specularmap_fragment,
  7438. specularmap_pars_fragment: specularmap_pars_fragment,
  7439. tonemapping_fragment: tonemapping_fragment,
  7440. tonemapping_pars_fragment: tonemapping_pars_fragment,
  7441. uv_pars_fragment: uv_pars_fragment,
  7442. uv_pars_vertex: uv_pars_vertex,
  7443. uv_vertex: uv_vertex,
  7444. uv2_pars_fragment: uv2_pars_fragment,
  7445. uv2_pars_vertex: uv2_pars_vertex,
  7446. uv2_vertex: uv2_vertex,
  7447. worldpos_vertex: worldpos_vertex,
  7448. cube_frag: cube_frag,
  7449. cube_vert: cube_vert,
  7450. depth_frag: depth_frag,
  7451. depth_vert: depth_vert,
  7452. distanceRGBA_frag: distanceRGBA_frag,
  7453. distanceRGBA_vert: distanceRGBA_vert,
  7454. equirect_frag: equirect_frag,
  7455. equirect_vert: equirect_vert,
  7456. linedashed_frag: linedashed_frag,
  7457. linedashed_vert: linedashed_vert,
  7458. meshbasic_frag: meshbasic_frag,
  7459. meshbasic_vert: meshbasic_vert,
  7460. meshlambert_frag: meshlambert_frag,
  7461. meshlambert_vert: meshlambert_vert,
  7462. meshphong_frag: meshphong_frag,
  7463. meshphong_vert: meshphong_vert,
  7464. meshphysical_frag: meshphysical_frag,
  7465. meshphysical_vert: meshphysical_vert,
  7466. normal_frag: normal_frag,
  7467. normal_vert: normal_vert,
  7468. points_frag: points_frag,
  7469. points_vert: points_vert,
  7470. shadow_frag: shadow_frag,
  7471. shadow_vert: shadow_vert
  7472. };
  7473. /**
  7474. * @author mrdoob / http://mrdoob.com/
  7475. */
  7476. function Color( r, g, b ) {
  7477. if ( g === undefined && b === undefined ) {
  7478. // r is THREE.Color, hex or string
  7479. return this.set( r );
  7480. }
  7481. return this.setRGB( r, g, b );
  7482. }
  7483. Color.prototype = {
  7484. constructor: Color,
  7485. isColor: true,
  7486. r: 1, g: 1, b: 1,
  7487. set: function ( value ) {
  7488. if ( value && value.isColor ) {
  7489. this.copy( value );
  7490. } else if ( typeof value === 'number' ) {
  7491. this.setHex( value );
  7492. } else if ( typeof value === 'string' ) {
  7493. this.setStyle( value );
  7494. }
  7495. return this;
  7496. },
  7497. setScalar: function ( scalar ) {
  7498. this.r = scalar;
  7499. this.g = scalar;
  7500. this.b = scalar;
  7501. return this;
  7502. },
  7503. setHex: function ( hex ) {
  7504. hex = Math.floor( hex );
  7505. this.r = ( hex >> 16 & 255 ) / 255;
  7506. this.g = ( hex >> 8 & 255 ) / 255;
  7507. this.b = ( hex & 255 ) / 255;
  7508. return this;
  7509. },
  7510. setRGB: function ( r, g, b ) {
  7511. this.r = r;
  7512. this.g = g;
  7513. this.b = b;
  7514. return this;
  7515. },
  7516. setHSL: function () {
  7517. function hue2rgb( p, q, t ) {
  7518. if ( t < 0 ) t += 1;
  7519. if ( t > 1 ) t -= 1;
  7520. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  7521. if ( t < 1 / 2 ) return q;
  7522. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  7523. return p;
  7524. }
  7525. return function setHSL( h, s, l ) {
  7526. // h,s,l ranges are in 0.0 - 1.0
  7527. h = _Math.euclideanModulo( h, 1 );
  7528. s = _Math.clamp( s, 0, 1 );
  7529. l = _Math.clamp( l, 0, 1 );
  7530. if ( s === 0 ) {
  7531. this.r = this.g = this.b = l;
  7532. } else {
  7533. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  7534. var q = ( 2 * l ) - p;
  7535. this.r = hue2rgb( q, p, h + 1 / 3 );
  7536. this.g = hue2rgb( q, p, h );
  7537. this.b = hue2rgb( q, p, h - 1 / 3 );
  7538. }
  7539. return this;
  7540. };
  7541. }(),
  7542. setStyle: function ( style ) {
  7543. function handleAlpha( string ) {
  7544. if ( string === undefined ) return;
  7545. if ( parseFloat( string ) < 1 ) {
  7546. console.warn( 'THREE.Color: Alpha component of ' + style + ' will be ignored.' );
  7547. }
  7548. }
  7549. var m;
  7550. if ( m = /^((?:rgb|hsl)a?)\(\s*([^\)]*)\)/.exec( style ) ) {
  7551. // rgb / hsl
  7552. var color;
  7553. var name = m[ 1 ];
  7554. var components = m[ 2 ];
  7555. switch ( name ) {
  7556. case 'rgb':
  7557. case 'rgba':
  7558. if ( color = /^(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7559. // rgb(255,0,0) rgba(255,0,0,0.5)
  7560. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  7561. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  7562. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  7563. handleAlpha( color[ 5 ] );
  7564. return this;
  7565. }
  7566. if ( color = /^(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7567. // rgb(100%,0%,0%) rgba(100%,0%,0%,0.5)
  7568. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  7569. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  7570. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  7571. handleAlpha( color[ 5 ] );
  7572. return this;
  7573. }
  7574. break;
  7575. case 'hsl':
  7576. case 'hsla':
  7577. if ( color = /^([0-9]*\.?[0-9]+)\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(,\s*([0-9]*\.?[0-9]+)\s*)?$/.exec( components ) ) {
  7578. // hsl(120,50%,50%) hsla(120,50%,50%,0.5)
  7579. var h = parseFloat( color[ 1 ] ) / 360;
  7580. var s = parseInt( color[ 2 ], 10 ) / 100;
  7581. var l = parseInt( color[ 3 ], 10 ) / 100;
  7582. handleAlpha( color[ 5 ] );
  7583. return this.setHSL( h, s, l );
  7584. }
  7585. break;
  7586. }
  7587. } else if ( m = /^\#([A-Fa-f0-9]+)$/.exec( style ) ) {
  7588. // hex color
  7589. var hex = m[ 1 ];
  7590. var size = hex.length;
  7591. if ( size === 3 ) {
  7592. // #ff0
  7593. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 0 ), 16 ) / 255;
  7594. this.g = parseInt( hex.charAt( 1 ) + hex.charAt( 1 ), 16 ) / 255;
  7595. this.b = parseInt( hex.charAt( 2 ) + hex.charAt( 2 ), 16 ) / 255;
  7596. return this;
  7597. } else if ( size === 6 ) {
  7598. // #ff0000
  7599. this.r = parseInt( hex.charAt( 0 ) + hex.charAt( 1 ), 16 ) / 255;
  7600. this.g = parseInt( hex.charAt( 2 ) + hex.charAt( 3 ), 16 ) / 255;
  7601. this.b = parseInt( hex.charAt( 4 ) + hex.charAt( 5 ), 16 ) / 255;
  7602. return this;
  7603. }
  7604. }
  7605. if ( style && style.length > 0 ) {
  7606. // color keywords
  7607. var hex = ColorKeywords[ style ];
  7608. if ( hex !== undefined ) {
  7609. // red
  7610. this.setHex( hex );
  7611. } else {
  7612. // unknown color
  7613. console.warn( 'THREE.Color: Unknown color ' + style );
  7614. }
  7615. }
  7616. return this;
  7617. },
  7618. clone: function () {
  7619. return new this.constructor( this.r, this.g, this.b );
  7620. },
  7621. copy: function ( color ) {
  7622. this.r = color.r;
  7623. this.g = color.g;
  7624. this.b = color.b;
  7625. return this;
  7626. },
  7627. copyGammaToLinear: function ( color, gammaFactor ) {
  7628. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7629. this.r = Math.pow( color.r, gammaFactor );
  7630. this.g = Math.pow( color.g, gammaFactor );
  7631. this.b = Math.pow( color.b, gammaFactor );
  7632. return this;
  7633. },
  7634. copyLinearToGamma: function ( color, gammaFactor ) {
  7635. if ( gammaFactor === undefined ) gammaFactor = 2.0;
  7636. var safeInverse = ( gammaFactor > 0 ) ? ( 1.0 / gammaFactor ) : 1.0;
  7637. this.r = Math.pow( color.r, safeInverse );
  7638. this.g = Math.pow( color.g, safeInverse );
  7639. this.b = Math.pow( color.b, safeInverse );
  7640. return this;
  7641. },
  7642. convertGammaToLinear: function () {
  7643. var r = this.r, g = this.g, b = this.b;
  7644. this.r = r * r;
  7645. this.g = g * g;
  7646. this.b = b * b;
  7647. return this;
  7648. },
  7649. convertLinearToGamma: function () {
  7650. this.r = Math.sqrt( this.r );
  7651. this.g = Math.sqrt( this.g );
  7652. this.b = Math.sqrt( this.b );
  7653. return this;
  7654. },
  7655. getHex: function () {
  7656. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  7657. },
  7658. getHexString: function () {
  7659. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  7660. },
  7661. getHSL: function ( optionalTarget ) {
  7662. // h,s,l ranges are in 0.0 - 1.0
  7663. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  7664. var r = this.r, g = this.g, b = this.b;
  7665. var max = Math.max( r, g, b );
  7666. var min = Math.min( r, g, b );
  7667. var hue, saturation;
  7668. var lightness = ( min + max ) / 2.0;
  7669. if ( min === max ) {
  7670. hue = 0;
  7671. saturation = 0;
  7672. } else {
  7673. var delta = max - min;
  7674. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  7675. switch ( max ) {
  7676. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  7677. case g: hue = ( b - r ) / delta + 2; break;
  7678. case b: hue = ( r - g ) / delta + 4; break;
  7679. }
  7680. hue /= 6;
  7681. }
  7682. hsl.h = hue;
  7683. hsl.s = saturation;
  7684. hsl.l = lightness;
  7685. return hsl;
  7686. },
  7687. getStyle: function () {
  7688. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  7689. },
  7690. offsetHSL: function ( h, s, l ) {
  7691. var hsl = this.getHSL();
  7692. hsl.h += h; hsl.s += s; hsl.l += l;
  7693. this.setHSL( hsl.h, hsl.s, hsl.l );
  7694. return this;
  7695. },
  7696. add: function ( color ) {
  7697. this.r += color.r;
  7698. this.g += color.g;
  7699. this.b += color.b;
  7700. return this;
  7701. },
  7702. addColors: function ( color1, color2 ) {
  7703. this.r = color1.r + color2.r;
  7704. this.g = color1.g + color2.g;
  7705. this.b = color1.b + color2.b;
  7706. return this;
  7707. },
  7708. addScalar: function ( s ) {
  7709. this.r += s;
  7710. this.g += s;
  7711. this.b += s;
  7712. return this;
  7713. },
  7714. sub: function( color ) {
  7715. this.r = Math.max( 0, this.r - color.r );
  7716. this.g = Math.max( 0, this.g - color.g );
  7717. this.b = Math.max( 0, this.b - color.b );
  7718. return this;
  7719. },
  7720. multiply: function ( color ) {
  7721. this.r *= color.r;
  7722. this.g *= color.g;
  7723. this.b *= color.b;
  7724. return this;
  7725. },
  7726. multiplyScalar: function ( s ) {
  7727. this.r *= s;
  7728. this.g *= s;
  7729. this.b *= s;
  7730. return this;
  7731. },
  7732. lerp: function ( color, alpha ) {
  7733. this.r += ( color.r - this.r ) * alpha;
  7734. this.g += ( color.g - this.g ) * alpha;
  7735. this.b += ( color.b - this.b ) * alpha;
  7736. return this;
  7737. },
  7738. equals: function ( c ) {
  7739. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  7740. },
  7741. fromArray: function ( array, offset ) {
  7742. if ( offset === undefined ) offset = 0;
  7743. this.r = array[ offset ];
  7744. this.g = array[ offset + 1 ];
  7745. this.b = array[ offset + 2 ];
  7746. return this;
  7747. },
  7748. toArray: function ( array, offset ) {
  7749. if ( array === undefined ) array = [];
  7750. if ( offset === undefined ) offset = 0;
  7751. array[ offset ] = this.r;
  7752. array[ offset + 1 ] = this.g;
  7753. array[ offset + 2 ] = this.b;
  7754. return array;
  7755. },
  7756. toJSON: function () {
  7757. return this.getHex();
  7758. }
  7759. };
  7760. var ColorKeywords = { 'aliceblue': 0xF0F8FF, 'antiquewhite': 0xFAEBD7, 'aqua': 0x00FFFF, 'aquamarine': 0x7FFFD4, 'azure': 0xF0FFFF,
  7761. 'beige': 0xF5F5DC, 'bisque': 0xFFE4C4, 'black': 0x000000, 'blanchedalmond': 0xFFEBCD, 'blue': 0x0000FF, 'blueviolet': 0x8A2BE2,
  7762. 'brown': 0xA52A2A, 'burlywood': 0xDEB887, 'cadetblue': 0x5F9EA0, 'chartreuse': 0x7FFF00, 'chocolate': 0xD2691E, 'coral': 0xFF7F50,
  7763. 'cornflowerblue': 0x6495ED, 'cornsilk': 0xFFF8DC, 'crimson': 0xDC143C, 'cyan': 0x00FFFF, 'darkblue': 0x00008B, 'darkcyan': 0x008B8B,
  7764. 'darkgoldenrod': 0xB8860B, 'darkgray': 0xA9A9A9, 'darkgreen': 0x006400, 'darkgrey': 0xA9A9A9, 'darkkhaki': 0xBDB76B, 'darkmagenta': 0x8B008B,
  7765. 'darkolivegreen': 0x556B2F, 'darkorange': 0xFF8C00, 'darkorchid': 0x9932CC, 'darkred': 0x8B0000, 'darksalmon': 0xE9967A, 'darkseagreen': 0x8FBC8F,
  7766. 'darkslateblue': 0x483D8B, 'darkslategray': 0x2F4F4F, 'darkslategrey': 0x2F4F4F, 'darkturquoise': 0x00CED1, 'darkviolet': 0x9400D3,
  7767. 'deeppink': 0xFF1493, 'deepskyblue': 0x00BFFF, 'dimgray': 0x696969, 'dimgrey': 0x696969, 'dodgerblue': 0x1E90FF, 'firebrick': 0xB22222,
  7768. 'floralwhite': 0xFFFAF0, 'forestgreen': 0x228B22, 'fuchsia': 0xFF00FF, 'gainsboro': 0xDCDCDC, 'ghostwhite': 0xF8F8FF, 'gold': 0xFFD700,
  7769. 'goldenrod': 0xDAA520, 'gray': 0x808080, 'green': 0x008000, 'greenyellow': 0xADFF2F, 'grey': 0x808080, 'honeydew': 0xF0FFF0, 'hotpink': 0xFF69B4,
  7770. 'indianred': 0xCD5C5C, 'indigo': 0x4B0082, 'ivory': 0xFFFFF0, 'khaki': 0xF0E68C, 'lavender': 0xE6E6FA, 'lavenderblush': 0xFFF0F5, 'lawngreen': 0x7CFC00,
  7771. 'lemonchiffon': 0xFFFACD, 'lightblue': 0xADD8E6, 'lightcoral': 0xF08080, 'lightcyan': 0xE0FFFF, 'lightgoldenrodyellow': 0xFAFAD2, 'lightgray': 0xD3D3D3,
  7772. 'lightgreen': 0x90EE90, 'lightgrey': 0xD3D3D3, 'lightpink': 0xFFB6C1, 'lightsalmon': 0xFFA07A, 'lightseagreen': 0x20B2AA, 'lightskyblue': 0x87CEFA,
  7773. 'lightslategray': 0x778899, 'lightslategrey': 0x778899, 'lightsteelblue': 0xB0C4DE, 'lightyellow': 0xFFFFE0, 'lime': 0x00FF00, 'limegreen': 0x32CD32,
  7774. 'linen': 0xFAF0E6, 'magenta': 0xFF00FF, 'maroon': 0x800000, 'mediumaquamarine': 0x66CDAA, 'mediumblue': 0x0000CD, 'mediumorchid': 0xBA55D3,
  7775. 'mediumpurple': 0x9370DB, 'mediumseagreen': 0x3CB371, 'mediumslateblue': 0x7B68EE, 'mediumspringgreen': 0x00FA9A, 'mediumturquoise': 0x48D1CC,
  7776. 'mediumvioletred': 0xC71585, 'midnightblue': 0x191970, 'mintcream': 0xF5FFFA, 'mistyrose': 0xFFE4E1, 'moccasin': 0xFFE4B5, 'navajowhite': 0xFFDEAD,
  7777. 'navy': 0x000080, 'oldlace': 0xFDF5E6, 'olive': 0x808000, 'olivedrab': 0x6B8E23, 'orange': 0xFFA500, 'orangered': 0xFF4500, 'orchid': 0xDA70D6,
  7778. 'palegoldenrod': 0xEEE8AA, 'palegreen': 0x98FB98, 'paleturquoise': 0xAFEEEE, 'palevioletred': 0xDB7093, 'papayawhip': 0xFFEFD5, 'peachpuff': 0xFFDAB9,
  7779. 'peru': 0xCD853F, 'pink': 0xFFC0CB, 'plum': 0xDDA0DD, 'powderblue': 0xB0E0E6, 'purple': 0x800080, 'red': 0xFF0000, 'rosybrown': 0xBC8F8F,
  7780. 'royalblue': 0x4169E1, 'saddlebrown': 0x8B4513, 'salmon': 0xFA8072, 'sandybrown': 0xF4A460, 'seagreen': 0x2E8B57, 'seashell': 0xFFF5EE,
  7781. 'sienna': 0xA0522D, 'silver': 0xC0C0C0, 'skyblue': 0x87CEEB, 'slateblue': 0x6A5ACD, 'slategray': 0x708090, 'slategrey': 0x708090, 'snow': 0xFFFAFA,
  7782. 'springgreen': 0x00FF7F, 'steelblue': 0x4682B4, 'tan': 0xD2B48C, 'teal': 0x008080, 'thistle': 0xD8BFD8, 'tomato': 0xFF6347, 'turquoise': 0x40E0D0,
  7783. 'violet': 0xEE82EE, 'wheat': 0xF5DEB3, 'white': 0xFFFFFF, 'whitesmoke': 0xF5F5F5, 'yellow': 0xFFFF00, 'yellowgreen': 0x9ACD32 };
  7784. /**
  7785. * @author alteredq / http://alteredqualia.com/
  7786. */
  7787. function DataTexture( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  7788. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  7789. this.image = { data: data, width: width, height: height };
  7790. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  7791. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  7792. this.generateMipmaps = false;
  7793. this.flipY = false;
  7794. this.unpackAlignment = 1;
  7795. }
  7796. DataTexture.prototype = Object.create( Texture.prototype );
  7797. DataTexture.prototype.constructor = DataTexture;
  7798. DataTexture.prototype.isDataTexture = true;
  7799. /**
  7800. * Uniforms library for shared webgl shaders
  7801. */
  7802. var UniformsLib = {
  7803. common: {
  7804. diffuse: { value: new Color( 0xeeeeee ) },
  7805. opacity: { value: 1.0 },
  7806. map: { value: null },
  7807. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) },
  7808. specularMap: { value: null },
  7809. alphaMap: { value: null },
  7810. envMap: { value: null },
  7811. flipEnvMap: { value: - 1 },
  7812. reflectivity: { value: 1.0 },
  7813. refractionRatio: { value: 0.98 }
  7814. },
  7815. aomap: {
  7816. aoMap: { value: null },
  7817. aoMapIntensity: { value: 1 }
  7818. },
  7819. lightmap: {
  7820. lightMap: { value: null },
  7821. lightMapIntensity: { value: 1 }
  7822. },
  7823. emissivemap: {
  7824. emissiveMap: { value: null }
  7825. },
  7826. bumpmap: {
  7827. bumpMap: { value: null },
  7828. bumpScale: { value: 1 }
  7829. },
  7830. normalmap: {
  7831. normalMap: { value: null },
  7832. normalScale: { value: new Vector2( 1, 1 ) }
  7833. },
  7834. displacementmap: {
  7835. displacementMap: { value: null },
  7836. displacementScale: { value: 1 },
  7837. displacementBias: { value: 0 }
  7838. },
  7839. roughnessmap: {
  7840. roughnessMap: { value: null }
  7841. },
  7842. metalnessmap: {
  7843. metalnessMap: { value: null }
  7844. },
  7845. gradientmap: {
  7846. gradientMap: { value: null }
  7847. },
  7848. fog: {
  7849. fogDensity: { value: 0.00025 },
  7850. fogNear: { value: 1 },
  7851. fogFar: { value: 2000 },
  7852. fogColor: { value: new Color( 0xffffff ) }
  7853. },
  7854. lights: {
  7855. ambientLightColor: { value: [] },
  7856. directionalLights: { value: [], properties: {
  7857. direction: {},
  7858. color: {},
  7859. shadow: {},
  7860. shadowBias: {},
  7861. shadowRadius: {},
  7862. shadowMapSize: {}
  7863. } },
  7864. directionalShadowMap: { value: [] },
  7865. directionalShadowMatrix: { value: [] },
  7866. spotLights: { value: [], properties: {
  7867. color: {},
  7868. position: {},
  7869. direction: {},
  7870. distance: {},
  7871. coneCos: {},
  7872. penumbraCos: {},
  7873. decay: {},
  7874. shadow: {},
  7875. shadowBias: {},
  7876. shadowRadius: {},
  7877. shadowMapSize: {}
  7878. } },
  7879. spotShadowMap: { value: [] },
  7880. spotShadowMatrix: { value: [] },
  7881. pointLights: { value: [], properties: {
  7882. color: {},
  7883. position: {},
  7884. decay: {},
  7885. distance: {},
  7886. shadow: {},
  7887. shadowBias: {},
  7888. shadowRadius: {},
  7889. shadowMapSize: {}
  7890. } },
  7891. pointShadowMap: { value: [] },
  7892. pointShadowMatrix: { value: [] },
  7893. hemisphereLights: { value: [], properties: {
  7894. direction: {},
  7895. skyColor: {},
  7896. groundColor: {}
  7897. } },
  7898. // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src
  7899. rectAreaLights: { value: [], properties: {
  7900. color: {},
  7901. position: {},
  7902. width: {},
  7903. height: {},
  7904. } }
  7905. },
  7906. points: {
  7907. diffuse: { value: new Color( 0xeeeeee ) },
  7908. opacity: { value: 1.0 },
  7909. size: { value: 1.0 },
  7910. scale: { value: 1.0 },
  7911. map: { value: null },
  7912. offsetRepeat: { value: new Vector4( 0, 0, 1, 1 ) }
  7913. }
  7914. };
  7915. /**
  7916. * @author alteredq / http://alteredqualia.com/
  7917. * @author mrdoob / http://mrdoob.com/
  7918. * @author mikael emtinger / http://gomo.se/
  7919. */
  7920. var ShaderLib = {
  7921. basic: {
  7922. uniforms: UniformsUtils.merge( [
  7923. UniformsLib.common,
  7924. UniformsLib.aomap,
  7925. UniformsLib.lightmap,
  7926. UniformsLib.fog
  7927. ] ),
  7928. vertexShader: ShaderChunk.meshbasic_vert,
  7929. fragmentShader: ShaderChunk.meshbasic_frag
  7930. },
  7931. lambert: {
  7932. uniforms: UniformsUtils.merge( [
  7933. UniformsLib.common,
  7934. UniformsLib.aomap,
  7935. UniformsLib.lightmap,
  7936. UniformsLib.emissivemap,
  7937. UniformsLib.fog,
  7938. UniformsLib.lights,
  7939. {
  7940. emissive: { value: new Color( 0x000000 ) }
  7941. }
  7942. ] ),
  7943. vertexShader: ShaderChunk.meshlambert_vert,
  7944. fragmentShader: ShaderChunk.meshlambert_frag
  7945. },
  7946. phong: {
  7947. uniforms: UniformsUtils.merge( [
  7948. UniformsLib.common,
  7949. UniformsLib.aomap,
  7950. UniformsLib.lightmap,
  7951. UniformsLib.emissivemap,
  7952. UniformsLib.bumpmap,
  7953. UniformsLib.normalmap,
  7954. UniformsLib.displacementmap,
  7955. UniformsLib.gradientmap,
  7956. UniformsLib.fog,
  7957. UniformsLib.lights,
  7958. {
  7959. emissive: { value: new Color( 0x000000 ) },
  7960. specular: { value: new Color( 0x111111 ) },
  7961. shininess: { value: 30 }
  7962. }
  7963. ] ),
  7964. vertexShader: ShaderChunk.meshphong_vert,
  7965. fragmentShader: ShaderChunk.meshphong_frag
  7966. },
  7967. standard: {
  7968. uniforms: UniformsUtils.merge( [
  7969. UniformsLib.common,
  7970. UniformsLib.aomap,
  7971. UniformsLib.lightmap,
  7972. UniformsLib.emissivemap,
  7973. UniformsLib.bumpmap,
  7974. UniformsLib.normalmap,
  7975. UniformsLib.displacementmap,
  7976. UniformsLib.roughnessmap,
  7977. UniformsLib.metalnessmap,
  7978. UniformsLib.fog,
  7979. UniformsLib.lights,
  7980. {
  7981. emissive: { value: new Color( 0x000000 ) },
  7982. roughness: { value: 0.5 },
  7983. metalness: { value: 0 },
  7984. envMapIntensity: { value: 1 } // temporary
  7985. }
  7986. ] ),
  7987. vertexShader: ShaderChunk.meshphysical_vert,
  7988. fragmentShader: ShaderChunk.meshphysical_frag
  7989. },
  7990. points: {
  7991. uniforms: UniformsUtils.merge( [
  7992. UniformsLib.points,
  7993. UniformsLib.fog
  7994. ] ),
  7995. vertexShader: ShaderChunk.points_vert,
  7996. fragmentShader: ShaderChunk.points_frag
  7997. },
  7998. dashed: {
  7999. uniforms: UniformsUtils.merge( [
  8000. UniformsLib.common,
  8001. UniformsLib.fog,
  8002. {
  8003. scale: { value: 1 },
  8004. dashSize: { value: 1 },
  8005. totalSize: { value: 2 }
  8006. }
  8007. ] ),
  8008. vertexShader: ShaderChunk.linedashed_vert,
  8009. fragmentShader: ShaderChunk.linedashed_frag
  8010. },
  8011. depth: {
  8012. uniforms: UniformsUtils.merge( [
  8013. UniformsLib.common,
  8014. UniformsLib.displacementmap
  8015. ] ),
  8016. vertexShader: ShaderChunk.depth_vert,
  8017. fragmentShader: ShaderChunk.depth_frag
  8018. },
  8019. normal: {
  8020. uniforms: UniformsUtils.merge( [
  8021. UniformsLib.common,
  8022. UniformsLib.bumpmap,
  8023. UniformsLib.normalmap,
  8024. UniformsLib.displacementmap,
  8025. {
  8026. opacity: { value: 1.0 }
  8027. }
  8028. ] ),
  8029. vertexShader: ShaderChunk.normal_vert,
  8030. fragmentShader: ShaderChunk.normal_frag
  8031. },
  8032. /* -------------------------------------------------------------------------
  8033. // Cube map shader
  8034. ------------------------------------------------------------------------- */
  8035. cube: {
  8036. uniforms: {
  8037. tCube: { value: null },
  8038. tFlip: { value: - 1 },
  8039. opacity: { value: 1.0 }
  8040. },
  8041. vertexShader: ShaderChunk.cube_vert,
  8042. fragmentShader: ShaderChunk.cube_frag
  8043. },
  8044. /* -------------------------------------------------------------------------
  8045. // Cube map shader
  8046. ------------------------------------------------------------------------- */
  8047. equirect: {
  8048. uniforms: {
  8049. tEquirect: { value: null },
  8050. tFlip: { value: - 1 }
  8051. },
  8052. vertexShader: ShaderChunk.equirect_vert,
  8053. fragmentShader: ShaderChunk.equirect_frag
  8054. },
  8055. distanceRGBA: {
  8056. uniforms: {
  8057. lightPos: { value: new Vector3() }
  8058. },
  8059. vertexShader: ShaderChunk.distanceRGBA_vert,
  8060. fragmentShader: ShaderChunk.distanceRGBA_frag
  8061. }
  8062. };
  8063. ShaderLib.physical = {
  8064. uniforms: UniformsUtils.merge( [
  8065. ShaderLib.standard.uniforms,
  8066. {
  8067. clearCoat: { value: 0 },
  8068. clearCoatRoughness: { value: 0 }
  8069. }
  8070. ] ),
  8071. vertexShader: ShaderChunk.meshphysical_vert,
  8072. fragmentShader: ShaderChunk.meshphysical_frag
  8073. };
  8074. /**
  8075. * @author bhouston / http://clara.io
  8076. */
  8077. function Box2( min, max ) {
  8078. this.min = ( min !== undefined ) ? min : new Vector2( + Infinity, + Infinity );
  8079. this.max = ( max !== undefined ) ? max : new Vector2( - Infinity, - Infinity );
  8080. }
  8081. Box2.prototype = {
  8082. constructor: Box2,
  8083. set: function ( min, max ) {
  8084. this.min.copy( min );
  8085. this.max.copy( max );
  8086. return this;
  8087. },
  8088. setFromPoints: function ( points ) {
  8089. this.makeEmpty();
  8090. for ( var i = 0, il = points.length; i < il; i ++ ) {
  8091. this.expandByPoint( points[ i ] );
  8092. }
  8093. return this;
  8094. },
  8095. setFromCenterAndSize: function () {
  8096. var v1 = new Vector2();
  8097. return function setFromCenterAndSize( center, size ) {
  8098. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  8099. this.min.copy( center ).sub( halfSize );
  8100. this.max.copy( center ).add( halfSize );
  8101. return this;
  8102. };
  8103. }(),
  8104. clone: function () {
  8105. return new this.constructor().copy( this );
  8106. },
  8107. copy: function ( box ) {
  8108. this.min.copy( box.min );
  8109. this.max.copy( box.max );
  8110. return this;
  8111. },
  8112. makeEmpty: function () {
  8113. this.min.x = this.min.y = + Infinity;
  8114. this.max.x = this.max.y = - Infinity;
  8115. return this;
  8116. },
  8117. isEmpty: function () {
  8118. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  8119. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  8120. },
  8121. getCenter: function ( optionalTarget ) {
  8122. var result = optionalTarget || new Vector2();
  8123. return this.isEmpty() ? result.set( 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  8124. },
  8125. getSize: function ( optionalTarget ) {
  8126. var result = optionalTarget || new Vector2();
  8127. return this.isEmpty() ? result.set( 0, 0 ) : result.subVectors( this.max, this.min );
  8128. },
  8129. expandByPoint: function ( point ) {
  8130. this.min.min( point );
  8131. this.max.max( point );
  8132. return this;
  8133. },
  8134. expandByVector: function ( vector ) {
  8135. this.min.sub( vector );
  8136. this.max.add( vector );
  8137. return this;
  8138. },
  8139. expandByScalar: function ( scalar ) {
  8140. this.min.addScalar( - scalar );
  8141. this.max.addScalar( scalar );
  8142. return this;
  8143. },
  8144. containsPoint: function ( point ) {
  8145. return point.x < this.min.x || point.x > this.max.x ||
  8146. point.y < this.min.y || point.y > this.max.y ? false : true;
  8147. },
  8148. containsBox: function ( box ) {
  8149. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  8150. this.min.y <= box.min.y && box.max.y <= this.max.y;
  8151. },
  8152. getParameter: function ( point, optionalTarget ) {
  8153. // This can potentially have a divide by zero if the box
  8154. // has a size dimension of 0.
  8155. var result = optionalTarget || new Vector2();
  8156. return result.set(
  8157. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  8158. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  8159. );
  8160. },
  8161. intersectsBox: function ( box ) {
  8162. // using 6 splitting planes to rule out intersections.
  8163. return box.max.x < this.min.x || box.min.x > this.max.x ||
  8164. box.max.y < this.min.y || box.min.y > this.max.y ? false : true;
  8165. },
  8166. clampPoint: function ( point, optionalTarget ) {
  8167. var result = optionalTarget || new Vector2();
  8168. return result.copy( point ).clamp( this.min, this.max );
  8169. },
  8170. distanceToPoint: function () {
  8171. var v1 = new Vector2();
  8172. return function distanceToPoint( point ) {
  8173. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  8174. return clampedPoint.sub( point ).length();
  8175. };
  8176. }(),
  8177. intersect: function ( box ) {
  8178. this.min.max( box.min );
  8179. this.max.min( box.max );
  8180. return this;
  8181. },
  8182. union: function ( box ) {
  8183. this.min.min( box.min );
  8184. this.max.max( box.max );
  8185. return this;
  8186. },
  8187. translate: function ( offset ) {
  8188. this.min.add( offset );
  8189. this.max.add( offset );
  8190. return this;
  8191. },
  8192. equals: function ( box ) {
  8193. return box.min.equals( this.min ) && box.max.equals( this.max );
  8194. }
  8195. };
  8196. /**
  8197. * @author mikael emtinger / http://gomo.se/
  8198. * @author alteredq / http://alteredqualia.com/
  8199. */
  8200. function LensFlarePlugin( renderer, flares ) {
  8201. var gl = renderer.context;
  8202. var state = renderer.state;
  8203. var vertexBuffer, elementBuffer;
  8204. var shader, program, attributes, uniforms;
  8205. var tempTexture, occlusionTexture;
  8206. function init() {
  8207. var vertices = new Float32Array( [
  8208. - 1, - 1, 0, 0,
  8209. 1, - 1, 1, 0,
  8210. 1, 1, 1, 1,
  8211. - 1, 1, 0, 1
  8212. ] );
  8213. var faces = new Uint16Array( [
  8214. 0, 1, 2,
  8215. 0, 2, 3
  8216. ] );
  8217. // buffers
  8218. vertexBuffer = gl.createBuffer();
  8219. elementBuffer = gl.createBuffer();
  8220. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8221. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8222. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8223. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8224. // textures
  8225. tempTexture = gl.createTexture();
  8226. occlusionTexture = gl.createTexture();
  8227. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8228. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGB, 16, 16, 0, gl.RGB, gl.UNSIGNED_BYTE, null );
  8229. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8230. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8231. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8232. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8233. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8234. gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, 16, 16, 0, gl.RGBA, gl.UNSIGNED_BYTE, null );
  8235. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
  8236. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
  8237. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  8238. gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  8239. shader = {
  8240. vertexShader: [
  8241. "uniform lowp int renderType;",
  8242. "uniform vec3 screenPosition;",
  8243. "uniform vec2 scale;",
  8244. "uniform float rotation;",
  8245. "uniform sampler2D occlusionMap;",
  8246. "attribute vec2 position;",
  8247. "attribute vec2 uv;",
  8248. "varying vec2 vUV;",
  8249. "varying float vVisibility;",
  8250. "void main() {",
  8251. "vUV = uv;",
  8252. "vec2 pos = position;",
  8253. "if ( renderType == 2 ) {",
  8254. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  8255. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  8256. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  8257. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  8258. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  8259. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  8260. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  8261. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  8262. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  8263. "vVisibility = visibility.r / 9.0;",
  8264. "vVisibility *= 1.0 - visibility.g / 9.0;",
  8265. "vVisibility *= visibility.b / 9.0;",
  8266. "vVisibility *= 1.0 - visibility.a / 9.0;",
  8267. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  8268. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  8269. "}",
  8270. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  8271. "}"
  8272. ].join( "\n" ),
  8273. fragmentShader: [
  8274. "uniform lowp int renderType;",
  8275. "uniform sampler2D map;",
  8276. "uniform float opacity;",
  8277. "uniform vec3 color;",
  8278. "varying vec2 vUV;",
  8279. "varying float vVisibility;",
  8280. "void main() {",
  8281. // pink square
  8282. "if ( renderType == 0 ) {",
  8283. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  8284. // restore
  8285. "} else if ( renderType == 1 ) {",
  8286. "gl_FragColor = texture2D( map, vUV );",
  8287. // flare
  8288. "} else {",
  8289. "vec4 texture = texture2D( map, vUV );",
  8290. "texture.a *= opacity * vVisibility;",
  8291. "gl_FragColor = texture;",
  8292. "gl_FragColor.rgb *= color;",
  8293. "}",
  8294. "}"
  8295. ].join( "\n" )
  8296. };
  8297. program = createProgram( shader );
  8298. attributes = {
  8299. vertex: gl.getAttribLocation ( program, "position" ),
  8300. uv: gl.getAttribLocation ( program, "uv" )
  8301. };
  8302. uniforms = {
  8303. renderType: gl.getUniformLocation( program, "renderType" ),
  8304. map: gl.getUniformLocation( program, "map" ),
  8305. occlusionMap: gl.getUniformLocation( program, "occlusionMap" ),
  8306. opacity: gl.getUniformLocation( program, "opacity" ),
  8307. color: gl.getUniformLocation( program, "color" ),
  8308. scale: gl.getUniformLocation( program, "scale" ),
  8309. rotation: gl.getUniformLocation( program, "rotation" ),
  8310. screenPosition: gl.getUniformLocation( program, "screenPosition" )
  8311. };
  8312. }
  8313. /*
  8314. * Render lens flares
  8315. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  8316. * reads these back and calculates occlusion.
  8317. */
  8318. this.render = function ( scene, camera, viewport ) {
  8319. if ( flares.length === 0 ) return;
  8320. var tempPosition = new Vector3();
  8321. var invAspect = viewport.w / viewport.z,
  8322. halfViewportWidth = viewport.z * 0.5,
  8323. halfViewportHeight = viewport.w * 0.5;
  8324. var size = 16 / viewport.w,
  8325. scale = new Vector2( size * invAspect, size );
  8326. var screenPosition = new Vector3( 1, 1, 0 ),
  8327. screenPositionPixels = new Vector2( 1, 1 );
  8328. var validArea = new Box2();
  8329. validArea.min.set( viewport.x, viewport.y );
  8330. validArea.max.set( viewport.x + ( viewport.z - 16 ), viewport.y + ( viewport.w - 16 ) );
  8331. if ( program === undefined ) {
  8332. init();
  8333. }
  8334. gl.useProgram( program );
  8335. state.initAttributes();
  8336. state.enableAttribute( attributes.vertex );
  8337. state.enableAttribute( attributes.uv );
  8338. state.disableUnusedAttributes();
  8339. // loop through all lens flares to update their occlusion and positions
  8340. // setup gl and common used attribs/uniforms
  8341. gl.uniform1i( uniforms.occlusionMap, 0 );
  8342. gl.uniform1i( uniforms.map, 1 );
  8343. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8344. gl.vertexAttribPointer( attributes.vertex, 2, gl.FLOAT, false, 2 * 8, 0 );
  8345. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8346. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8347. state.disable( gl.CULL_FACE );
  8348. state.setDepthWrite( false );
  8349. for ( var i = 0, l = flares.length; i < l; i ++ ) {
  8350. size = 16 / viewport.w;
  8351. scale.set( size * invAspect, size );
  8352. // calc object screen position
  8353. var flare = flares[ i ];
  8354. tempPosition.set( flare.matrixWorld.elements[ 12 ], flare.matrixWorld.elements[ 13 ], flare.matrixWorld.elements[ 14 ] );
  8355. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  8356. tempPosition.applyProjection( camera.projectionMatrix );
  8357. // setup arrays for gl programs
  8358. screenPosition.copy( tempPosition );
  8359. // horizontal and vertical coordinate of the lower left corner of the pixels to copy
  8360. screenPositionPixels.x = viewport.x + ( screenPosition.x * halfViewportWidth ) + halfViewportWidth - 8;
  8361. screenPositionPixels.y = viewport.y + ( screenPosition.y * halfViewportHeight ) + halfViewportHeight - 8;
  8362. // screen cull
  8363. if ( validArea.containsPoint( screenPositionPixels ) === true ) {
  8364. // save current RGB to temp texture
  8365. state.activeTexture( gl.TEXTURE0 );
  8366. state.bindTexture( gl.TEXTURE_2D, null );
  8367. state.activeTexture( gl.TEXTURE1 );
  8368. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8369. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGB, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8370. // render pink quad
  8371. gl.uniform1i( uniforms.renderType, 0 );
  8372. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8373. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8374. state.disable( gl.BLEND );
  8375. state.enable( gl.DEPTH_TEST );
  8376. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8377. // copy result to occlusionMap
  8378. state.activeTexture( gl.TEXTURE0 );
  8379. state.bindTexture( gl.TEXTURE_2D, occlusionTexture );
  8380. gl.copyTexImage2D( gl.TEXTURE_2D, 0, gl.RGBA, screenPositionPixels.x, screenPositionPixels.y, 16, 16, 0 );
  8381. // restore graphics
  8382. gl.uniform1i( uniforms.renderType, 1 );
  8383. state.disable( gl.DEPTH_TEST );
  8384. state.activeTexture( gl.TEXTURE1 );
  8385. state.bindTexture( gl.TEXTURE_2D, tempTexture );
  8386. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8387. // update object positions
  8388. flare.positionScreen.copy( screenPosition );
  8389. if ( flare.customUpdateCallback ) {
  8390. flare.customUpdateCallback( flare );
  8391. } else {
  8392. flare.updateLensFlares();
  8393. }
  8394. // render flares
  8395. gl.uniform1i( uniforms.renderType, 2 );
  8396. state.enable( gl.BLEND );
  8397. for ( var j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  8398. var sprite = flare.lensFlares[ j ];
  8399. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  8400. screenPosition.x = sprite.x;
  8401. screenPosition.y = sprite.y;
  8402. screenPosition.z = sprite.z;
  8403. size = sprite.size * sprite.scale / viewport.w;
  8404. scale.x = size * invAspect;
  8405. scale.y = size;
  8406. gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  8407. gl.uniform2f( uniforms.scale, scale.x, scale.y );
  8408. gl.uniform1f( uniforms.rotation, sprite.rotation );
  8409. gl.uniform1f( uniforms.opacity, sprite.opacity );
  8410. gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  8411. state.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  8412. renderer.setTexture2D( sprite.texture, 1 );
  8413. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8414. }
  8415. }
  8416. }
  8417. }
  8418. // restore gl
  8419. state.enable( gl.CULL_FACE );
  8420. state.enable( gl.DEPTH_TEST );
  8421. state.setDepthWrite( true );
  8422. renderer.resetGLState();
  8423. };
  8424. function createProgram( shader ) {
  8425. var program = gl.createProgram();
  8426. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8427. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8428. var prefix = "precision " + renderer.getPrecision() + " float;\n";
  8429. gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  8430. gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  8431. gl.compileShader( fragmentShader );
  8432. gl.compileShader( vertexShader );
  8433. gl.attachShader( program, fragmentShader );
  8434. gl.attachShader( program, vertexShader );
  8435. gl.linkProgram( program );
  8436. return program;
  8437. }
  8438. }
  8439. /**
  8440. * @author mikael emtinger / http://gomo.se/
  8441. * @author alteredq / http://alteredqualia.com/
  8442. */
  8443. function SpritePlugin( renderer, sprites ) {
  8444. var gl = renderer.context;
  8445. var state = renderer.state;
  8446. var vertexBuffer, elementBuffer;
  8447. var program, attributes, uniforms;
  8448. var texture;
  8449. // decompose matrixWorld
  8450. var spritePosition = new Vector3();
  8451. var spriteRotation = new Quaternion();
  8452. var spriteScale = new Vector3();
  8453. function init() {
  8454. var vertices = new Float32Array( [
  8455. - 0.5, - 0.5, 0, 0,
  8456. 0.5, - 0.5, 1, 0,
  8457. 0.5, 0.5, 1, 1,
  8458. - 0.5, 0.5, 0, 1
  8459. ] );
  8460. var faces = new Uint16Array( [
  8461. 0, 1, 2,
  8462. 0, 2, 3
  8463. ] );
  8464. vertexBuffer = gl.createBuffer();
  8465. elementBuffer = gl.createBuffer();
  8466. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8467. gl.bufferData( gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW );
  8468. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8469. gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, faces, gl.STATIC_DRAW );
  8470. program = createProgram();
  8471. attributes = {
  8472. position: gl.getAttribLocation ( program, 'position' ),
  8473. uv: gl.getAttribLocation ( program, 'uv' )
  8474. };
  8475. uniforms = {
  8476. uvOffset: gl.getUniformLocation( program, 'uvOffset' ),
  8477. uvScale: gl.getUniformLocation( program, 'uvScale' ),
  8478. rotation: gl.getUniformLocation( program, 'rotation' ),
  8479. scale: gl.getUniformLocation( program, 'scale' ),
  8480. color: gl.getUniformLocation( program, 'color' ),
  8481. map: gl.getUniformLocation( program, 'map' ),
  8482. opacity: gl.getUniformLocation( program, 'opacity' ),
  8483. modelViewMatrix: gl.getUniformLocation( program, 'modelViewMatrix' ),
  8484. projectionMatrix: gl.getUniformLocation( program, 'projectionMatrix' ),
  8485. fogType: gl.getUniformLocation( program, 'fogType' ),
  8486. fogDensity: gl.getUniformLocation( program, 'fogDensity' ),
  8487. fogNear: gl.getUniformLocation( program, 'fogNear' ),
  8488. fogFar: gl.getUniformLocation( program, 'fogFar' ),
  8489. fogColor: gl.getUniformLocation( program, 'fogColor' ),
  8490. alphaTest: gl.getUniformLocation( program, 'alphaTest' )
  8491. };
  8492. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  8493. canvas.width = 8;
  8494. canvas.height = 8;
  8495. var context = canvas.getContext( '2d' );
  8496. context.fillStyle = 'white';
  8497. context.fillRect( 0, 0, 8, 8 );
  8498. texture = new Texture( canvas );
  8499. texture.needsUpdate = true;
  8500. }
  8501. this.render = function ( scene, camera ) {
  8502. if ( sprites.length === 0 ) return;
  8503. // setup gl
  8504. if ( program === undefined ) {
  8505. init();
  8506. }
  8507. gl.useProgram( program );
  8508. state.initAttributes();
  8509. state.enableAttribute( attributes.position );
  8510. state.enableAttribute( attributes.uv );
  8511. state.disableUnusedAttributes();
  8512. state.disable( gl.CULL_FACE );
  8513. state.enable( gl.BLEND );
  8514. gl.bindBuffer( gl.ARRAY_BUFFER, vertexBuffer );
  8515. gl.vertexAttribPointer( attributes.position, 2, gl.FLOAT, false, 2 * 8, 0 );
  8516. gl.vertexAttribPointer( attributes.uv, 2, gl.FLOAT, false, 2 * 8, 8 );
  8517. gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  8518. gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  8519. state.activeTexture( gl.TEXTURE0 );
  8520. gl.uniform1i( uniforms.map, 0 );
  8521. var oldFogType = 0;
  8522. var sceneFogType = 0;
  8523. var fog = scene.fog;
  8524. if ( fog ) {
  8525. gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  8526. if ( fog.isFog ) {
  8527. gl.uniform1f( uniforms.fogNear, fog.near );
  8528. gl.uniform1f( uniforms.fogFar, fog.far );
  8529. gl.uniform1i( uniforms.fogType, 1 );
  8530. oldFogType = 1;
  8531. sceneFogType = 1;
  8532. } else if ( fog.isFogExp2 ) {
  8533. gl.uniform1f( uniforms.fogDensity, fog.density );
  8534. gl.uniform1i( uniforms.fogType, 2 );
  8535. oldFogType = 2;
  8536. sceneFogType = 2;
  8537. }
  8538. } else {
  8539. gl.uniform1i( uniforms.fogType, 0 );
  8540. oldFogType = 0;
  8541. sceneFogType = 0;
  8542. }
  8543. // update positions and sort
  8544. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8545. var sprite = sprites[ i ];
  8546. sprite.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  8547. sprite.z = - sprite.modelViewMatrix.elements[ 14 ];
  8548. }
  8549. sprites.sort( painterSortStable );
  8550. // render all sprites
  8551. var scale = [];
  8552. for ( var i = 0, l = sprites.length; i < l; i ++ ) {
  8553. var sprite = sprites[ i ];
  8554. var material = sprite.material;
  8555. if ( material.visible === false ) continue;
  8556. gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  8557. gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite.modelViewMatrix.elements );
  8558. sprite.matrixWorld.decompose( spritePosition, spriteRotation, spriteScale );
  8559. scale[ 0 ] = spriteScale.x;
  8560. scale[ 1 ] = spriteScale.y;
  8561. var fogType = 0;
  8562. if ( scene.fog && material.fog ) {
  8563. fogType = sceneFogType;
  8564. }
  8565. if ( oldFogType !== fogType ) {
  8566. gl.uniform1i( uniforms.fogType, fogType );
  8567. oldFogType = fogType;
  8568. }
  8569. if ( material.map !== null ) {
  8570. gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  8571. gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  8572. } else {
  8573. gl.uniform2f( uniforms.uvOffset, 0, 0 );
  8574. gl.uniform2f( uniforms.uvScale, 1, 1 );
  8575. }
  8576. gl.uniform1f( uniforms.opacity, material.opacity );
  8577. gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  8578. gl.uniform1f( uniforms.rotation, material.rotation );
  8579. gl.uniform2fv( uniforms.scale, scale );
  8580. state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8581. state.setDepthTest( material.depthTest );
  8582. state.setDepthWrite( material.depthWrite );
  8583. if ( material.map ) {
  8584. renderer.setTexture2D( material.map, 0 );
  8585. } else {
  8586. renderer.setTexture2D( texture, 0 );
  8587. }
  8588. gl.drawElements( gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  8589. }
  8590. // restore gl
  8591. state.enable( gl.CULL_FACE );
  8592. renderer.resetGLState();
  8593. };
  8594. function createProgram() {
  8595. var program = gl.createProgram();
  8596. var vertexShader = gl.createShader( gl.VERTEX_SHADER );
  8597. var fragmentShader = gl.createShader( gl.FRAGMENT_SHADER );
  8598. gl.shaderSource( vertexShader, [
  8599. 'precision ' + renderer.getPrecision() + ' float;',
  8600. 'uniform mat4 modelViewMatrix;',
  8601. 'uniform mat4 projectionMatrix;',
  8602. 'uniform float rotation;',
  8603. 'uniform vec2 scale;',
  8604. 'uniform vec2 uvOffset;',
  8605. 'uniform vec2 uvScale;',
  8606. 'attribute vec2 position;',
  8607. 'attribute vec2 uv;',
  8608. 'varying vec2 vUV;',
  8609. 'void main() {',
  8610. 'vUV = uvOffset + uv * uvScale;',
  8611. 'vec2 alignedPosition = position * scale;',
  8612. 'vec2 rotatedPosition;',
  8613. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  8614. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  8615. 'vec4 finalPosition;',
  8616. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  8617. 'finalPosition.xy += rotatedPosition;',
  8618. 'finalPosition = projectionMatrix * finalPosition;',
  8619. 'gl_Position = finalPosition;',
  8620. '}'
  8621. ].join( '\n' ) );
  8622. gl.shaderSource( fragmentShader, [
  8623. 'precision ' + renderer.getPrecision() + ' float;',
  8624. 'uniform vec3 color;',
  8625. 'uniform sampler2D map;',
  8626. 'uniform float opacity;',
  8627. 'uniform int fogType;',
  8628. 'uniform vec3 fogColor;',
  8629. 'uniform float fogDensity;',
  8630. 'uniform float fogNear;',
  8631. 'uniform float fogFar;',
  8632. 'uniform float alphaTest;',
  8633. 'varying vec2 vUV;',
  8634. 'void main() {',
  8635. 'vec4 texture = texture2D( map, vUV );',
  8636. 'if ( texture.a < alphaTest ) discard;',
  8637. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  8638. 'if ( fogType > 0 ) {',
  8639. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  8640. 'float fogFactor = 0.0;',
  8641. 'if ( fogType == 1 ) {',
  8642. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  8643. '} else {',
  8644. 'const float LOG2 = 1.442695;',
  8645. 'fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  8646. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  8647. '}',
  8648. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  8649. '}',
  8650. '}'
  8651. ].join( '\n' ) );
  8652. gl.compileShader( vertexShader );
  8653. gl.compileShader( fragmentShader );
  8654. gl.attachShader( program, vertexShader );
  8655. gl.attachShader( program, fragmentShader );
  8656. gl.linkProgram( program );
  8657. return program;
  8658. }
  8659. function painterSortStable( a, b ) {
  8660. if ( a.renderOrder !== b.renderOrder ) {
  8661. return a.renderOrder - b.renderOrder;
  8662. } else if ( a.z !== b.z ) {
  8663. return b.z - a.z;
  8664. } else {
  8665. return b.id - a.id;
  8666. }
  8667. }
  8668. }
  8669. /**
  8670. * @author mrdoob / http://mrdoob.com/
  8671. * @author alteredq / http://alteredqualia.com/
  8672. */
  8673. var materialId = 0;
  8674. function Material() {
  8675. Object.defineProperty( this, 'id', { value: materialId ++ } );
  8676. this.uuid = _Math.generateUUID();
  8677. this.name = '';
  8678. this.type = 'Material';
  8679. this.fog = true;
  8680. this.lights = true;
  8681. this.blending = NormalBlending;
  8682. this.side = FrontSide;
  8683. this.shading = SmoothShading; // THREE.FlatShading, THREE.SmoothShading
  8684. this.vertexColors = NoColors; // THREE.NoColors, THREE.VertexColors, THREE.FaceColors
  8685. this.opacity = 1;
  8686. this.transparent = false;
  8687. this.blendSrc = SrcAlphaFactor;
  8688. this.blendDst = OneMinusSrcAlphaFactor;
  8689. this.blendEquation = AddEquation;
  8690. this.blendSrcAlpha = null;
  8691. this.blendDstAlpha = null;
  8692. this.blendEquationAlpha = null;
  8693. this.depthFunc = LessEqualDepth;
  8694. this.depthTest = true;
  8695. this.depthWrite = true;
  8696. this.clippingPlanes = null;
  8697. this.clipIntersection = false;
  8698. this.clipShadows = false;
  8699. this.colorWrite = true;
  8700. this.precision = null; // override the renderer's default precision for this material
  8701. this.polygonOffset = false;
  8702. this.polygonOffsetFactor = 0;
  8703. this.polygonOffsetUnits = 0;
  8704. this.alphaTest = 0;
  8705. this.premultipliedAlpha = false;
  8706. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8707. this.visible = true;
  8708. this._needsUpdate = true;
  8709. }
  8710. Material.prototype = {
  8711. constructor: Material,
  8712. isMaterial: true,
  8713. get needsUpdate() {
  8714. return this._needsUpdate;
  8715. },
  8716. set needsUpdate( value ) {
  8717. if ( value === true ) this.update();
  8718. this._needsUpdate = value;
  8719. },
  8720. setValues: function ( values ) {
  8721. if ( values === undefined ) return;
  8722. for ( var key in values ) {
  8723. var newValue = values[ key ];
  8724. if ( newValue === undefined ) {
  8725. console.warn( "THREE.Material: '" + key + "' parameter is undefined." );
  8726. continue;
  8727. }
  8728. var currentValue = this[ key ];
  8729. if ( currentValue === undefined ) {
  8730. console.warn( "THREE." + this.type + ": '" + key + "' is not a property of this material." );
  8731. continue;
  8732. }
  8733. if ( currentValue && currentValue.isColor ) {
  8734. currentValue.set( newValue );
  8735. } else if ( (currentValue && currentValue.isVector3) && (newValue && newValue.isVector3) ) {
  8736. currentValue.copy( newValue );
  8737. } else if ( key === 'overdraw' ) {
  8738. // ensure overdraw is backwards-compatible with legacy boolean type
  8739. this[ key ] = Number( newValue );
  8740. } else {
  8741. this[ key ] = newValue;
  8742. }
  8743. }
  8744. },
  8745. toJSON: function ( meta ) {
  8746. var isRoot = meta === undefined;
  8747. if ( isRoot ) {
  8748. meta = {
  8749. textures: {},
  8750. images: {}
  8751. };
  8752. }
  8753. var data = {
  8754. metadata: {
  8755. version: 4.4,
  8756. type: 'Material',
  8757. generator: 'Material.toJSON'
  8758. }
  8759. };
  8760. // standard Material serialization
  8761. data.uuid = this.uuid;
  8762. data.type = this.type;
  8763. if ( this.name !== '' ) data.name = this.name;
  8764. if ( this.color && this.color.isColor ) data.color = this.color.getHex();
  8765. if ( this.roughness !== undefined ) data.roughness = this.roughness;
  8766. if ( this.metalness !== undefined ) data.metalness = this.metalness;
  8767. if ( this.emissive && this.emissive.isColor ) data.emissive = this.emissive.getHex();
  8768. if ( this.specular && this.specular.isColor ) data.specular = this.specular.getHex();
  8769. if ( this.shininess !== undefined ) data.shininess = this.shininess;
  8770. if ( this.clearCoat !== undefined ) data.clearCoat = this.clearCoat;
  8771. if ( this.clearCoatRoughness !== undefined ) data.clearCoatRoughness = this.clearCoatRoughness;
  8772. if ( this.map && this.map.isTexture ) data.map = this.map.toJSON( meta ).uuid;
  8773. if ( this.alphaMap && this.alphaMap.isTexture ) data.alphaMap = this.alphaMap.toJSON( meta ).uuid;
  8774. if ( this.lightMap && this.lightMap.isTexture ) data.lightMap = this.lightMap.toJSON( meta ).uuid;
  8775. if ( this.bumpMap && this.bumpMap.isTexture ) {
  8776. data.bumpMap = this.bumpMap.toJSON( meta ).uuid;
  8777. data.bumpScale = this.bumpScale;
  8778. }
  8779. if ( this.normalMap && this.normalMap.isTexture ) {
  8780. data.normalMap = this.normalMap.toJSON( meta ).uuid;
  8781. data.normalScale = this.normalScale.toArray();
  8782. }
  8783. if ( this.displacementMap && this.displacementMap.isTexture ) {
  8784. data.displacementMap = this.displacementMap.toJSON( meta ).uuid;
  8785. data.displacementScale = this.displacementScale;
  8786. data.displacementBias = this.displacementBias;
  8787. }
  8788. if ( this.roughnessMap && this.roughnessMap.isTexture ) data.roughnessMap = this.roughnessMap.toJSON( meta ).uuid;
  8789. if ( this.metalnessMap && this.metalnessMap.isTexture ) data.metalnessMap = this.metalnessMap.toJSON( meta ).uuid;
  8790. if ( this.emissiveMap && this.emissiveMap.isTexture ) data.emissiveMap = this.emissiveMap.toJSON( meta ).uuid;
  8791. if ( this.specularMap && this.specularMap.isTexture ) data.specularMap = this.specularMap.toJSON( meta ).uuid;
  8792. if ( this.envMap && this.envMap.isTexture ) {
  8793. data.envMap = this.envMap.toJSON( meta ).uuid;
  8794. data.reflectivity = this.reflectivity; // Scale behind envMap
  8795. }
  8796. if ( this.gradientMap && this.gradientMap.isTexture ) {
  8797. data.gradientMap = this.gradientMap.toJSON( meta ).uuid;
  8798. }
  8799. if ( this.size !== undefined ) data.size = this.size;
  8800. if ( this.sizeAttenuation !== undefined ) data.sizeAttenuation = this.sizeAttenuation;
  8801. if ( this.blending !== NormalBlending ) data.blending = this.blending;
  8802. if ( this.shading !== SmoothShading ) data.shading = this.shading;
  8803. if ( this.side !== FrontSide ) data.side = this.side;
  8804. if ( this.vertexColors !== NoColors ) data.vertexColors = this.vertexColors;
  8805. if ( this.opacity < 1 ) data.opacity = this.opacity;
  8806. if ( this.transparent === true ) data.transparent = this.transparent;
  8807. data.depthFunc = this.depthFunc;
  8808. data.depthTest = this.depthTest;
  8809. data.depthWrite = this.depthWrite;
  8810. if ( this.alphaTest > 0 ) data.alphaTest = this.alphaTest;
  8811. if ( this.premultipliedAlpha === true ) data.premultipliedAlpha = this.premultipliedAlpha;
  8812. if ( this.wireframe === true ) data.wireframe = this.wireframe;
  8813. if ( this.wireframeLinewidth > 1 ) data.wireframeLinewidth = this.wireframeLinewidth;
  8814. if ( this.wireframeLinecap !== 'round' ) data.wireframeLinecap = this.wireframeLinecap;
  8815. if ( this.wireframeLinejoin !== 'round' ) data.wireframeLinejoin = this.wireframeLinejoin;
  8816. data.skinning = this.skinning;
  8817. data.morphTargets = this.morphTargets;
  8818. // TODO: Copied from Object3D.toJSON
  8819. function extractFromCache( cache ) {
  8820. var values = [];
  8821. for ( var key in cache ) {
  8822. var data = cache[ key ];
  8823. delete data.metadata;
  8824. values.push( data );
  8825. }
  8826. return values;
  8827. }
  8828. if ( isRoot ) {
  8829. var textures = extractFromCache( meta.textures );
  8830. var images = extractFromCache( meta.images );
  8831. if ( textures.length > 0 ) data.textures = textures;
  8832. if ( images.length > 0 ) data.images = images;
  8833. }
  8834. return data;
  8835. },
  8836. clone: function () {
  8837. return new this.constructor().copy( this );
  8838. },
  8839. copy: function ( source ) {
  8840. this.name = source.name;
  8841. this.fog = source.fog;
  8842. this.lights = source.lights;
  8843. this.blending = source.blending;
  8844. this.side = source.side;
  8845. this.shading = source.shading;
  8846. this.vertexColors = source.vertexColors;
  8847. this.opacity = source.opacity;
  8848. this.transparent = source.transparent;
  8849. this.blendSrc = source.blendSrc;
  8850. this.blendDst = source.blendDst;
  8851. this.blendEquation = source.blendEquation;
  8852. this.blendSrcAlpha = source.blendSrcAlpha;
  8853. this.blendDstAlpha = source.blendDstAlpha;
  8854. this.blendEquationAlpha = source.blendEquationAlpha;
  8855. this.depthFunc = source.depthFunc;
  8856. this.depthTest = source.depthTest;
  8857. this.depthWrite = source.depthWrite;
  8858. this.colorWrite = source.colorWrite;
  8859. this.precision = source.precision;
  8860. this.polygonOffset = source.polygonOffset;
  8861. this.polygonOffsetFactor = source.polygonOffsetFactor;
  8862. this.polygonOffsetUnits = source.polygonOffsetUnits;
  8863. this.alphaTest = source.alphaTest;
  8864. this.premultipliedAlpha = source.premultipliedAlpha;
  8865. this.overdraw = source.overdraw;
  8866. this.visible = source.visible;
  8867. this.clipShadows = source.clipShadows;
  8868. this.clipIntersection = source.clipIntersection;
  8869. var srcPlanes = source.clippingPlanes,
  8870. dstPlanes = null;
  8871. if ( srcPlanes !== null ) {
  8872. var n = srcPlanes.length;
  8873. dstPlanes = new Array( n );
  8874. for ( var i = 0; i !== n; ++ i )
  8875. dstPlanes[ i ] = srcPlanes[ i ].clone();
  8876. }
  8877. this.clippingPlanes = dstPlanes;
  8878. return this;
  8879. },
  8880. update: function () {
  8881. this.dispatchEvent( { type: 'update' } );
  8882. },
  8883. dispose: function () {
  8884. this.dispatchEvent( { type: 'dispose' } );
  8885. }
  8886. };
  8887. Object.assign( Material.prototype, EventDispatcher.prototype );
  8888. /**
  8889. * @author alteredq / http://alteredqualia.com/
  8890. *
  8891. * parameters = {
  8892. * defines: { "label" : "value" },
  8893. * uniforms: { "parameter1": { value: 1.0 }, "parameter2": { value2: 2 } },
  8894. *
  8895. * fragmentShader: <string>,
  8896. * vertexShader: <string>,
  8897. *
  8898. * wireframe: <boolean>,
  8899. * wireframeLinewidth: <float>,
  8900. *
  8901. * lights: <bool>,
  8902. *
  8903. * skinning: <bool>,
  8904. * morphTargets: <bool>,
  8905. * morphNormals: <bool>
  8906. * }
  8907. */
  8908. function ShaderMaterial( parameters ) {
  8909. Material.call( this );
  8910. this.type = 'ShaderMaterial';
  8911. this.defines = {};
  8912. this.uniforms = {};
  8913. this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
  8914. this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
  8915. this.linewidth = 1;
  8916. this.wireframe = false;
  8917. this.wireframeLinewidth = 1;
  8918. this.fog = false; // set to use scene fog
  8919. this.lights = false; // set to use scene lights
  8920. this.clipping = false; // set to use user-defined clipping planes
  8921. this.skinning = false; // set to use skinning attribute streams
  8922. this.morphTargets = false; // set to use morph targets
  8923. this.morphNormals = false; // set to use morph normals
  8924. this.extensions = {
  8925. derivatives: false, // set to use derivatives
  8926. fragDepth: false, // set to use fragment depth values
  8927. drawBuffers: false, // set to use draw buffers
  8928. shaderTextureLOD: false // set to use shader texture LOD
  8929. };
  8930. // When rendered geometry doesn't include these attributes but the material does,
  8931. // use these default values in WebGL. This avoids errors when buffer data is missing.
  8932. this.defaultAttributeValues = {
  8933. 'color': [ 1, 1, 1 ],
  8934. 'uv': [ 0, 0 ],
  8935. 'uv2': [ 0, 0 ]
  8936. };
  8937. this.index0AttributeName = undefined;
  8938. if ( parameters !== undefined ) {
  8939. if ( parameters.attributes !== undefined ) {
  8940. console.error( 'THREE.ShaderMaterial: attributes should now be defined in THREE.BufferGeometry instead.' );
  8941. }
  8942. this.setValues( parameters );
  8943. }
  8944. }
  8945. ShaderMaterial.prototype = Object.create( Material.prototype );
  8946. ShaderMaterial.prototype.constructor = ShaderMaterial;
  8947. ShaderMaterial.prototype.isShaderMaterial = true;
  8948. ShaderMaterial.prototype.copy = function ( source ) {
  8949. Material.prototype.copy.call( this, source );
  8950. this.fragmentShader = source.fragmentShader;
  8951. this.vertexShader = source.vertexShader;
  8952. this.uniforms = UniformsUtils.clone( source.uniforms );
  8953. this.defines = source.defines;
  8954. this.wireframe = source.wireframe;
  8955. this.wireframeLinewidth = source.wireframeLinewidth;
  8956. this.lights = source.lights;
  8957. this.clipping = source.clipping;
  8958. this.skinning = source.skinning;
  8959. this.morphTargets = source.morphTargets;
  8960. this.morphNormals = source.morphNormals;
  8961. this.extensions = source.extensions;
  8962. return this;
  8963. };
  8964. ShaderMaterial.prototype.toJSON = function ( meta ) {
  8965. var data = Material.prototype.toJSON.call( this, meta );
  8966. data.uniforms = this.uniforms;
  8967. data.vertexShader = this.vertexShader;
  8968. data.fragmentShader = this.fragmentShader;
  8969. return data;
  8970. };
  8971. /**
  8972. * @author mrdoob / http://mrdoob.com/
  8973. * @author alteredq / http://alteredqualia.com/
  8974. * @author bhouston / https://clara.io
  8975. * @author WestLangley / http://github.com/WestLangley
  8976. *
  8977. * parameters = {
  8978. *
  8979. * opacity: <float>,
  8980. *
  8981. * map: new THREE.Texture( <Image> ),
  8982. *
  8983. * alphaMap: new THREE.Texture( <Image> ),
  8984. *
  8985. * displacementMap: new THREE.Texture( <Image> ),
  8986. * displacementScale: <float>,
  8987. * displacementBias: <float>,
  8988. *
  8989. * wireframe: <boolean>,
  8990. * wireframeLinewidth: <float>
  8991. * }
  8992. */
  8993. function MeshDepthMaterial( parameters ) {
  8994. Material.call( this );
  8995. this.type = 'MeshDepthMaterial';
  8996. this.depthPacking = BasicDepthPacking;
  8997. this.skinning = false;
  8998. this.morphTargets = false;
  8999. this.map = null;
  9000. this.alphaMap = null;
  9001. this.displacementMap = null;
  9002. this.displacementScale = 1;
  9003. this.displacementBias = 0;
  9004. this.wireframe = false;
  9005. this.wireframeLinewidth = 1;
  9006. this.fog = false;
  9007. this.lights = false;
  9008. this.setValues( parameters );
  9009. }
  9010. MeshDepthMaterial.prototype = Object.create( Material.prototype );
  9011. MeshDepthMaterial.prototype.constructor = MeshDepthMaterial;
  9012. MeshDepthMaterial.prototype.isMeshDepthMaterial = true;
  9013. MeshDepthMaterial.prototype.copy = function ( source ) {
  9014. Material.prototype.copy.call( this, source );
  9015. this.depthPacking = source.depthPacking;
  9016. this.skinning = source.skinning;
  9017. this.morphTargets = source.morphTargets;
  9018. this.map = source.map;
  9019. this.alphaMap = source.alphaMap;
  9020. this.displacementMap = source.displacementMap;
  9021. this.displacementScale = source.displacementScale;
  9022. this.displacementBias = source.displacementBias;
  9023. this.wireframe = source.wireframe;
  9024. this.wireframeLinewidth = source.wireframeLinewidth;
  9025. return this;
  9026. };
  9027. /**
  9028. * @author bhouston / http://clara.io
  9029. * @author WestLangley / http://github.com/WestLangley
  9030. */
  9031. function Box3( min, max ) {
  9032. this.min = ( min !== undefined ) ? min : new Vector3( + Infinity, + Infinity, + Infinity );
  9033. this.max = ( max !== undefined ) ? max : new Vector3( - Infinity, - Infinity, - Infinity );
  9034. }
  9035. Box3.prototype = {
  9036. constructor: Box3,
  9037. isBox3: true,
  9038. set: function ( min, max ) {
  9039. this.min.copy( min );
  9040. this.max.copy( max );
  9041. return this;
  9042. },
  9043. setFromArray: function ( array ) {
  9044. var minX = + Infinity;
  9045. var minY = + Infinity;
  9046. var minZ = + Infinity;
  9047. var maxX = - Infinity;
  9048. var maxY = - Infinity;
  9049. var maxZ = - Infinity;
  9050. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  9051. var x = array[ i ];
  9052. var y = array[ i + 1 ];
  9053. var z = array[ i + 2 ];
  9054. if ( x < minX ) minX = x;
  9055. if ( y < minY ) minY = y;
  9056. if ( z < minZ ) minZ = z;
  9057. if ( x > maxX ) maxX = x;
  9058. if ( y > maxY ) maxY = y;
  9059. if ( z > maxZ ) maxZ = z;
  9060. }
  9061. this.min.set( minX, minY, minZ );
  9062. this.max.set( maxX, maxY, maxZ );
  9063. },
  9064. setFromBufferAttribute: function ( attribute ) {
  9065. var minX = + Infinity;
  9066. var minY = + Infinity;
  9067. var minZ = + Infinity;
  9068. var maxX = - Infinity;
  9069. var maxY = - Infinity;
  9070. var maxZ = - Infinity;
  9071. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9072. var x = attribute.getX( i );
  9073. var y = attribute.getY( i );
  9074. var z = attribute.getZ( i );
  9075. if ( x < minX ) minX = x;
  9076. if ( y < minY ) minY = y;
  9077. if ( z < minZ ) minZ = z;
  9078. if ( x > maxX ) maxX = x;
  9079. if ( y > maxY ) maxY = y;
  9080. if ( z > maxZ ) maxZ = z;
  9081. }
  9082. this.min.set( minX, minY, minZ );
  9083. this.max.set( maxX, maxY, maxZ );
  9084. },
  9085. setFromPoints: function ( points ) {
  9086. this.makeEmpty();
  9087. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9088. this.expandByPoint( points[ i ] );
  9089. }
  9090. return this;
  9091. },
  9092. setFromCenterAndSize: function () {
  9093. var v1 = new Vector3();
  9094. return function setFromCenterAndSize( center, size ) {
  9095. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  9096. this.min.copy( center ).sub( halfSize );
  9097. this.max.copy( center ).add( halfSize );
  9098. return this;
  9099. };
  9100. }(),
  9101. setFromObject: function () {
  9102. // Computes the world-axis-aligned bounding box of an object (including its children),
  9103. // accounting for both the object's, and children's, world transforms
  9104. var v1 = new Vector3();
  9105. return function setFromObject( object ) {
  9106. var scope = this;
  9107. object.updateMatrixWorld( true );
  9108. this.makeEmpty();
  9109. object.traverse( function ( node ) {
  9110. var i, l;
  9111. var geometry = node.geometry;
  9112. if ( geometry !== undefined ) {
  9113. if ( geometry.isGeometry ) {
  9114. var vertices = geometry.vertices;
  9115. for ( i = 0, l = vertices.length; i < l; i ++ ) {
  9116. v1.copy( vertices[ i ] );
  9117. v1.applyMatrix4( node.matrixWorld );
  9118. scope.expandByPoint( v1 );
  9119. }
  9120. } else if ( geometry.isBufferGeometry ) {
  9121. var attribute = geometry.attributes.position;
  9122. if ( attribute !== undefined ) {
  9123. for ( i = 0, l = attribute.count; i < l; i ++ ) {
  9124. v1.fromAttribute( attribute, i ).applyMatrix4( node.matrixWorld );
  9125. scope.expandByPoint( v1 );
  9126. }
  9127. }
  9128. }
  9129. }
  9130. } );
  9131. return this;
  9132. };
  9133. }(),
  9134. clone: function () {
  9135. return new this.constructor().copy( this );
  9136. },
  9137. copy: function ( box ) {
  9138. this.min.copy( box.min );
  9139. this.max.copy( box.max );
  9140. return this;
  9141. },
  9142. makeEmpty: function () {
  9143. this.min.x = this.min.y = this.min.z = + Infinity;
  9144. this.max.x = this.max.y = this.max.z = - Infinity;
  9145. return this;
  9146. },
  9147. isEmpty: function () {
  9148. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  9149. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  9150. },
  9151. getCenter: function ( optionalTarget ) {
  9152. var result = optionalTarget || new Vector3();
  9153. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  9154. },
  9155. getSize: function ( optionalTarget ) {
  9156. var result = optionalTarget || new Vector3();
  9157. return this.isEmpty() ? result.set( 0, 0, 0 ) : result.subVectors( this.max, this.min );
  9158. },
  9159. expandByPoint: function ( point ) {
  9160. this.min.min( point );
  9161. this.max.max( point );
  9162. return this;
  9163. },
  9164. expandByVector: function ( vector ) {
  9165. this.min.sub( vector );
  9166. this.max.add( vector );
  9167. return this;
  9168. },
  9169. expandByScalar: function ( scalar ) {
  9170. this.min.addScalar( - scalar );
  9171. this.max.addScalar( scalar );
  9172. return this;
  9173. },
  9174. containsPoint: function ( point ) {
  9175. return point.x < this.min.x || point.x > this.max.x ||
  9176. point.y < this.min.y || point.y > this.max.y ||
  9177. point.z < this.min.z || point.z > this.max.z ? false : true;
  9178. },
  9179. containsBox: function ( box ) {
  9180. return this.min.x <= box.min.x && box.max.x <= this.max.x &&
  9181. this.min.y <= box.min.y && box.max.y <= this.max.y &&
  9182. this.min.z <= box.min.z && box.max.z <= this.max.z;
  9183. },
  9184. getParameter: function ( point, optionalTarget ) {
  9185. // This can potentially have a divide by zero if the box
  9186. // has a size dimension of 0.
  9187. var result = optionalTarget || new Vector3();
  9188. return result.set(
  9189. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  9190. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  9191. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  9192. );
  9193. },
  9194. intersectsBox: function ( box ) {
  9195. // using 6 splitting planes to rule out intersections.
  9196. return box.max.x < this.min.x || box.min.x > this.max.x ||
  9197. box.max.y < this.min.y || box.min.y > this.max.y ||
  9198. box.max.z < this.min.z || box.min.z > this.max.z ? false : true;
  9199. },
  9200. intersectsSphere: ( function () {
  9201. var closestPoint;
  9202. return function intersectsSphere( sphere ) {
  9203. if ( closestPoint === undefined ) closestPoint = new Vector3();
  9204. // Find the point on the AABB closest to the sphere center.
  9205. this.clampPoint( sphere.center, closestPoint );
  9206. // If that point is inside the sphere, the AABB and sphere intersect.
  9207. return closestPoint.distanceToSquared( sphere.center ) <= ( sphere.radius * sphere.radius );
  9208. };
  9209. } )(),
  9210. intersectsPlane: function ( plane ) {
  9211. // We compute the minimum and maximum dot product values. If those values
  9212. // are on the same side (back or front) of the plane, then there is no intersection.
  9213. var min, max;
  9214. if ( plane.normal.x > 0 ) {
  9215. min = plane.normal.x * this.min.x;
  9216. max = plane.normal.x * this.max.x;
  9217. } else {
  9218. min = plane.normal.x * this.max.x;
  9219. max = plane.normal.x * this.min.x;
  9220. }
  9221. if ( plane.normal.y > 0 ) {
  9222. min += plane.normal.y * this.min.y;
  9223. max += plane.normal.y * this.max.y;
  9224. } else {
  9225. min += plane.normal.y * this.max.y;
  9226. max += plane.normal.y * this.min.y;
  9227. }
  9228. if ( plane.normal.z > 0 ) {
  9229. min += plane.normal.z * this.min.z;
  9230. max += plane.normal.z * this.max.z;
  9231. } else {
  9232. min += plane.normal.z * this.max.z;
  9233. max += plane.normal.z * this.min.z;
  9234. }
  9235. return ( min <= plane.constant && max >= plane.constant );
  9236. },
  9237. clampPoint: function ( point, optionalTarget ) {
  9238. var result = optionalTarget || new Vector3();
  9239. return result.copy( point ).clamp( this.min, this.max );
  9240. },
  9241. distanceToPoint: function () {
  9242. var v1 = new Vector3();
  9243. return function distanceToPoint( point ) {
  9244. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  9245. return clampedPoint.sub( point ).length();
  9246. };
  9247. }(),
  9248. getBoundingSphere: function () {
  9249. var v1 = new Vector3();
  9250. return function getBoundingSphere( optionalTarget ) {
  9251. var result = optionalTarget || new Sphere();
  9252. this.getCenter( result.center );
  9253. result.radius = this.getSize( v1 ).length() * 0.5;
  9254. return result;
  9255. };
  9256. }(),
  9257. intersect: function ( box ) {
  9258. this.min.max( box.min );
  9259. this.max.min( box.max );
  9260. // 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.
  9261. if( this.isEmpty() ) this.makeEmpty();
  9262. return this;
  9263. },
  9264. union: function ( box ) {
  9265. this.min.min( box.min );
  9266. this.max.max( box.max );
  9267. return this;
  9268. },
  9269. applyMatrix4: function () {
  9270. var points = [
  9271. new Vector3(),
  9272. new Vector3(),
  9273. new Vector3(),
  9274. new Vector3(),
  9275. new Vector3(),
  9276. new Vector3(),
  9277. new Vector3(),
  9278. new Vector3()
  9279. ];
  9280. return function applyMatrix4( matrix ) {
  9281. // transform of empty box is an empty box.
  9282. if( this.isEmpty() ) return this;
  9283. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  9284. points[ 0 ].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  9285. points[ 1 ].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  9286. points[ 2 ].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  9287. points[ 3 ].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  9288. points[ 4 ].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  9289. points[ 5 ].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  9290. points[ 6 ].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  9291. points[ 7 ].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  9292. this.setFromPoints( points );
  9293. return this;
  9294. };
  9295. }(),
  9296. translate: function ( offset ) {
  9297. this.min.add( offset );
  9298. this.max.add( offset );
  9299. return this;
  9300. },
  9301. equals: function ( box ) {
  9302. return box.min.equals( this.min ) && box.max.equals( this.max );
  9303. }
  9304. };
  9305. /**
  9306. * @author bhouston / http://clara.io
  9307. * @author mrdoob / http://mrdoob.com/
  9308. */
  9309. function Sphere( center, radius ) {
  9310. this.center = ( center !== undefined ) ? center : new Vector3();
  9311. this.radius = ( radius !== undefined ) ? radius : 0;
  9312. }
  9313. Sphere.prototype = {
  9314. constructor: Sphere,
  9315. set: function ( center, radius ) {
  9316. this.center.copy( center );
  9317. this.radius = radius;
  9318. return this;
  9319. },
  9320. setFromPoints: function () {
  9321. var box = new Box3();
  9322. return function setFromPoints( points, optionalCenter ) {
  9323. var center = this.center;
  9324. if ( optionalCenter !== undefined ) {
  9325. center.copy( optionalCenter );
  9326. } else {
  9327. box.setFromPoints( points ).getCenter( center );
  9328. }
  9329. var maxRadiusSq = 0;
  9330. for ( var i = 0, il = points.length; i < il; i ++ ) {
  9331. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  9332. }
  9333. this.radius = Math.sqrt( maxRadiusSq );
  9334. return this;
  9335. };
  9336. }(),
  9337. clone: function () {
  9338. return new this.constructor().copy( this );
  9339. },
  9340. copy: function ( sphere ) {
  9341. this.center.copy( sphere.center );
  9342. this.radius = sphere.radius;
  9343. return this;
  9344. },
  9345. empty: function () {
  9346. return ( this.radius <= 0 );
  9347. },
  9348. containsPoint: function ( point ) {
  9349. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  9350. },
  9351. distanceToPoint: function ( point ) {
  9352. return ( point.distanceTo( this.center ) - this.radius );
  9353. },
  9354. intersectsSphere: function ( sphere ) {
  9355. var radiusSum = this.radius + sphere.radius;
  9356. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  9357. },
  9358. intersectsBox: function ( box ) {
  9359. return box.intersectsSphere( this );
  9360. },
  9361. intersectsPlane: function ( plane ) {
  9362. // We use the following equation to compute the signed distance from
  9363. // the center of the sphere to the plane.
  9364. //
  9365. // distance = q * n - d
  9366. //
  9367. // If this distance is greater than the radius of the sphere,
  9368. // then there is no intersection.
  9369. return Math.abs( this.center.dot( plane.normal ) - plane.constant ) <= this.radius;
  9370. },
  9371. clampPoint: function ( point, optionalTarget ) {
  9372. var deltaLengthSq = this.center.distanceToSquared( point );
  9373. var result = optionalTarget || new Vector3();
  9374. result.copy( point );
  9375. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  9376. result.sub( this.center ).normalize();
  9377. result.multiplyScalar( this.radius ).add( this.center );
  9378. }
  9379. return result;
  9380. },
  9381. getBoundingBox: function ( optionalTarget ) {
  9382. var box = optionalTarget || new Box3();
  9383. box.set( this.center, this.center );
  9384. box.expandByScalar( this.radius );
  9385. return box;
  9386. },
  9387. applyMatrix4: function ( matrix ) {
  9388. this.center.applyMatrix4( matrix );
  9389. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  9390. return this;
  9391. },
  9392. translate: function ( offset ) {
  9393. this.center.add( offset );
  9394. return this;
  9395. },
  9396. equals: function ( sphere ) {
  9397. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  9398. }
  9399. };
  9400. /**
  9401. * @author alteredq / http://alteredqualia.com/
  9402. * @author WestLangley / http://github.com/WestLangley
  9403. * @author bhouston / http://clara.io
  9404. * @author tschw
  9405. */
  9406. function Matrix3() {
  9407. this.elements = new Float32Array( [
  9408. 1, 0, 0,
  9409. 0, 1, 0,
  9410. 0, 0, 1
  9411. ] );
  9412. if ( arguments.length > 0 ) {
  9413. console.error( 'THREE.Matrix3: the constructor no longer reads arguments. use .set() instead.' );
  9414. }
  9415. }
  9416. Matrix3.prototype = {
  9417. constructor: Matrix3,
  9418. isMatrix3: true,
  9419. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  9420. var te = this.elements;
  9421. te[ 0 ] = n11; te[ 1 ] = n21; te[ 2 ] = n31;
  9422. te[ 3 ] = n12; te[ 4 ] = n22; te[ 5 ] = n32;
  9423. te[ 6 ] = n13; te[ 7 ] = n23; te[ 8 ] = n33;
  9424. return this;
  9425. },
  9426. identity: function () {
  9427. this.set(
  9428. 1, 0, 0,
  9429. 0, 1, 0,
  9430. 0, 0, 1
  9431. );
  9432. return this;
  9433. },
  9434. clone: function () {
  9435. return new this.constructor().fromArray( this.elements );
  9436. },
  9437. copy: function ( m ) {
  9438. var me = m.elements;
  9439. this.set(
  9440. me[ 0 ], me[ 3 ], me[ 6 ],
  9441. me[ 1 ], me[ 4 ], me[ 7 ],
  9442. me[ 2 ], me[ 5 ], me[ 8 ]
  9443. );
  9444. return this;
  9445. },
  9446. setFromMatrix4: function( m ) {
  9447. var me = m.elements;
  9448. this.set(
  9449. me[ 0 ], me[ 4 ], me[ 8 ],
  9450. me[ 1 ], me[ 5 ], me[ 9 ],
  9451. me[ 2 ], me[ 6 ], me[ 10 ]
  9452. );
  9453. return this;
  9454. },
  9455. applyToVector3Array: function () {
  9456. var v1;
  9457. return function applyToVector3Array( array, offset, length ) {
  9458. if ( v1 === undefined ) v1 = new Vector3();
  9459. if ( offset === undefined ) offset = 0;
  9460. if ( length === undefined ) length = array.length;
  9461. for ( var i = 0, j = offset; i < length; i += 3, j += 3 ) {
  9462. v1.fromArray( array, j );
  9463. v1.applyMatrix3( this );
  9464. v1.toArray( array, j );
  9465. }
  9466. return array;
  9467. };
  9468. }(),
  9469. applyToBufferAttribute: function () {
  9470. var v1;
  9471. return function applyToBufferAttribute( attribute ) {
  9472. if ( v1 === undefined ) v1 = new Vector3();
  9473. for ( var i = 0, l = attribute.count; i < l; i ++ ) {
  9474. v1.x = attribute.getX( i );
  9475. v1.y = attribute.getY( i );
  9476. v1.z = attribute.getZ( i );
  9477. v1.applyMatrix3( this );
  9478. attribute.setXYZ( i, v1.x, v1.y, v1.z );
  9479. }
  9480. return attribute;
  9481. };
  9482. }(),
  9483. multiplyScalar: function ( s ) {
  9484. var te = this.elements;
  9485. te[ 0 ] *= s; te[ 3 ] *= s; te[ 6 ] *= s;
  9486. te[ 1 ] *= s; te[ 4 ] *= s; te[ 7 ] *= s;
  9487. te[ 2 ] *= s; te[ 5 ] *= s; te[ 8 ] *= s;
  9488. return this;
  9489. },
  9490. determinant: function () {
  9491. var te = this.elements;
  9492. var a = te[ 0 ], b = te[ 1 ], c = te[ 2 ],
  9493. d = te[ 3 ], e = te[ 4 ], f = te[ 5 ],
  9494. g = te[ 6 ], h = te[ 7 ], i = te[ 8 ];
  9495. return a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g;
  9496. },
  9497. getInverse: function ( matrix, throwOnDegenerate ) {
  9498. if ( matrix && matrix.isMatrix4 ) {
  9499. console.error( "THREE.Matrix3.getInverse no longer takes a Matrix4 argument." );
  9500. }
  9501. var me = matrix.elements,
  9502. te = this.elements,
  9503. n11 = me[ 0 ], n21 = me[ 1 ], n31 = me[ 2 ],
  9504. n12 = me[ 3 ], n22 = me[ 4 ], n32 = me[ 5 ],
  9505. n13 = me[ 6 ], n23 = me[ 7 ], n33 = me[ 8 ],
  9506. t11 = n33 * n22 - n32 * n23,
  9507. t12 = n32 * n13 - n33 * n12,
  9508. t13 = n23 * n12 - n22 * n13,
  9509. det = n11 * t11 + n21 * t12 + n31 * t13;
  9510. if ( det === 0 ) {
  9511. var msg = "THREE.Matrix3.getInverse(): can't invert matrix, determinant is 0";
  9512. if ( throwOnDegenerate === true ) {
  9513. throw new Error( msg );
  9514. } else {
  9515. console.warn( msg );
  9516. }
  9517. return this.identity();
  9518. }
  9519. var detInv = 1 / det;
  9520. te[ 0 ] = t11 * detInv;
  9521. te[ 1 ] = ( n31 * n23 - n33 * n21 ) * detInv;
  9522. te[ 2 ] = ( n32 * n21 - n31 * n22 ) * detInv;
  9523. te[ 3 ] = t12 * detInv;
  9524. te[ 4 ] = ( n33 * n11 - n31 * n13 ) * detInv;
  9525. te[ 5 ] = ( n31 * n12 - n32 * n11 ) * detInv;
  9526. te[ 6 ] = t13 * detInv;
  9527. te[ 7 ] = ( n21 * n13 - n23 * n11 ) * detInv;
  9528. te[ 8 ] = ( n22 * n11 - n21 * n12 ) * detInv;
  9529. return this;
  9530. },
  9531. transpose: function () {
  9532. var tmp, m = this.elements;
  9533. tmp = m[ 1 ]; m[ 1 ] = m[ 3 ]; m[ 3 ] = tmp;
  9534. tmp = m[ 2 ]; m[ 2 ] = m[ 6 ]; m[ 6 ] = tmp;
  9535. tmp = m[ 5 ]; m[ 5 ] = m[ 7 ]; m[ 7 ] = tmp;
  9536. return this;
  9537. },
  9538. getNormalMatrix: function ( matrix4 ) {
  9539. return this.setFromMatrix4( matrix4 ).getInverse( this ).transpose();
  9540. },
  9541. transposeIntoArray: function ( r ) {
  9542. var m = this.elements;
  9543. r[ 0 ] = m[ 0 ];
  9544. r[ 1 ] = m[ 3 ];
  9545. r[ 2 ] = m[ 6 ];
  9546. r[ 3 ] = m[ 1 ];
  9547. r[ 4 ] = m[ 4 ];
  9548. r[ 5 ] = m[ 7 ];
  9549. r[ 6 ] = m[ 2 ];
  9550. r[ 7 ] = m[ 5 ];
  9551. r[ 8 ] = m[ 8 ];
  9552. return this;
  9553. },
  9554. fromArray: function ( array, offset ) {
  9555. if ( offset === undefined ) offset = 0;
  9556. for( var i = 0; i < 9; i ++ ) {
  9557. this.elements[ i ] = array[ i + offset ];
  9558. }
  9559. return this;
  9560. },
  9561. toArray: function ( array, offset ) {
  9562. if ( array === undefined ) array = [];
  9563. if ( offset === undefined ) offset = 0;
  9564. var te = this.elements;
  9565. array[ offset ] = te[ 0 ];
  9566. array[ offset + 1 ] = te[ 1 ];
  9567. array[ offset + 2 ] = te[ 2 ];
  9568. array[ offset + 3 ] = te[ 3 ];
  9569. array[ offset + 4 ] = te[ 4 ];
  9570. array[ offset + 5 ] = te[ 5 ];
  9571. array[ offset + 6 ] = te[ 6 ];
  9572. array[ offset + 7 ] = te[ 7 ];
  9573. array[ offset + 8 ] = te[ 8 ];
  9574. return array;
  9575. }
  9576. };
  9577. /**
  9578. * @author bhouston / http://clara.io
  9579. */
  9580. function Plane( normal, constant ) {
  9581. this.normal = ( normal !== undefined ) ? normal : new Vector3( 1, 0, 0 );
  9582. this.constant = ( constant !== undefined ) ? constant : 0;
  9583. }
  9584. Plane.prototype = {
  9585. constructor: Plane,
  9586. set: function ( normal, constant ) {
  9587. this.normal.copy( normal );
  9588. this.constant = constant;
  9589. return this;
  9590. },
  9591. setComponents: function ( x, y, z, w ) {
  9592. this.normal.set( x, y, z );
  9593. this.constant = w;
  9594. return this;
  9595. },
  9596. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  9597. this.normal.copy( normal );
  9598. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  9599. return this;
  9600. },
  9601. setFromCoplanarPoints: function () {
  9602. var v1 = new Vector3();
  9603. var v2 = new Vector3();
  9604. return function setFromCoplanarPoints( a, b, c ) {
  9605. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  9606. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  9607. this.setFromNormalAndCoplanarPoint( normal, a );
  9608. return this;
  9609. };
  9610. }(),
  9611. clone: function () {
  9612. return new this.constructor().copy( this );
  9613. },
  9614. copy: function ( plane ) {
  9615. this.normal.copy( plane.normal );
  9616. this.constant = plane.constant;
  9617. return this;
  9618. },
  9619. normalize: function () {
  9620. // Note: will lead to a divide by zero if the plane is invalid.
  9621. var inverseNormalLength = 1.0 / this.normal.length();
  9622. this.normal.multiplyScalar( inverseNormalLength );
  9623. this.constant *= inverseNormalLength;
  9624. return this;
  9625. },
  9626. negate: function () {
  9627. this.constant *= - 1;
  9628. this.normal.negate();
  9629. return this;
  9630. },
  9631. distanceToPoint: function ( point ) {
  9632. return this.normal.dot( point ) + this.constant;
  9633. },
  9634. distanceToSphere: function ( sphere ) {
  9635. return this.distanceToPoint( sphere.center ) - sphere.radius;
  9636. },
  9637. projectPoint: function ( point, optionalTarget ) {
  9638. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  9639. },
  9640. orthoPoint: function ( point, optionalTarget ) {
  9641. var perpendicularMagnitude = this.distanceToPoint( point );
  9642. var result = optionalTarget || new Vector3();
  9643. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  9644. },
  9645. intersectLine: function () {
  9646. var v1 = new Vector3();
  9647. return function intersectLine( line, optionalTarget ) {
  9648. var result = optionalTarget || new Vector3();
  9649. var direction = line.delta( v1 );
  9650. var denominator = this.normal.dot( direction );
  9651. if ( denominator === 0 ) {
  9652. // line is coplanar, return origin
  9653. if ( this.distanceToPoint( line.start ) === 0 ) {
  9654. return result.copy( line.start );
  9655. }
  9656. // Unsure if this is the correct method to handle this case.
  9657. return undefined;
  9658. }
  9659. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  9660. if ( t < 0 || t > 1 ) {
  9661. return undefined;
  9662. }
  9663. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  9664. };
  9665. }(),
  9666. intersectsLine: function ( line ) {
  9667. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  9668. var startSign = this.distanceToPoint( line.start );
  9669. var endSign = this.distanceToPoint( line.end );
  9670. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  9671. },
  9672. intersectsBox: function ( box ) {
  9673. return box.intersectsPlane( this );
  9674. },
  9675. intersectsSphere: function ( sphere ) {
  9676. return sphere.intersectsPlane( this );
  9677. },
  9678. coplanarPoint: function ( optionalTarget ) {
  9679. var result = optionalTarget || new Vector3();
  9680. return result.copy( this.normal ).multiplyScalar( - this.constant );
  9681. },
  9682. applyMatrix4: function () {
  9683. var v1 = new Vector3();
  9684. var m1 = new Matrix3();
  9685. return function applyMatrix4( matrix, optionalNormalMatrix ) {
  9686. var referencePoint = this.coplanarPoint( v1 ).applyMatrix4( matrix );
  9687. // transform normal based on theory here:
  9688. // http://www.songho.ca/opengl/gl_normaltransform.html
  9689. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  9690. var normal = this.normal.applyMatrix3( normalMatrix ).normalize();
  9691. // recalculate constant (like in setFromNormalAndCoplanarPoint)
  9692. this.constant = - referencePoint.dot( normal );
  9693. return this;
  9694. };
  9695. }(),
  9696. translate: function ( offset ) {
  9697. this.constant = this.constant - offset.dot( this.normal );
  9698. return this;
  9699. },
  9700. equals: function ( plane ) {
  9701. return plane.normal.equals( this.normal ) && ( plane.constant === this.constant );
  9702. }
  9703. };
  9704. /**
  9705. * @author mrdoob / http://mrdoob.com/
  9706. * @author alteredq / http://alteredqualia.com/
  9707. * @author bhouston / http://clara.io
  9708. */
  9709. function Frustum( p0, p1, p2, p3, p4, p5 ) {
  9710. this.planes = [
  9711. ( p0 !== undefined ) ? p0 : new Plane(),
  9712. ( p1 !== undefined ) ? p1 : new Plane(),
  9713. ( p2 !== undefined ) ? p2 : new Plane(),
  9714. ( p3 !== undefined ) ? p3 : new Plane(),
  9715. ( p4 !== undefined ) ? p4 : new Plane(),
  9716. ( p5 !== undefined ) ? p5 : new Plane()
  9717. ];
  9718. }
  9719. Frustum.prototype = {
  9720. constructor: Frustum,
  9721. set: function ( p0, p1, p2, p3, p4, p5 ) {
  9722. var planes = this.planes;
  9723. planes[ 0 ].copy( p0 );
  9724. planes[ 1 ].copy( p1 );
  9725. planes[ 2 ].copy( p2 );
  9726. planes[ 3 ].copy( p3 );
  9727. planes[ 4 ].copy( p4 );
  9728. planes[ 5 ].copy( p5 );
  9729. return this;
  9730. },
  9731. clone: function () {
  9732. return new this.constructor().copy( this );
  9733. },
  9734. copy: function ( frustum ) {
  9735. var planes = this.planes;
  9736. for ( var i = 0; i < 6; i ++ ) {
  9737. planes[ i ].copy( frustum.planes[ i ] );
  9738. }
  9739. return this;
  9740. },
  9741. setFromMatrix: function ( m ) {
  9742. var planes = this.planes;
  9743. var me = m.elements;
  9744. var me0 = me[ 0 ], me1 = me[ 1 ], me2 = me[ 2 ], me3 = me[ 3 ];
  9745. var me4 = me[ 4 ], me5 = me[ 5 ], me6 = me[ 6 ], me7 = me[ 7 ];
  9746. var me8 = me[ 8 ], me9 = me[ 9 ], me10 = me[ 10 ], me11 = me[ 11 ];
  9747. var me12 = me[ 12 ], me13 = me[ 13 ], me14 = me[ 14 ], me15 = me[ 15 ];
  9748. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  9749. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  9750. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  9751. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  9752. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  9753. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  9754. return this;
  9755. },
  9756. intersectsObject: function () {
  9757. var sphere = new Sphere();
  9758. return function intersectsObject( object ) {
  9759. var geometry = object.geometry;
  9760. if ( geometry.boundingSphere === null )
  9761. geometry.computeBoundingSphere();
  9762. sphere.copy( geometry.boundingSphere )
  9763. .applyMatrix4( object.matrixWorld );
  9764. return this.intersectsSphere( sphere );
  9765. };
  9766. }(),
  9767. intersectsSprite: function () {
  9768. var sphere = new Sphere();
  9769. return function intersectsSprite( sprite ) {
  9770. sphere.center.set( 0, 0, 0 );
  9771. sphere.radius = 0.7071067811865476;
  9772. sphere.applyMatrix4( sprite.matrixWorld );
  9773. return this.intersectsSphere( sphere );
  9774. };
  9775. }(),
  9776. intersectsSphere: function ( sphere ) {
  9777. var planes = this.planes;
  9778. var center = sphere.center;
  9779. var negRadius = - sphere.radius;
  9780. for ( var i = 0; i < 6; i ++ ) {
  9781. var distance = planes[ i ].distanceToPoint( center );
  9782. if ( distance < negRadius ) {
  9783. return false;
  9784. }
  9785. }
  9786. return true;
  9787. },
  9788. intersectsBox: function () {
  9789. var p1 = new Vector3(),
  9790. p2 = new Vector3();
  9791. return function intersectsBox( box ) {
  9792. var planes = this.planes;
  9793. for ( var i = 0; i < 6 ; i ++ ) {
  9794. var plane = planes[ i ];
  9795. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  9796. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  9797. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  9798. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  9799. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  9800. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  9801. var d1 = plane.distanceToPoint( p1 );
  9802. var d2 = plane.distanceToPoint( p2 );
  9803. // if both outside plane, no intersection
  9804. if ( d1 < 0 && d2 < 0 ) {
  9805. return false;
  9806. }
  9807. }
  9808. return true;
  9809. };
  9810. }(),
  9811. containsPoint: function ( point ) {
  9812. var planes = this.planes;
  9813. for ( var i = 0; i < 6; i ++ ) {
  9814. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  9815. return false;
  9816. }
  9817. }
  9818. return true;
  9819. }
  9820. };
  9821. /**
  9822. * @author alteredq / http://alteredqualia.com/
  9823. * @author mrdoob / http://mrdoob.com/
  9824. */
  9825. function WebGLShadowMap( _renderer, _lights, _objects, capabilities ) {
  9826. var _gl = _renderer.context,
  9827. _state = _renderer.state,
  9828. _frustum = new Frustum(),
  9829. _projScreenMatrix = new Matrix4(),
  9830. _lightShadows = _lights.shadows,
  9831. _shadowMapSize = new Vector2(),
  9832. _maxShadowMapSize = new Vector2( capabilities.maxTextureSize, capabilities.maxTextureSize ),
  9833. _lookTarget = new Vector3(),
  9834. _lightPositionWorld = new Vector3(),
  9835. _renderList = [],
  9836. _MorphingFlag = 1,
  9837. _SkinningFlag = 2,
  9838. _NumberOfMaterialVariants = ( _MorphingFlag | _SkinningFlag ) + 1,
  9839. _depthMaterials = new Array( _NumberOfMaterialVariants ),
  9840. _distanceMaterials = new Array( _NumberOfMaterialVariants ),
  9841. _materialCache = {};
  9842. var cubeDirections = [
  9843. new Vector3( 1, 0, 0 ), new Vector3( - 1, 0, 0 ), new Vector3( 0, 0, 1 ),
  9844. new Vector3( 0, 0, - 1 ), new Vector3( 0, 1, 0 ), new Vector3( 0, - 1, 0 )
  9845. ];
  9846. var cubeUps = [
  9847. new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ), new Vector3( 0, 1, 0 ),
  9848. new Vector3( 0, 1, 0 ), new Vector3( 0, 0, 1 ), new Vector3( 0, 0, - 1 )
  9849. ];
  9850. var cube2DViewPorts = [
  9851. new Vector4(), new Vector4(), new Vector4(),
  9852. new Vector4(), new Vector4(), new Vector4()
  9853. ];
  9854. // init
  9855. var depthMaterialTemplate = new MeshDepthMaterial();
  9856. depthMaterialTemplate.depthPacking = RGBADepthPacking;
  9857. depthMaterialTemplate.clipping = true;
  9858. var distanceShader = ShaderLib[ "distanceRGBA" ];
  9859. var distanceUniforms = UniformsUtils.clone( distanceShader.uniforms );
  9860. for ( var i = 0; i !== _NumberOfMaterialVariants; ++ i ) {
  9861. var useMorphing = ( i & _MorphingFlag ) !== 0;
  9862. var useSkinning = ( i & _SkinningFlag ) !== 0;
  9863. var depthMaterial = depthMaterialTemplate.clone();
  9864. depthMaterial.morphTargets = useMorphing;
  9865. depthMaterial.skinning = useSkinning;
  9866. _depthMaterials[ i ] = depthMaterial;
  9867. var distanceMaterial = new ShaderMaterial( {
  9868. defines: {
  9869. 'USE_SHADOWMAP': ''
  9870. },
  9871. uniforms: distanceUniforms,
  9872. vertexShader: distanceShader.vertexShader,
  9873. fragmentShader: distanceShader.fragmentShader,
  9874. morphTargets: useMorphing,
  9875. skinning: useSkinning,
  9876. clipping: true
  9877. } );
  9878. _distanceMaterials[ i ] = distanceMaterial;
  9879. }
  9880. //
  9881. var scope = this;
  9882. this.enabled = false;
  9883. this.autoUpdate = true;
  9884. this.needsUpdate = false;
  9885. this.type = PCFShadowMap;
  9886. this.renderReverseSided = true;
  9887. this.renderSingleSided = true;
  9888. this.render = function ( scene, camera ) {
  9889. if ( scope.enabled === false ) return;
  9890. if ( scope.autoUpdate === false && scope.needsUpdate === false ) return;
  9891. if ( _lightShadows.length === 0 ) return;
  9892. // Set GL state for depth map.
  9893. _state.buffers.color.setClear( 1, 1, 1, 1 );
  9894. _state.disable( _gl.BLEND );
  9895. _state.setDepthTest( true );
  9896. _state.setScissorTest( false );
  9897. // render depth map
  9898. var faceCount, isPointLight;
  9899. for ( var i = 0, il = _lightShadows.length; i < il; i ++ ) {
  9900. var light = _lightShadows[ i ];
  9901. var shadow = light.shadow;
  9902. if ( shadow === undefined ) {
  9903. console.warn( 'THREE.WebGLShadowMap:', light, 'has no shadow.' );
  9904. continue;
  9905. }
  9906. var shadowCamera = shadow.camera;
  9907. _shadowMapSize.copy( shadow.mapSize );
  9908. _shadowMapSize.min( _maxShadowMapSize );
  9909. if ( light && light.isPointLight ) {
  9910. faceCount = 6;
  9911. isPointLight = true;
  9912. var vpWidth = _shadowMapSize.x;
  9913. var vpHeight = _shadowMapSize.y;
  9914. // These viewports map a cube-map onto a 2D texture with the
  9915. // following orientation:
  9916. //
  9917. // xzXZ
  9918. // y Y
  9919. //
  9920. // X - Positive x direction
  9921. // x - Negative x direction
  9922. // Y - Positive y direction
  9923. // y - Negative y direction
  9924. // Z - Positive z direction
  9925. // z - Negative z direction
  9926. // positive X
  9927. cube2DViewPorts[ 0 ].set( vpWidth * 2, vpHeight, vpWidth, vpHeight );
  9928. // negative X
  9929. cube2DViewPorts[ 1 ].set( 0, vpHeight, vpWidth, vpHeight );
  9930. // positive Z
  9931. cube2DViewPorts[ 2 ].set( vpWidth * 3, vpHeight, vpWidth, vpHeight );
  9932. // negative Z
  9933. cube2DViewPorts[ 3 ].set( vpWidth, vpHeight, vpWidth, vpHeight );
  9934. // positive Y
  9935. cube2DViewPorts[ 4 ].set( vpWidth * 3, 0, vpWidth, vpHeight );
  9936. // negative Y
  9937. cube2DViewPorts[ 5 ].set( vpWidth, 0, vpWidth, vpHeight );
  9938. _shadowMapSize.x *= 4.0;
  9939. _shadowMapSize.y *= 2.0;
  9940. } else {
  9941. faceCount = 1;
  9942. isPointLight = false;
  9943. }
  9944. if ( shadow.map === null ) {
  9945. var pars = { minFilter: NearestFilter, magFilter: NearestFilter, format: RGBAFormat };
  9946. shadow.map = new WebGLRenderTarget( _shadowMapSize.x, _shadowMapSize.y, pars );
  9947. shadowCamera.updateProjectionMatrix();
  9948. }
  9949. if ( shadow.isSpotLightShadow ) {
  9950. shadow.update( light );
  9951. }
  9952. // TODO (abelnation / sam-g-steel): is this needed?
  9953. if (shadow && shadow.isRectAreaLightShadow ) {
  9954. shadow.update( light );
  9955. }
  9956. var shadowMap = shadow.map;
  9957. var shadowMatrix = shadow.matrix;
  9958. _lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
  9959. shadowCamera.position.copy( _lightPositionWorld );
  9960. _renderer.setRenderTarget( shadowMap );
  9961. _renderer.clear();
  9962. // render shadow map for each cube face (if omni-directional) or
  9963. // run a single pass if not
  9964. for ( var face = 0; face < faceCount; face ++ ) {
  9965. if ( isPointLight ) {
  9966. _lookTarget.copy( shadowCamera.position );
  9967. _lookTarget.add( cubeDirections[ face ] );
  9968. shadowCamera.up.copy( cubeUps[ face ] );
  9969. shadowCamera.lookAt( _lookTarget );
  9970. var vpDimensions = cube2DViewPorts[ face ];
  9971. _state.viewport( vpDimensions );
  9972. } else {
  9973. _lookTarget.setFromMatrixPosition( light.target.matrixWorld );
  9974. shadowCamera.lookAt( _lookTarget );
  9975. }
  9976. shadowCamera.updateMatrixWorld();
  9977. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  9978. // compute shadow matrix
  9979. shadowMatrix.set(
  9980. 0.5, 0.0, 0.0, 0.5,
  9981. 0.0, 0.5, 0.0, 0.5,
  9982. 0.0, 0.0, 0.5, 0.5,
  9983. 0.0, 0.0, 0.0, 1.0
  9984. );
  9985. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  9986. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  9987. // update camera matrices and frustum
  9988. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  9989. _frustum.setFromMatrix( _projScreenMatrix );
  9990. // set object matrices & frustum culling
  9991. _renderList.length = 0;
  9992. projectObject( scene, camera, shadowCamera );
  9993. // render shadow map
  9994. // render regular objects
  9995. for ( var j = 0, jl = _renderList.length; j < jl; j ++ ) {
  9996. var object = _renderList[ j ];
  9997. var geometry = _objects.update( object );
  9998. var material = object.material;
  9999. if ( material && material.isMultiMaterial ) {
  10000. var groups = geometry.groups;
  10001. var materials = material.materials;
  10002. for ( var k = 0, kl = groups.length; k < kl; k ++ ) {
  10003. var group = groups[ k ];
  10004. var groupMaterial = materials[ group.materialIndex ];
  10005. if ( groupMaterial.visible === true ) {
  10006. var depthMaterial = getDepthMaterial( object, groupMaterial, isPointLight, _lightPositionWorld );
  10007. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, group );
  10008. }
  10009. }
  10010. } else {
  10011. var depthMaterial = getDepthMaterial( object, material, isPointLight, _lightPositionWorld );
  10012. _renderer.renderBufferDirect( shadowCamera, null, geometry, depthMaterial, object, null );
  10013. }
  10014. }
  10015. }
  10016. }
  10017. // Restore GL state.
  10018. var clearColor = _renderer.getClearColor(),
  10019. clearAlpha = _renderer.getClearAlpha();
  10020. _renderer.setClearColor( clearColor, clearAlpha );
  10021. scope.needsUpdate = false;
  10022. };
  10023. function getDepthMaterial( object, material, isPointLight, lightPositionWorld ) {
  10024. var geometry = object.geometry;
  10025. var result = null;
  10026. var materialVariants = _depthMaterials;
  10027. var customMaterial = object.customDepthMaterial;
  10028. if ( isPointLight ) {
  10029. materialVariants = _distanceMaterials;
  10030. customMaterial = object.customDistanceMaterial;
  10031. }
  10032. if ( ! customMaterial ) {
  10033. var useMorphing = false;
  10034. if ( material.morphTargets ) {
  10035. if ( geometry && geometry.isBufferGeometry ) {
  10036. useMorphing = geometry.morphAttributes && geometry.morphAttributes.position && geometry.morphAttributes.position.length > 0;
  10037. } else if ( geometry && geometry.isGeometry ) {
  10038. useMorphing = geometry.morphTargets && geometry.morphTargets.length > 0;
  10039. }
  10040. }
  10041. var useSkinning = object.isSkinnedMesh && material.skinning;
  10042. var variantIndex = 0;
  10043. if ( useMorphing ) variantIndex |= _MorphingFlag;
  10044. if ( useSkinning ) variantIndex |= _SkinningFlag;
  10045. result = materialVariants[ variantIndex ];
  10046. } else {
  10047. result = customMaterial;
  10048. }
  10049. if ( _renderer.localClippingEnabled &&
  10050. material.clipShadows === true &&
  10051. material.clippingPlanes.length !== 0 ) {
  10052. // in this case we need a unique material instance reflecting the
  10053. // appropriate state
  10054. var keyA = result.uuid, keyB = material.uuid;
  10055. var materialsForVariant = _materialCache[ keyA ];
  10056. if ( materialsForVariant === undefined ) {
  10057. materialsForVariant = {};
  10058. _materialCache[ keyA ] = materialsForVariant;
  10059. }
  10060. var cachedMaterial = materialsForVariant[ keyB ];
  10061. if ( cachedMaterial === undefined ) {
  10062. cachedMaterial = result.clone();
  10063. materialsForVariant[ keyB ] = cachedMaterial;
  10064. }
  10065. result = cachedMaterial;
  10066. }
  10067. result.visible = material.visible;
  10068. result.wireframe = material.wireframe;
  10069. var side = material.side;
  10070. if ( scope.renderSingleSided && side == DoubleSide ) {
  10071. side = FrontSide;
  10072. }
  10073. if ( scope.renderReverseSided ) {
  10074. if ( side === FrontSide ) side = BackSide;
  10075. else if ( side === BackSide ) side = FrontSide;
  10076. }
  10077. result.side = side;
  10078. result.clipShadows = material.clipShadows;
  10079. result.clippingPlanes = material.clippingPlanes;
  10080. result.wireframeLinewidth = material.wireframeLinewidth;
  10081. result.linewidth = material.linewidth;
  10082. if ( isPointLight && result.uniforms.lightPos !== undefined ) {
  10083. result.uniforms.lightPos.value.copy( lightPositionWorld );
  10084. }
  10085. return result;
  10086. }
  10087. function projectObject( object, camera, shadowCamera ) {
  10088. if ( object.visible === false ) return;
  10089. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  10090. if ( visible && ( object.isMesh || object.isLine || object.isPoints ) ) {
  10091. if ( object.castShadow && ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) ) {
  10092. var material = object.material;
  10093. if ( material.visible === true ) {
  10094. object.modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  10095. _renderList.push( object );
  10096. }
  10097. }
  10098. }
  10099. var children = object.children;
  10100. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10101. projectObject( children[ i ], camera, shadowCamera );
  10102. }
  10103. }
  10104. }
  10105. /**
  10106. * @author bhouston / http://clara.io
  10107. */
  10108. function Ray( origin, direction ) {
  10109. this.origin = ( origin !== undefined ) ? origin : new Vector3();
  10110. this.direction = ( direction !== undefined ) ? direction : new Vector3();
  10111. }
  10112. Ray.prototype = {
  10113. constructor: Ray,
  10114. set: function ( origin, direction ) {
  10115. this.origin.copy( origin );
  10116. this.direction.copy( direction );
  10117. return this;
  10118. },
  10119. clone: function () {
  10120. return new this.constructor().copy( this );
  10121. },
  10122. copy: function ( ray ) {
  10123. this.origin.copy( ray.origin );
  10124. this.direction.copy( ray.direction );
  10125. return this;
  10126. },
  10127. at: function ( t, optionalTarget ) {
  10128. var result = optionalTarget || new Vector3();
  10129. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  10130. },
  10131. lookAt: function ( v ) {
  10132. this.direction.copy( v ).sub( this.origin ).normalize();
  10133. return this;
  10134. },
  10135. recast: function () {
  10136. var v1 = new Vector3();
  10137. return function recast( t ) {
  10138. this.origin.copy( this.at( t, v1 ) );
  10139. return this;
  10140. };
  10141. }(),
  10142. closestPointToPoint: function ( point, optionalTarget ) {
  10143. var result = optionalTarget || new Vector3();
  10144. result.subVectors( point, this.origin );
  10145. var directionDistance = result.dot( this.direction );
  10146. if ( directionDistance < 0 ) {
  10147. return result.copy( this.origin );
  10148. }
  10149. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10150. },
  10151. distanceToPoint: function ( point ) {
  10152. return Math.sqrt( this.distanceSqToPoint( point ) );
  10153. },
  10154. distanceSqToPoint: function () {
  10155. var v1 = new Vector3();
  10156. return function distanceSqToPoint( point ) {
  10157. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  10158. // point behind the ray
  10159. if ( directionDistance < 0 ) {
  10160. return this.origin.distanceToSquared( point );
  10161. }
  10162. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  10163. return v1.distanceToSquared( point );
  10164. };
  10165. }(),
  10166. distanceSqToSegment: function () {
  10167. var segCenter = new Vector3();
  10168. var segDir = new Vector3();
  10169. var diff = new Vector3();
  10170. return function distanceSqToSegment( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  10171. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h
  10172. // It returns the min distance between the ray and the segment
  10173. // defined by v0 and v1
  10174. // It can also set two optional targets :
  10175. // - The closest point on the ray
  10176. // - The closest point on the segment
  10177. segCenter.copy( v0 ).add( v1 ).multiplyScalar( 0.5 );
  10178. segDir.copy( v1 ).sub( v0 ).normalize();
  10179. diff.copy( this.origin ).sub( segCenter );
  10180. var segExtent = v0.distanceTo( v1 ) * 0.5;
  10181. var a01 = - this.direction.dot( segDir );
  10182. var b0 = diff.dot( this.direction );
  10183. var b1 = - diff.dot( segDir );
  10184. var c = diff.lengthSq();
  10185. var det = Math.abs( 1 - a01 * a01 );
  10186. var s0, s1, sqrDist, extDet;
  10187. if ( det > 0 ) {
  10188. // The ray and segment are not parallel.
  10189. s0 = a01 * b1 - b0;
  10190. s1 = a01 * b0 - b1;
  10191. extDet = segExtent * det;
  10192. if ( s0 >= 0 ) {
  10193. if ( s1 >= - extDet ) {
  10194. if ( s1 <= extDet ) {
  10195. // region 0
  10196. // Minimum at interior points of ray and segment.
  10197. var invDet = 1 / det;
  10198. s0 *= invDet;
  10199. s1 *= invDet;
  10200. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  10201. } else {
  10202. // region 1
  10203. s1 = segExtent;
  10204. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10205. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10206. }
  10207. } else {
  10208. // region 5
  10209. s1 = - segExtent;
  10210. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10211. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10212. }
  10213. } else {
  10214. if ( s1 <= - extDet ) {
  10215. // region 4
  10216. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  10217. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10218. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10219. } else if ( s1 <= extDet ) {
  10220. // region 3
  10221. s0 = 0;
  10222. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10223. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  10224. } else {
  10225. // region 2
  10226. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  10227. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  10228. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10229. }
  10230. }
  10231. } else {
  10232. // Ray and segment are parallel.
  10233. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  10234. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  10235. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  10236. }
  10237. if ( optionalPointOnRay ) {
  10238. optionalPointOnRay.copy( this.direction ).multiplyScalar( s0 ).add( this.origin );
  10239. }
  10240. if ( optionalPointOnSegment ) {
  10241. optionalPointOnSegment.copy( segDir ).multiplyScalar( s1 ).add( segCenter );
  10242. }
  10243. return sqrDist;
  10244. };
  10245. }(),
  10246. intersectSphere: function () {
  10247. var v1 = new Vector3();
  10248. return function intersectSphere( sphere, optionalTarget ) {
  10249. v1.subVectors( sphere.center, this.origin );
  10250. var tca = v1.dot( this.direction );
  10251. var d2 = v1.dot( v1 ) - tca * tca;
  10252. var radius2 = sphere.radius * sphere.radius;
  10253. if ( d2 > radius2 ) return null;
  10254. var thc = Math.sqrt( radius2 - d2 );
  10255. // t0 = first intersect point - entrance on front of sphere
  10256. var t0 = tca - thc;
  10257. // t1 = second intersect point - exit point on back of sphere
  10258. var t1 = tca + thc;
  10259. // test to see if both t0 and t1 are behind the ray - if so, return null
  10260. if ( t0 < 0 && t1 < 0 ) return null;
  10261. // test to see if t0 is behind the ray:
  10262. // if it is, the ray is inside the sphere, so return the second exit point scaled by t1,
  10263. // in order to always return an intersect point that is in front of the ray.
  10264. if ( t0 < 0 ) return this.at( t1, optionalTarget );
  10265. // else t0 is in front of the ray, so return the first collision point scaled by t0
  10266. return this.at( t0, optionalTarget );
  10267. };
  10268. }(),
  10269. intersectsSphere: function ( sphere ) {
  10270. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  10271. },
  10272. distanceToPlane: function ( plane ) {
  10273. var denominator = plane.normal.dot( this.direction );
  10274. if ( denominator === 0 ) {
  10275. // line is coplanar, return origin
  10276. if ( plane.distanceToPoint( this.origin ) === 0 ) {
  10277. return 0;
  10278. }
  10279. // Null is preferable to undefined since undefined means.... it is undefined
  10280. return null;
  10281. }
  10282. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  10283. // Return if the ray never intersects the plane
  10284. return t >= 0 ? t : null;
  10285. },
  10286. intersectPlane: function ( plane, optionalTarget ) {
  10287. var t = this.distanceToPlane( plane );
  10288. if ( t === null ) {
  10289. return null;
  10290. }
  10291. return this.at( t, optionalTarget );
  10292. },
  10293. intersectsPlane: function ( plane ) {
  10294. // check if the ray lies on the plane first
  10295. var distToPoint = plane.distanceToPoint( this.origin );
  10296. if ( distToPoint === 0 ) {
  10297. return true;
  10298. }
  10299. var denominator = plane.normal.dot( this.direction );
  10300. if ( denominator * distToPoint < 0 ) {
  10301. return true;
  10302. }
  10303. // ray origin is behind the plane (and is pointing behind it)
  10304. return false;
  10305. },
  10306. intersectBox: function ( box, optionalTarget ) {
  10307. var tmin, tmax, tymin, tymax, tzmin, tzmax;
  10308. var invdirx = 1 / this.direction.x,
  10309. invdiry = 1 / this.direction.y,
  10310. invdirz = 1 / this.direction.z;
  10311. var origin = this.origin;
  10312. if ( invdirx >= 0 ) {
  10313. tmin = ( box.min.x - origin.x ) * invdirx;
  10314. tmax = ( box.max.x - origin.x ) * invdirx;
  10315. } else {
  10316. tmin = ( box.max.x - origin.x ) * invdirx;
  10317. tmax = ( box.min.x - origin.x ) * invdirx;
  10318. }
  10319. if ( invdiry >= 0 ) {
  10320. tymin = ( box.min.y - origin.y ) * invdiry;
  10321. tymax = ( box.max.y - origin.y ) * invdiry;
  10322. } else {
  10323. tymin = ( box.max.y - origin.y ) * invdiry;
  10324. tymax = ( box.min.y - origin.y ) * invdiry;
  10325. }
  10326. if ( ( tmin > tymax ) || ( tymin > tmax ) ) return null;
  10327. // These lines also handle the case where tmin or tmax is NaN
  10328. // (result of 0 * Infinity). x !== x returns true if x is NaN
  10329. if ( tymin > tmin || tmin !== tmin ) tmin = tymin;
  10330. if ( tymax < tmax || tmax !== tmax ) tmax = tymax;
  10331. if ( invdirz >= 0 ) {
  10332. tzmin = ( box.min.z - origin.z ) * invdirz;
  10333. tzmax = ( box.max.z - origin.z ) * invdirz;
  10334. } else {
  10335. tzmin = ( box.max.z - origin.z ) * invdirz;
  10336. tzmax = ( box.min.z - origin.z ) * invdirz;
  10337. }
  10338. if ( ( tmin > tzmax ) || ( tzmin > tmax ) ) return null;
  10339. if ( tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  10340. if ( tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  10341. //return point closest to the ray (positive side)
  10342. if ( tmax < 0 ) return null;
  10343. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  10344. },
  10345. intersectsBox: ( function () {
  10346. var v = new Vector3();
  10347. return function intersectsBox( box ) {
  10348. return this.intersectBox( box, v ) !== null;
  10349. };
  10350. } )(),
  10351. intersectTriangle: function () {
  10352. // Compute the offset origin, edges, and normal.
  10353. var diff = new Vector3();
  10354. var edge1 = new Vector3();
  10355. var edge2 = new Vector3();
  10356. var normal = new Vector3();
  10357. return function intersectTriangle( a, b, c, backfaceCulling, optionalTarget ) {
  10358. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h
  10359. edge1.subVectors( b, a );
  10360. edge2.subVectors( c, a );
  10361. normal.crossVectors( edge1, edge2 );
  10362. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  10363. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  10364. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  10365. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  10366. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  10367. var DdN = this.direction.dot( normal );
  10368. var sign;
  10369. if ( DdN > 0 ) {
  10370. if ( backfaceCulling ) return null;
  10371. sign = 1;
  10372. } else if ( DdN < 0 ) {
  10373. sign = - 1;
  10374. DdN = - DdN;
  10375. } else {
  10376. return null;
  10377. }
  10378. diff.subVectors( this.origin, a );
  10379. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  10380. // b1 < 0, no intersection
  10381. if ( DdQxE2 < 0 ) {
  10382. return null;
  10383. }
  10384. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  10385. // b2 < 0, no intersection
  10386. if ( DdE1xQ < 0 ) {
  10387. return null;
  10388. }
  10389. // b1+b2 > 1, no intersection
  10390. if ( DdQxE2 + DdE1xQ > DdN ) {
  10391. return null;
  10392. }
  10393. // Line intersects triangle, check if ray does.
  10394. var QdN = - sign * diff.dot( normal );
  10395. // t < 0, no intersection
  10396. if ( QdN < 0 ) {
  10397. return null;
  10398. }
  10399. // Ray intersects triangle.
  10400. return this.at( QdN / DdN, optionalTarget );
  10401. };
  10402. }(),
  10403. applyMatrix4: function ( matrix4 ) {
  10404. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  10405. this.origin.applyMatrix4( matrix4 );
  10406. this.direction.sub( this.origin );
  10407. this.direction.normalize();
  10408. return this;
  10409. },
  10410. equals: function ( ray ) {
  10411. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  10412. }
  10413. };
  10414. /**
  10415. * @author mrdoob / http://mrdoob.com/
  10416. * @author WestLangley / http://github.com/WestLangley
  10417. * @author bhouston / http://clara.io
  10418. */
  10419. function Euler( x, y, z, order ) {
  10420. this._x = x || 0;
  10421. this._y = y || 0;
  10422. this._z = z || 0;
  10423. this._order = order || Euler.DefaultOrder;
  10424. }
  10425. Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  10426. Euler.DefaultOrder = 'XYZ';
  10427. Euler.prototype = {
  10428. constructor: Euler,
  10429. isEuler: true,
  10430. get x () {
  10431. return this._x;
  10432. },
  10433. set x ( value ) {
  10434. this._x = value;
  10435. this.onChangeCallback();
  10436. },
  10437. get y () {
  10438. return this._y;
  10439. },
  10440. set y ( value ) {
  10441. this._y = value;
  10442. this.onChangeCallback();
  10443. },
  10444. get z () {
  10445. return this._z;
  10446. },
  10447. set z ( value ) {
  10448. this._z = value;
  10449. this.onChangeCallback();
  10450. },
  10451. get order () {
  10452. return this._order;
  10453. },
  10454. set order ( value ) {
  10455. this._order = value;
  10456. this.onChangeCallback();
  10457. },
  10458. set: function ( x, y, z, order ) {
  10459. this._x = x;
  10460. this._y = y;
  10461. this._z = z;
  10462. this._order = order || this._order;
  10463. this.onChangeCallback();
  10464. return this;
  10465. },
  10466. clone: function () {
  10467. return new this.constructor( this._x, this._y, this._z, this._order );
  10468. },
  10469. copy: function ( euler ) {
  10470. this._x = euler._x;
  10471. this._y = euler._y;
  10472. this._z = euler._z;
  10473. this._order = euler._order;
  10474. this.onChangeCallback();
  10475. return this;
  10476. },
  10477. setFromRotationMatrix: function ( m, order, update ) {
  10478. var clamp = _Math.clamp;
  10479. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10480. var te = m.elements;
  10481. var m11 = te[ 0 ], m12 = te[ 4 ], m13 = te[ 8 ];
  10482. var m21 = te[ 1 ], m22 = te[ 5 ], m23 = te[ 9 ];
  10483. var m31 = te[ 2 ], m32 = te[ 6 ], m33 = te[ 10 ];
  10484. order = order || this._order;
  10485. if ( order === 'XYZ' ) {
  10486. this._y = Math.asin( clamp( m13, - 1, 1 ) );
  10487. if ( Math.abs( m13 ) < 0.99999 ) {
  10488. this._x = Math.atan2( - m23, m33 );
  10489. this._z = Math.atan2( - m12, m11 );
  10490. } else {
  10491. this._x = Math.atan2( m32, m22 );
  10492. this._z = 0;
  10493. }
  10494. } else if ( order === 'YXZ' ) {
  10495. this._x = Math.asin( - clamp( m23, - 1, 1 ) );
  10496. if ( Math.abs( m23 ) < 0.99999 ) {
  10497. this._y = Math.atan2( m13, m33 );
  10498. this._z = Math.atan2( m21, m22 );
  10499. } else {
  10500. this._y = Math.atan2( - m31, m11 );
  10501. this._z = 0;
  10502. }
  10503. } else if ( order === 'ZXY' ) {
  10504. this._x = Math.asin( clamp( m32, - 1, 1 ) );
  10505. if ( Math.abs( m32 ) < 0.99999 ) {
  10506. this._y = Math.atan2( - m31, m33 );
  10507. this._z = Math.atan2( - m12, m22 );
  10508. } else {
  10509. this._y = 0;
  10510. this._z = Math.atan2( m21, m11 );
  10511. }
  10512. } else if ( order === 'ZYX' ) {
  10513. this._y = Math.asin( - clamp( m31, - 1, 1 ) );
  10514. if ( Math.abs( m31 ) < 0.99999 ) {
  10515. this._x = Math.atan2( m32, m33 );
  10516. this._z = Math.atan2( m21, m11 );
  10517. } else {
  10518. this._x = 0;
  10519. this._z = Math.atan2( - m12, m22 );
  10520. }
  10521. } else if ( order === 'YZX' ) {
  10522. this._z = Math.asin( clamp( m21, - 1, 1 ) );
  10523. if ( Math.abs( m21 ) < 0.99999 ) {
  10524. this._x = Math.atan2( - m23, m22 );
  10525. this._y = Math.atan2( - m31, m11 );
  10526. } else {
  10527. this._x = 0;
  10528. this._y = Math.atan2( m13, m33 );
  10529. }
  10530. } else if ( order === 'XZY' ) {
  10531. this._z = Math.asin( - clamp( m12, - 1, 1 ) );
  10532. if ( Math.abs( m12 ) < 0.99999 ) {
  10533. this._x = Math.atan2( m32, m22 );
  10534. this._y = Math.atan2( m13, m11 );
  10535. } else {
  10536. this._x = Math.atan2( - m23, m33 );
  10537. this._y = 0;
  10538. }
  10539. } else {
  10540. console.warn( 'THREE.Euler: .setFromRotationMatrix() given unsupported order: ' + order );
  10541. }
  10542. this._order = order;
  10543. if ( update !== false ) this.onChangeCallback();
  10544. return this;
  10545. },
  10546. setFromQuaternion: function () {
  10547. var matrix;
  10548. return function setFromQuaternion( q, order, update ) {
  10549. if ( matrix === undefined ) matrix = new Matrix4();
  10550. matrix.makeRotationFromQuaternion( q );
  10551. return this.setFromRotationMatrix( matrix, order, update );
  10552. };
  10553. }(),
  10554. setFromVector3: function ( v, order ) {
  10555. return this.set( v.x, v.y, v.z, order || this._order );
  10556. },
  10557. reorder: function () {
  10558. // WARNING: this discards revolution information -bhouston
  10559. var q = new Quaternion();
  10560. return function reorder( newOrder ) {
  10561. q.setFromEuler( this );
  10562. return this.setFromQuaternion( q, newOrder );
  10563. };
  10564. }(),
  10565. equals: function ( euler ) {
  10566. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  10567. },
  10568. fromArray: function ( array ) {
  10569. this._x = array[ 0 ];
  10570. this._y = array[ 1 ];
  10571. this._z = array[ 2 ];
  10572. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  10573. this.onChangeCallback();
  10574. return this;
  10575. },
  10576. toArray: function ( array, offset ) {
  10577. if ( array === undefined ) array = [];
  10578. if ( offset === undefined ) offset = 0;
  10579. array[ offset ] = this._x;
  10580. array[ offset + 1 ] = this._y;
  10581. array[ offset + 2 ] = this._z;
  10582. array[ offset + 3 ] = this._order;
  10583. return array;
  10584. },
  10585. toVector3: function ( optionalResult ) {
  10586. if ( optionalResult ) {
  10587. return optionalResult.set( this._x, this._y, this._z );
  10588. } else {
  10589. return new Vector3( this._x, this._y, this._z );
  10590. }
  10591. },
  10592. onChange: function ( callback ) {
  10593. this.onChangeCallback = callback;
  10594. return this;
  10595. },
  10596. onChangeCallback: function () {}
  10597. };
  10598. /**
  10599. * @author mrdoob / http://mrdoob.com/
  10600. */
  10601. function Layers() {
  10602. this.mask = 1;
  10603. }
  10604. Layers.prototype = {
  10605. constructor: Layers,
  10606. set: function ( channel ) {
  10607. this.mask = 1 << channel;
  10608. },
  10609. enable: function ( channel ) {
  10610. this.mask |= 1 << channel;
  10611. },
  10612. toggle: function ( channel ) {
  10613. this.mask ^= 1 << channel;
  10614. },
  10615. disable: function ( channel ) {
  10616. this.mask &= ~ ( 1 << channel );
  10617. },
  10618. test: function ( layers ) {
  10619. return ( this.mask & layers.mask ) !== 0;
  10620. }
  10621. };
  10622. /**
  10623. * @author mrdoob / http://mrdoob.com/
  10624. * @author mikael emtinger / http://gomo.se/
  10625. * @author alteredq / http://alteredqualia.com/
  10626. * @author WestLangley / http://github.com/WestLangley
  10627. * @author elephantatwork / www.elephantatwork.ch
  10628. */
  10629. var object3DId = 0;
  10630. function Object3D() {
  10631. Object.defineProperty( this, 'id', { value: object3DId ++ } );
  10632. this.uuid = _Math.generateUUID();
  10633. this.name = '';
  10634. this.type = 'Object3D';
  10635. this.parent = null;
  10636. this.children = [];
  10637. this.up = Object3D.DefaultUp.clone();
  10638. var position = new Vector3();
  10639. var rotation = new Euler();
  10640. var quaternion = new Quaternion();
  10641. var scale = new Vector3( 1, 1, 1 );
  10642. function onRotationChange() {
  10643. quaternion.setFromEuler( rotation, false );
  10644. }
  10645. function onQuaternionChange() {
  10646. rotation.setFromQuaternion( quaternion, undefined, false );
  10647. }
  10648. rotation.onChange( onRotationChange );
  10649. quaternion.onChange( onQuaternionChange );
  10650. Object.defineProperties( this, {
  10651. position: {
  10652. enumerable: true,
  10653. value: position
  10654. },
  10655. rotation: {
  10656. enumerable: true,
  10657. value: rotation
  10658. },
  10659. quaternion: {
  10660. enumerable: true,
  10661. value: quaternion
  10662. },
  10663. scale: {
  10664. enumerable: true,
  10665. value: scale
  10666. },
  10667. modelViewMatrix: {
  10668. value: new Matrix4()
  10669. },
  10670. normalMatrix: {
  10671. value: new Matrix3()
  10672. }
  10673. } );
  10674. this.matrix = new Matrix4();
  10675. this.matrixWorld = new Matrix4();
  10676. this.matrixAutoUpdate = Object3D.DefaultMatrixAutoUpdate;
  10677. this.matrixWorldNeedsUpdate = false;
  10678. this.layers = new Layers();
  10679. this.visible = true;
  10680. this.castShadow = false;
  10681. this.receiveShadow = false;
  10682. this.frustumCulled = true;
  10683. this.renderOrder = 0;
  10684. this.userData = {};
  10685. this.onBeforeRender = function () {};
  10686. this.onAfterRender = function () {};
  10687. }
  10688. Object3D.DefaultUp = new Vector3( 0, 1, 0 );
  10689. Object3D.DefaultMatrixAutoUpdate = true;
  10690. Object.assign( Object3D.prototype, EventDispatcher.prototype, {
  10691. isObject3D: true,
  10692. applyMatrix: function ( matrix ) {
  10693. this.matrix.multiplyMatrices( matrix, this.matrix );
  10694. this.matrix.decompose( this.position, this.quaternion, this.scale );
  10695. },
  10696. setRotationFromAxisAngle: function ( axis, angle ) {
  10697. // assumes axis is normalized
  10698. this.quaternion.setFromAxisAngle( axis, angle );
  10699. },
  10700. setRotationFromEuler: function ( euler ) {
  10701. this.quaternion.setFromEuler( euler, true );
  10702. },
  10703. setRotationFromMatrix: function ( m ) {
  10704. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  10705. this.quaternion.setFromRotationMatrix( m );
  10706. },
  10707. setRotationFromQuaternion: function ( q ) {
  10708. // assumes q is normalized
  10709. this.quaternion.copy( q );
  10710. },
  10711. rotateOnAxis: function () {
  10712. // rotate object on axis in object space
  10713. // axis is assumed to be normalized
  10714. var q1 = new Quaternion();
  10715. return function rotateOnAxis( axis, angle ) {
  10716. q1.setFromAxisAngle( axis, angle );
  10717. this.quaternion.multiply( q1 );
  10718. return this;
  10719. };
  10720. }(),
  10721. rotateX: function () {
  10722. var v1 = new Vector3( 1, 0, 0 );
  10723. return function rotateX( angle ) {
  10724. return this.rotateOnAxis( v1, angle );
  10725. };
  10726. }(),
  10727. rotateY: function () {
  10728. var v1 = new Vector3( 0, 1, 0 );
  10729. return function rotateY( angle ) {
  10730. return this.rotateOnAxis( v1, angle );
  10731. };
  10732. }(),
  10733. rotateZ: function () {
  10734. var v1 = new Vector3( 0, 0, 1 );
  10735. return function rotateZ( angle ) {
  10736. return this.rotateOnAxis( v1, angle );
  10737. };
  10738. }(),
  10739. translateOnAxis: function () {
  10740. // translate object by distance along axis in object space
  10741. // axis is assumed to be normalized
  10742. var v1 = new Vector3();
  10743. return function translateOnAxis( axis, distance ) {
  10744. v1.copy( axis ).applyQuaternion( this.quaternion );
  10745. this.position.add( v1.multiplyScalar( distance ) );
  10746. return this;
  10747. };
  10748. }(),
  10749. translateX: function () {
  10750. var v1 = new Vector3( 1, 0, 0 );
  10751. return function translateX( distance ) {
  10752. return this.translateOnAxis( v1, distance );
  10753. };
  10754. }(),
  10755. translateY: function () {
  10756. var v1 = new Vector3( 0, 1, 0 );
  10757. return function translateY( distance ) {
  10758. return this.translateOnAxis( v1, distance );
  10759. };
  10760. }(),
  10761. translateZ: function () {
  10762. var v1 = new Vector3( 0, 0, 1 );
  10763. return function translateZ( distance ) {
  10764. return this.translateOnAxis( v1, distance );
  10765. };
  10766. }(),
  10767. localToWorld: function ( vector ) {
  10768. return vector.applyMatrix4( this.matrixWorld );
  10769. },
  10770. worldToLocal: function () {
  10771. var m1 = new Matrix4();
  10772. return function worldToLocal( vector ) {
  10773. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  10774. };
  10775. }(),
  10776. lookAt: function () {
  10777. // This routine does not support objects with rotated and/or translated parent(s)
  10778. var m1 = new Matrix4();
  10779. return function lookAt( vector ) {
  10780. m1.lookAt( vector, this.position, this.up );
  10781. this.quaternion.setFromRotationMatrix( m1 );
  10782. };
  10783. }(),
  10784. add: function ( object ) {
  10785. if ( arguments.length > 1 ) {
  10786. for ( var i = 0; i < arguments.length; i ++ ) {
  10787. this.add( arguments[ i ] );
  10788. }
  10789. return this;
  10790. }
  10791. if ( object === this ) {
  10792. console.error( "THREE.Object3D.add: object can't be added as a child of itself.", object );
  10793. return this;
  10794. }
  10795. if ( ( object && object.isObject3D ) ) {
  10796. if ( object.parent !== null ) {
  10797. object.parent.remove( object );
  10798. }
  10799. object.parent = this;
  10800. object.dispatchEvent( { type: 'added' } );
  10801. this.children.push( object );
  10802. } else {
  10803. console.error( "THREE.Object3D.add: object not an instance of THREE.Object3D.", object );
  10804. }
  10805. return this;
  10806. },
  10807. remove: function ( object ) {
  10808. if ( arguments.length > 1 ) {
  10809. for ( var i = 0; i < arguments.length; i ++ ) {
  10810. this.remove( arguments[ i ] );
  10811. }
  10812. }
  10813. var index = this.children.indexOf( object );
  10814. if ( index !== - 1 ) {
  10815. object.parent = null;
  10816. object.dispatchEvent( { type: 'removed' } );
  10817. this.children.splice( index, 1 );
  10818. }
  10819. },
  10820. getObjectById: function ( id ) {
  10821. return this.getObjectByProperty( 'id', id );
  10822. },
  10823. getObjectByName: function ( name ) {
  10824. return this.getObjectByProperty( 'name', name );
  10825. },
  10826. getObjectByProperty: function ( name, value ) {
  10827. if ( this[ name ] === value ) return this;
  10828. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  10829. var child = this.children[ i ];
  10830. var object = child.getObjectByProperty( name, value );
  10831. if ( object !== undefined ) {
  10832. return object;
  10833. }
  10834. }
  10835. return undefined;
  10836. },
  10837. getWorldPosition: function ( optionalTarget ) {
  10838. var result = optionalTarget || new Vector3();
  10839. this.updateMatrixWorld( true );
  10840. return result.setFromMatrixPosition( this.matrixWorld );
  10841. },
  10842. getWorldQuaternion: function () {
  10843. var position = new Vector3();
  10844. var scale = new Vector3();
  10845. return function getWorldQuaternion( optionalTarget ) {
  10846. var result = optionalTarget || new Quaternion();
  10847. this.updateMatrixWorld( true );
  10848. this.matrixWorld.decompose( position, result, scale );
  10849. return result;
  10850. };
  10851. }(),
  10852. getWorldRotation: function () {
  10853. var quaternion = new Quaternion();
  10854. return function getWorldRotation( optionalTarget ) {
  10855. var result = optionalTarget || new Euler();
  10856. this.getWorldQuaternion( quaternion );
  10857. return result.setFromQuaternion( quaternion, this.rotation.order, false );
  10858. };
  10859. }(),
  10860. getWorldScale: function () {
  10861. var position = new Vector3();
  10862. var quaternion = new Quaternion();
  10863. return function getWorldScale( optionalTarget ) {
  10864. var result = optionalTarget || new Vector3();
  10865. this.updateMatrixWorld( true );
  10866. this.matrixWorld.decompose( position, quaternion, result );
  10867. return result;
  10868. };
  10869. }(),
  10870. getWorldDirection: function () {
  10871. var quaternion = new Quaternion();
  10872. return function getWorldDirection( optionalTarget ) {
  10873. var result = optionalTarget || new Vector3();
  10874. this.getWorldQuaternion( quaternion );
  10875. return result.set( 0, 0, 1 ).applyQuaternion( quaternion );
  10876. };
  10877. }(),
  10878. raycast: function () {},
  10879. traverse: function ( callback ) {
  10880. callback( this );
  10881. var children = this.children;
  10882. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10883. children[ i ].traverse( callback );
  10884. }
  10885. },
  10886. traverseVisible: function ( callback ) {
  10887. if ( this.visible === false ) return;
  10888. callback( this );
  10889. var children = this.children;
  10890. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10891. children[ i ].traverseVisible( callback );
  10892. }
  10893. },
  10894. traverseAncestors: function ( callback ) {
  10895. var parent = this.parent;
  10896. if ( parent !== null ) {
  10897. callback( parent );
  10898. parent.traverseAncestors( callback );
  10899. }
  10900. },
  10901. updateMatrix: function () {
  10902. this.matrix.compose( this.position, this.quaternion, this.scale );
  10903. this.matrixWorldNeedsUpdate = true;
  10904. },
  10905. updateMatrixWorld: function ( force ) {
  10906. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  10907. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  10908. if ( this.parent === null ) {
  10909. this.matrixWorld.copy( this.matrix );
  10910. } else {
  10911. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  10912. }
  10913. this.matrixWorldNeedsUpdate = false;
  10914. force = true;
  10915. }
  10916. // update children
  10917. var children = this.children;
  10918. for ( var i = 0, l = children.length; i < l; i ++ ) {
  10919. children[ i ].updateMatrixWorld( force );
  10920. }
  10921. },
  10922. toJSON: function ( meta ) {
  10923. // meta is '' when called from JSON.stringify
  10924. var isRootObject = ( meta === undefined || meta === '' );
  10925. var output = {};
  10926. // meta is a hash used to collect geometries, materials.
  10927. // not providing it implies that this is the root object
  10928. // being serialized.
  10929. if ( isRootObject ) {
  10930. // initialize meta obj
  10931. meta = {
  10932. geometries: {},
  10933. materials: {},
  10934. textures: {},
  10935. images: {}
  10936. };
  10937. output.metadata = {
  10938. version: 4.4,
  10939. type: 'Object',
  10940. generator: 'Object3D.toJSON'
  10941. };
  10942. }
  10943. // standard Object3D serialization
  10944. var object = {};
  10945. object.uuid = this.uuid;
  10946. object.type = this.type;
  10947. if ( this.name !== '' ) object.name = this.name;
  10948. if ( JSON.stringify( this.userData ) !== '{}' ) object.userData = this.userData;
  10949. if ( this.castShadow === true ) object.castShadow = true;
  10950. if ( this.receiveShadow === true ) object.receiveShadow = true;
  10951. if ( this.visible === false ) object.visible = false;
  10952. object.matrix = this.matrix.toArray();
  10953. //
  10954. if ( this.geometry !== undefined ) {
  10955. if ( meta.geometries[ this.geometry.uuid ] === undefined ) {
  10956. meta.geometries[ this.geometry.uuid ] = this.geometry.toJSON( meta );
  10957. }
  10958. object.geometry = this.geometry.uuid;
  10959. }
  10960. if ( this.material !== undefined ) {
  10961. if ( meta.materials[ this.material.uuid ] === undefined ) {
  10962. meta.materials[ this.material.uuid ] = this.material.toJSON( meta );
  10963. }
  10964. object.material = this.material.uuid;
  10965. }
  10966. //
  10967. if ( this.children.length > 0 ) {
  10968. object.children = [];
  10969. for ( var i = 0; i < this.children.length; i ++ ) {
  10970. object.children.push( this.children[ i ].toJSON( meta ).object );
  10971. }
  10972. }
  10973. if ( isRootObject ) {
  10974. var geometries = extractFromCache( meta.geometries );
  10975. var materials = extractFromCache( meta.materials );
  10976. var textures = extractFromCache( meta.textures );
  10977. var images = extractFromCache( meta.images );
  10978. if ( geometries.length > 0 ) output.geometries = geometries;
  10979. if ( materials.length > 0 ) output.materials = materials;
  10980. if ( textures.length > 0 ) output.textures = textures;
  10981. if ( images.length > 0 ) output.images = images;
  10982. }
  10983. output.object = object;
  10984. return output;
  10985. // extract data from the cache hash
  10986. // remove metadata on each item
  10987. // and return as array
  10988. function extractFromCache( cache ) {
  10989. var values = [];
  10990. for ( var key in cache ) {
  10991. var data = cache[ key ];
  10992. delete data.metadata;
  10993. values.push( data );
  10994. }
  10995. return values;
  10996. }
  10997. },
  10998. clone: function ( recursive ) {
  10999. return new this.constructor().copy( this, recursive );
  11000. },
  11001. copy: function ( source, recursive ) {
  11002. if ( recursive === undefined ) recursive = true;
  11003. this.name = source.name;
  11004. this.up.copy( source.up );
  11005. this.position.copy( source.position );
  11006. this.quaternion.copy( source.quaternion );
  11007. this.scale.copy( source.scale );
  11008. this.matrix.copy( source.matrix );
  11009. this.matrixWorld.copy( source.matrixWorld );
  11010. this.matrixAutoUpdate = source.matrixAutoUpdate;
  11011. this.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  11012. this.layers.mask = source.layers.mask;
  11013. this.visible = source.visible;
  11014. this.castShadow = source.castShadow;
  11015. this.receiveShadow = source.receiveShadow;
  11016. this.frustumCulled = source.frustumCulled;
  11017. this.renderOrder = source.renderOrder;
  11018. this.userData = JSON.parse( JSON.stringify( source.userData ) );
  11019. if ( recursive === true ) {
  11020. for ( var i = 0; i < source.children.length; i ++ ) {
  11021. var child = source.children[ i ];
  11022. this.add( child.clone() );
  11023. }
  11024. }
  11025. return this;
  11026. }
  11027. } );
  11028. /**
  11029. * @author bhouston / http://clara.io
  11030. */
  11031. function Line3( start, end ) {
  11032. this.start = ( start !== undefined ) ? start : new Vector3();
  11033. this.end = ( end !== undefined ) ? end : new Vector3();
  11034. }
  11035. Line3.prototype = {
  11036. constructor: Line3,
  11037. set: function ( start, end ) {
  11038. this.start.copy( start );
  11039. this.end.copy( end );
  11040. return this;
  11041. },
  11042. clone: function () {
  11043. return new this.constructor().copy( this );
  11044. },
  11045. copy: function ( line ) {
  11046. this.start.copy( line.start );
  11047. this.end.copy( line.end );
  11048. return this;
  11049. },
  11050. getCenter: function ( optionalTarget ) {
  11051. var result = optionalTarget || new Vector3();
  11052. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  11053. },
  11054. delta: function ( optionalTarget ) {
  11055. var result = optionalTarget || new Vector3();
  11056. return result.subVectors( this.end, this.start );
  11057. },
  11058. distanceSq: function () {
  11059. return this.start.distanceToSquared( this.end );
  11060. },
  11061. distance: function () {
  11062. return this.start.distanceTo( this.end );
  11063. },
  11064. at: function ( t, optionalTarget ) {
  11065. var result = optionalTarget || new Vector3();
  11066. return this.delta( result ).multiplyScalar( t ).add( this.start );
  11067. },
  11068. closestPointToPointParameter: function () {
  11069. var startP = new Vector3();
  11070. var startEnd = new Vector3();
  11071. return function closestPointToPointParameter( point, clampToLine ) {
  11072. startP.subVectors( point, this.start );
  11073. startEnd.subVectors( this.end, this.start );
  11074. var startEnd2 = startEnd.dot( startEnd );
  11075. var startEnd_startP = startEnd.dot( startP );
  11076. var t = startEnd_startP / startEnd2;
  11077. if ( clampToLine ) {
  11078. t = _Math.clamp( t, 0, 1 );
  11079. }
  11080. return t;
  11081. };
  11082. }(),
  11083. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  11084. var t = this.closestPointToPointParameter( point, clampToLine );
  11085. var result = optionalTarget || new Vector3();
  11086. return this.delta( result ).multiplyScalar( t ).add( this.start );
  11087. },
  11088. applyMatrix4: function ( matrix ) {
  11089. this.start.applyMatrix4( matrix );
  11090. this.end.applyMatrix4( matrix );
  11091. return this;
  11092. },
  11093. equals: function ( line ) {
  11094. return line.start.equals( this.start ) && line.end.equals( this.end );
  11095. }
  11096. };
  11097. /**
  11098. * @author bhouston / http://clara.io
  11099. * @author mrdoob / http://mrdoob.com/
  11100. */
  11101. function Triangle( a, b, c ) {
  11102. this.a = ( a !== undefined ) ? a : new Vector3();
  11103. this.b = ( b !== undefined ) ? b : new Vector3();
  11104. this.c = ( c !== undefined ) ? c : new Vector3();
  11105. }
  11106. Triangle.normal = function () {
  11107. var v0 = new Vector3();
  11108. return function normal( a, b, c, optionalTarget ) {
  11109. var result = optionalTarget || new Vector3();
  11110. result.subVectors( c, b );
  11111. v0.subVectors( a, b );
  11112. result.cross( v0 );
  11113. var resultLengthSq = result.lengthSq();
  11114. if ( resultLengthSq > 0 ) {
  11115. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  11116. }
  11117. return result.set( 0, 0, 0 );
  11118. };
  11119. }();
  11120. // static/instance method to calculate barycentric coordinates
  11121. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  11122. Triangle.barycoordFromPoint = function () {
  11123. var v0 = new Vector3();
  11124. var v1 = new Vector3();
  11125. var v2 = new Vector3();
  11126. return function barycoordFromPoint( point, a, b, c, optionalTarget ) {
  11127. v0.subVectors( c, a );
  11128. v1.subVectors( b, a );
  11129. v2.subVectors( point, a );
  11130. var dot00 = v0.dot( v0 );
  11131. var dot01 = v0.dot( v1 );
  11132. var dot02 = v0.dot( v2 );
  11133. var dot11 = v1.dot( v1 );
  11134. var dot12 = v1.dot( v2 );
  11135. var denom = ( dot00 * dot11 - dot01 * dot01 );
  11136. var result = optionalTarget || new Vector3();
  11137. // collinear or singular triangle
  11138. if ( denom === 0 ) {
  11139. // arbitrary location outside of triangle?
  11140. // not sure if this is the best idea, maybe should be returning undefined
  11141. return result.set( - 2, - 1, - 1 );
  11142. }
  11143. var invDenom = 1 / denom;
  11144. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  11145. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  11146. // barycentric coordinates must always sum to 1
  11147. return result.set( 1 - u - v, v, u );
  11148. };
  11149. }();
  11150. Triangle.containsPoint = function () {
  11151. var v1 = new Vector3();
  11152. return function containsPoint( point, a, b, c ) {
  11153. var result = Triangle.barycoordFromPoint( point, a, b, c, v1 );
  11154. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  11155. };
  11156. }();
  11157. Triangle.prototype = {
  11158. constructor: Triangle,
  11159. set: function ( a, b, c ) {
  11160. this.a.copy( a );
  11161. this.b.copy( b );
  11162. this.c.copy( c );
  11163. return this;
  11164. },
  11165. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  11166. this.a.copy( points[ i0 ] );
  11167. this.b.copy( points[ i1 ] );
  11168. this.c.copy( points[ i2 ] );
  11169. return this;
  11170. },
  11171. clone: function () {
  11172. return new this.constructor().copy( this );
  11173. },
  11174. copy: function ( triangle ) {
  11175. this.a.copy( triangle.a );
  11176. this.b.copy( triangle.b );
  11177. this.c.copy( triangle.c );
  11178. return this;
  11179. },
  11180. area: function () {
  11181. var v0 = new Vector3();
  11182. var v1 = new Vector3();
  11183. return function area() {
  11184. v0.subVectors( this.c, this.b );
  11185. v1.subVectors( this.a, this.b );
  11186. return v0.cross( v1 ).length() * 0.5;
  11187. };
  11188. }(),
  11189. midpoint: function ( optionalTarget ) {
  11190. var result = optionalTarget || new Vector3();
  11191. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  11192. },
  11193. normal: function ( optionalTarget ) {
  11194. return Triangle.normal( this.a, this.b, this.c, optionalTarget );
  11195. },
  11196. plane: function ( optionalTarget ) {
  11197. var result = optionalTarget || new Plane();
  11198. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  11199. },
  11200. barycoordFromPoint: function ( point, optionalTarget ) {
  11201. return Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  11202. },
  11203. containsPoint: function ( point ) {
  11204. return Triangle.containsPoint( point, this.a, this.b, this.c );
  11205. },
  11206. closestPointToPoint: function () {
  11207. var plane, edgeList, projectedPoint, closestPoint;
  11208. return function closestPointToPoint( point, optionalTarget ) {
  11209. if ( plane === undefined ) {
  11210. plane = new Plane();
  11211. edgeList = [ new Line3(), new Line3(), new Line3() ];
  11212. projectedPoint = new Vector3();
  11213. closestPoint = new Vector3();
  11214. }
  11215. var result = optionalTarget || new Vector3();
  11216. var minDistance = Infinity;
  11217. // project the point onto the plane of the triangle
  11218. plane.setFromCoplanarPoints( this.a, this.b, this.c );
  11219. plane.projectPoint( point, projectedPoint );
  11220. // check if the projection lies within the triangle
  11221. if( this.containsPoint( projectedPoint ) === true ) {
  11222. // if so, this is the closest point
  11223. result.copy( projectedPoint );
  11224. } else {
  11225. // if not, the point falls outside the triangle. the result is the closest point to the triangle's edges or vertices
  11226. edgeList[ 0 ].set( this.a, this.b );
  11227. edgeList[ 1 ].set( this.b, this.c );
  11228. edgeList[ 2 ].set( this.c, this.a );
  11229. for( var i = 0; i < edgeList.length; i ++ ) {
  11230. edgeList[ i ].closestPointToPoint( projectedPoint, true, closestPoint );
  11231. var distance = projectedPoint.distanceToSquared( closestPoint );
  11232. if( distance < minDistance ) {
  11233. minDistance = distance;
  11234. result.copy( closestPoint );
  11235. }
  11236. }
  11237. }
  11238. return result;
  11239. };
  11240. }(),
  11241. equals: function ( triangle ) {
  11242. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  11243. }
  11244. };
  11245. /**
  11246. * @author mrdoob / http://mrdoob.com/
  11247. * @author alteredq / http://alteredqualia.com/
  11248. */
  11249. function Face3( a, b, c, normal, color, materialIndex ) {
  11250. this.a = a;
  11251. this.b = b;
  11252. this.c = c;
  11253. this.normal = (normal && normal.isVector3) ? normal : new Vector3();
  11254. this.vertexNormals = Array.isArray( normal ) ? normal : [];
  11255. this.color = (color && color.isColor) ? color : new Color();
  11256. this.vertexColors = Array.isArray( color ) ? color : [];
  11257. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  11258. }
  11259. Face3.prototype = {
  11260. constructor: Face3,
  11261. clone: function () {
  11262. return new this.constructor().copy( this );
  11263. },
  11264. copy: function ( source ) {
  11265. this.a = source.a;
  11266. this.b = source.b;
  11267. this.c = source.c;
  11268. this.normal.copy( source.normal );
  11269. this.color.copy( source.color );
  11270. this.materialIndex = source.materialIndex;
  11271. for ( var i = 0, il = source.vertexNormals.length; i < il; i ++ ) {
  11272. this.vertexNormals[ i ] = source.vertexNormals[ i ].clone();
  11273. }
  11274. for ( var i = 0, il = source.vertexColors.length; i < il; i ++ ) {
  11275. this.vertexColors[ i ] = source.vertexColors[ i ].clone();
  11276. }
  11277. return this;
  11278. }
  11279. };
  11280. /**
  11281. * @author mrdoob / http://mrdoob.com/
  11282. * @author alteredq / http://alteredqualia.com/
  11283. *
  11284. * parameters = {
  11285. * color: <hex>,
  11286. * opacity: <float>,
  11287. * map: new THREE.Texture( <Image> ),
  11288. *
  11289. * lightMap: new THREE.Texture( <Image> ),
  11290. * lightMapIntensity: <float>
  11291. *
  11292. * aoMap: new THREE.Texture( <Image> ),
  11293. * aoMapIntensity: <float>
  11294. *
  11295. * specularMap: new THREE.Texture( <Image> ),
  11296. *
  11297. * alphaMap: new THREE.Texture( <Image> ),
  11298. *
  11299. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  11300. * combine: THREE.Multiply,
  11301. * reflectivity: <float>,
  11302. * refractionRatio: <float>,
  11303. *
  11304. * shading: THREE.SmoothShading,
  11305. * depthTest: <bool>,
  11306. * depthWrite: <bool>,
  11307. *
  11308. * wireframe: <boolean>,
  11309. * wireframeLinewidth: <float>,
  11310. *
  11311. * skinning: <bool>,
  11312. * morphTargets: <bool>
  11313. * }
  11314. */
  11315. function MeshBasicMaterial( parameters ) {
  11316. Material.call( this );
  11317. this.type = 'MeshBasicMaterial';
  11318. this.color = new Color( 0xffffff ); // emissive
  11319. this.map = null;
  11320. this.lightMap = null;
  11321. this.lightMapIntensity = 1.0;
  11322. this.aoMap = null;
  11323. this.aoMapIntensity = 1.0;
  11324. this.specularMap = null;
  11325. this.alphaMap = null;
  11326. this.envMap = null;
  11327. this.combine = MultiplyOperation;
  11328. this.reflectivity = 1;
  11329. this.refractionRatio = 0.98;
  11330. this.wireframe = false;
  11331. this.wireframeLinewidth = 1;
  11332. this.wireframeLinecap = 'round';
  11333. this.wireframeLinejoin = 'round';
  11334. this.skinning = false;
  11335. this.morphTargets = false;
  11336. this.lights = false;
  11337. this.setValues( parameters );
  11338. }
  11339. MeshBasicMaterial.prototype = Object.create( Material.prototype );
  11340. MeshBasicMaterial.prototype.constructor = MeshBasicMaterial;
  11341. MeshBasicMaterial.prototype.isMeshBasicMaterial = true;
  11342. MeshBasicMaterial.prototype.copy = function ( source ) {
  11343. Material.prototype.copy.call( this, source );
  11344. this.color.copy( source.color );
  11345. this.map = source.map;
  11346. this.lightMap = source.lightMap;
  11347. this.lightMapIntensity = source.lightMapIntensity;
  11348. this.aoMap = source.aoMap;
  11349. this.aoMapIntensity = source.aoMapIntensity;
  11350. this.specularMap = source.specularMap;
  11351. this.alphaMap = source.alphaMap;
  11352. this.envMap = source.envMap;
  11353. this.combine = source.combine;
  11354. this.reflectivity = source.reflectivity;
  11355. this.refractionRatio = source.refractionRatio;
  11356. this.wireframe = source.wireframe;
  11357. this.wireframeLinewidth = source.wireframeLinewidth;
  11358. this.wireframeLinecap = source.wireframeLinecap;
  11359. this.wireframeLinejoin = source.wireframeLinejoin;
  11360. this.skinning = source.skinning;
  11361. this.morphTargets = source.morphTargets;
  11362. return this;
  11363. };
  11364. /**
  11365. * @author mrdoob / http://mrdoob.com/
  11366. */
  11367. function BufferAttribute( array, itemSize, normalized ) {
  11368. if ( Array.isArray( array ) ) {
  11369. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11370. }
  11371. this.uuid = _Math.generateUUID();
  11372. this.array = array;
  11373. this.itemSize = itemSize;
  11374. this.count = array !== undefined ? array.length / itemSize : 0;
  11375. this.normalized = normalized === true;
  11376. this.dynamic = false;
  11377. this.updateRange = { offset: 0, count: - 1 };
  11378. this.onUploadCallback = function () {};
  11379. this.version = 0;
  11380. }
  11381. BufferAttribute.prototype = {
  11382. constructor: BufferAttribute,
  11383. isBufferAttribute: true,
  11384. set needsUpdate( value ) {
  11385. if ( value === true ) this.version ++;
  11386. },
  11387. setArray: function ( array ) {
  11388. if ( Array.isArray( array ) ) {
  11389. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  11390. }
  11391. this.count = array !== undefined ? array.length / this.itemSize : 0;
  11392. this.array = array;
  11393. },
  11394. setDynamic: function ( value ) {
  11395. this.dynamic = value;
  11396. return this;
  11397. },
  11398. copy: function ( source ) {
  11399. this.array = new source.array.constructor( source.array );
  11400. this.itemSize = source.itemSize;
  11401. this.count = source.count;
  11402. this.normalized = source.normalized;
  11403. this.dynamic = source.dynamic;
  11404. return this;
  11405. },
  11406. copyAt: function ( index1, attribute, index2 ) {
  11407. index1 *= this.itemSize;
  11408. index2 *= attribute.itemSize;
  11409. for ( var i = 0, l = this.itemSize; i < l; i ++ ) {
  11410. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  11411. }
  11412. return this;
  11413. },
  11414. copyArray: function ( array ) {
  11415. this.array.set( array );
  11416. return this;
  11417. },
  11418. copyColorsArray: function ( colors ) {
  11419. var array = this.array, offset = 0;
  11420. for ( var i = 0, l = colors.length; i < l; i ++ ) {
  11421. var color = colors[ i ];
  11422. if ( color === undefined ) {
  11423. console.warn( 'THREE.BufferAttribute.copyColorsArray(): color is undefined', i );
  11424. color = new Color();
  11425. }
  11426. array[ offset ++ ] = color.r;
  11427. array[ offset ++ ] = color.g;
  11428. array[ offset ++ ] = color.b;
  11429. }
  11430. return this;
  11431. },
  11432. copyIndicesArray: function ( indices ) {
  11433. var array = this.array, offset = 0;
  11434. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  11435. var index = indices[ i ];
  11436. array[ offset ++ ] = index.a;
  11437. array[ offset ++ ] = index.b;
  11438. array[ offset ++ ] = index.c;
  11439. }
  11440. return this;
  11441. },
  11442. copyVector2sArray: function ( vectors ) {
  11443. var array = this.array, offset = 0;
  11444. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11445. var vector = vectors[ i ];
  11446. if ( vector === undefined ) {
  11447. console.warn( 'THREE.BufferAttribute.copyVector2sArray(): vector is undefined', i );
  11448. vector = new Vector2();
  11449. }
  11450. array[ offset ++ ] = vector.x;
  11451. array[ offset ++ ] = vector.y;
  11452. }
  11453. return this;
  11454. },
  11455. copyVector3sArray: function ( vectors ) {
  11456. var array = this.array, offset = 0;
  11457. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11458. var vector = vectors[ i ];
  11459. if ( vector === undefined ) {
  11460. console.warn( 'THREE.BufferAttribute.copyVector3sArray(): vector is undefined', i );
  11461. vector = new Vector3();
  11462. }
  11463. array[ offset ++ ] = vector.x;
  11464. array[ offset ++ ] = vector.y;
  11465. array[ offset ++ ] = vector.z;
  11466. }
  11467. return this;
  11468. },
  11469. copyVector4sArray: function ( vectors ) {
  11470. var array = this.array, offset = 0;
  11471. for ( var i = 0, l = vectors.length; i < l; i ++ ) {
  11472. var vector = vectors[ i ];
  11473. if ( vector === undefined ) {
  11474. console.warn( 'THREE.BufferAttribute.copyVector4sArray(): vector is undefined', i );
  11475. vector = new Vector4();
  11476. }
  11477. array[ offset ++ ] = vector.x;
  11478. array[ offset ++ ] = vector.y;
  11479. array[ offset ++ ] = vector.z;
  11480. array[ offset ++ ] = vector.w;
  11481. }
  11482. return this;
  11483. },
  11484. set: function ( value, offset ) {
  11485. if ( offset === undefined ) offset = 0;
  11486. this.array.set( value, offset );
  11487. return this;
  11488. },
  11489. getX: function ( index ) {
  11490. return this.array[ index * this.itemSize ];
  11491. },
  11492. setX: function ( index, x ) {
  11493. this.array[ index * this.itemSize ] = x;
  11494. return this;
  11495. },
  11496. getY: function ( index ) {
  11497. return this.array[ index * this.itemSize + 1 ];
  11498. },
  11499. setY: function ( index, y ) {
  11500. this.array[ index * this.itemSize + 1 ] = y;
  11501. return this;
  11502. },
  11503. getZ: function ( index ) {
  11504. return this.array[ index * this.itemSize + 2 ];
  11505. },
  11506. setZ: function ( index, z ) {
  11507. this.array[ index * this.itemSize + 2 ] = z;
  11508. return this;
  11509. },
  11510. getW: function ( index ) {
  11511. return this.array[ index * this.itemSize + 3 ];
  11512. },
  11513. setW: function ( index, w ) {
  11514. this.array[ index * this.itemSize + 3 ] = w;
  11515. return this;
  11516. },
  11517. setXY: function ( index, x, y ) {
  11518. index *= this.itemSize;
  11519. this.array[ index + 0 ] = x;
  11520. this.array[ index + 1 ] = y;
  11521. return this;
  11522. },
  11523. setXYZ: function ( index, x, y, z ) {
  11524. index *= this.itemSize;
  11525. this.array[ index + 0 ] = x;
  11526. this.array[ index + 1 ] = y;
  11527. this.array[ index + 2 ] = z;
  11528. return this;
  11529. },
  11530. setXYZW: function ( index, x, y, z, w ) {
  11531. index *= this.itemSize;
  11532. this.array[ index + 0 ] = x;
  11533. this.array[ index + 1 ] = y;
  11534. this.array[ index + 2 ] = z;
  11535. this.array[ index + 3 ] = w;
  11536. return this;
  11537. },
  11538. onUpload: function ( callback ) {
  11539. this.onUploadCallback = callback;
  11540. return this;
  11541. },
  11542. clone: function () {
  11543. return new this.constructor().copy( this );
  11544. }
  11545. };
  11546. //
  11547. function Int8BufferAttribute( array, itemSize ) {
  11548. BufferAttribute.call( this, new Int8Array( array ), itemSize );
  11549. }
  11550. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11551. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  11552. function Uint8BufferAttribute( array, itemSize ) {
  11553. BufferAttribute.call( this, new Uint8Array( array ), itemSize );
  11554. }
  11555. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11556. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  11557. function Uint8ClampedBufferAttribute( array, itemSize ) {
  11558. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize );
  11559. }
  11560. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11561. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  11562. function Int16BufferAttribute( array, itemSize ) {
  11563. BufferAttribute.call( this, new Int16Array( array ), itemSize );
  11564. }
  11565. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11566. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  11567. function Uint16BufferAttribute( array, itemSize ) {
  11568. BufferAttribute.call( this, new Uint16Array( array ), itemSize );
  11569. }
  11570. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11571. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  11572. function Int32BufferAttribute( array, itemSize ) {
  11573. BufferAttribute.call( this, new Int32Array( array ), itemSize );
  11574. }
  11575. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11576. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  11577. function Uint32BufferAttribute( array, itemSize ) {
  11578. BufferAttribute.call( this, new Uint32Array( array ), itemSize );
  11579. }
  11580. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11581. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  11582. function Float32BufferAttribute( array, itemSize ) {
  11583. BufferAttribute.call( this, new Float32Array( array ), itemSize );
  11584. }
  11585. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11586. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  11587. function Float64BufferAttribute( array, itemSize ) {
  11588. BufferAttribute.call( this, new Float64Array( array ), itemSize );
  11589. }
  11590. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  11591. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  11592. /**
  11593. * @author mrdoob / http://mrdoob.com/
  11594. */
  11595. function DirectGeometry() {
  11596. this.indices = [];
  11597. this.vertices = [];
  11598. this.normals = [];
  11599. this.colors = [];
  11600. this.uvs = [];
  11601. this.uvs2 = [];
  11602. this.groups = [];
  11603. this.morphTargets = {};
  11604. this.skinWeights = [];
  11605. this.skinIndices = [];
  11606. // this.lineDistances = [];
  11607. this.boundingBox = null;
  11608. this.boundingSphere = null;
  11609. // update flags
  11610. this.verticesNeedUpdate = false;
  11611. this.normalsNeedUpdate = false;
  11612. this.colorsNeedUpdate = false;
  11613. this.uvsNeedUpdate = false;
  11614. this.groupsNeedUpdate = false;
  11615. }
  11616. Object.assign( DirectGeometry.prototype, {
  11617. computeGroups: function ( geometry ) {
  11618. var group;
  11619. var groups = [];
  11620. var materialIndex = undefined;
  11621. var faces = geometry.faces;
  11622. for ( var i = 0; i < faces.length; i ++ ) {
  11623. var face = faces[ i ];
  11624. // materials
  11625. if ( face.materialIndex !== materialIndex ) {
  11626. materialIndex = face.materialIndex;
  11627. if ( group !== undefined ) {
  11628. group.count = ( i * 3 ) - group.start;
  11629. groups.push( group );
  11630. }
  11631. group = {
  11632. start: i * 3,
  11633. materialIndex: materialIndex
  11634. };
  11635. }
  11636. }
  11637. if ( group !== undefined ) {
  11638. group.count = ( i * 3 ) - group.start;
  11639. groups.push( group );
  11640. }
  11641. this.groups = groups;
  11642. },
  11643. fromGeometry: function ( geometry ) {
  11644. var faces = geometry.faces;
  11645. var vertices = geometry.vertices;
  11646. var faceVertexUvs = geometry.faceVertexUvs;
  11647. var hasFaceVertexUv = faceVertexUvs[ 0 ] && faceVertexUvs[ 0 ].length > 0;
  11648. var hasFaceVertexUv2 = faceVertexUvs[ 1 ] && faceVertexUvs[ 1 ].length > 0;
  11649. // morphs
  11650. var morphTargets = geometry.morphTargets;
  11651. var morphTargetsLength = morphTargets.length;
  11652. var morphTargetsPosition;
  11653. if ( morphTargetsLength > 0 ) {
  11654. morphTargetsPosition = [];
  11655. for ( var i = 0; i < morphTargetsLength; i ++ ) {
  11656. morphTargetsPosition[ i ] = [];
  11657. }
  11658. this.morphTargets.position = morphTargetsPosition;
  11659. }
  11660. var morphNormals = geometry.morphNormals;
  11661. var morphNormalsLength = morphNormals.length;
  11662. var morphTargetsNormal;
  11663. if ( morphNormalsLength > 0 ) {
  11664. morphTargetsNormal = [];
  11665. for ( var i = 0; i < morphNormalsLength; i ++ ) {
  11666. morphTargetsNormal[ i ] = [];
  11667. }
  11668. this.morphTargets.normal = morphTargetsNormal;
  11669. }
  11670. // skins
  11671. var skinIndices = geometry.skinIndices;
  11672. var skinWeights = geometry.skinWeights;
  11673. var hasSkinIndices = skinIndices.length === vertices.length;
  11674. var hasSkinWeights = skinWeights.length === vertices.length;
  11675. //
  11676. for ( var i = 0; i < faces.length; i ++ ) {
  11677. var face = faces[ i ];
  11678. this.vertices.push( vertices[ face.a ], vertices[ face.b ], vertices[ face.c ] );
  11679. var vertexNormals = face.vertexNormals;
  11680. if ( vertexNormals.length === 3 ) {
  11681. this.normals.push( vertexNormals[ 0 ], vertexNormals[ 1 ], vertexNormals[ 2 ] );
  11682. } else {
  11683. var normal = face.normal;
  11684. this.normals.push( normal, normal, normal );
  11685. }
  11686. var vertexColors = face.vertexColors;
  11687. if ( vertexColors.length === 3 ) {
  11688. this.colors.push( vertexColors[ 0 ], vertexColors[ 1 ], vertexColors[ 2 ] );
  11689. } else {
  11690. var color = face.color;
  11691. this.colors.push( color, color, color );
  11692. }
  11693. if ( hasFaceVertexUv === true ) {
  11694. var vertexUvs = faceVertexUvs[ 0 ][ i ];
  11695. if ( vertexUvs !== undefined ) {
  11696. this.uvs.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11697. } else {
  11698. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv ', i );
  11699. this.uvs.push( new Vector2(), new Vector2(), new Vector2() );
  11700. }
  11701. }
  11702. if ( hasFaceVertexUv2 === true ) {
  11703. var vertexUvs = faceVertexUvs[ 1 ][ i ];
  11704. if ( vertexUvs !== undefined ) {
  11705. this.uvs2.push( vertexUvs[ 0 ], vertexUvs[ 1 ], vertexUvs[ 2 ] );
  11706. } else {
  11707. console.warn( 'THREE.DirectGeometry.fromGeometry(): Undefined vertexUv2 ', i );
  11708. this.uvs2.push( new Vector2(), new Vector2(), new Vector2() );
  11709. }
  11710. }
  11711. // morphs
  11712. for ( var j = 0; j < morphTargetsLength; j ++ ) {
  11713. var morphTarget = morphTargets[ j ].vertices;
  11714. morphTargetsPosition[ j ].push( morphTarget[ face.a ], morphTarget[ face.b ], morphTarget[ face.c ] );
  11715. }
  11716. for ( var j = 0; j < morphNormalsLength; j ++ ) {
  11717. var morphNormal = morphNormals[ j ].vertexNormals[ i ];
  11718. morphTargetsNormal[ j ].push( morphNormal.a, morphNormal.b, morphNormal.c );
  11719. }
  11720. // skins
  11721. if ( hasSkinIndices ) {
  11722. this.skinIndices.push( skinIndices[ face.a ], skinIndices[ face.b ], skinIndices[ face.c ] );
  11723. }
  11724. if ( hasSkinWeights ) {
  11725. this.skinWeights.push( skinWeights[ face.a ], skinWeights[ face.b ], skinWeights[ face.c ] );
  11726. }
  11727. }
  11728. this.computeGroups( geometry );
  11729. this.verticesNeedUpdate = geometry.verticesNeedUpdate;
  11730. this.normalsNeedUpdate = geometry.normalsNeedUpdate;
  11731. this.colorsNeedUpdate = geometry.colorsNeedUpdate;
  11732. this.uvsNeedUpdate = geometry.uvsNeedUpdate;
  11733. this.groupsNeedUpdate = geometry.groupsNeedUpdate;
  11734. return this;
  11735. }
  11736. } );
  11737. /**
  11738. * @author mrdoob / http://mrdoob.com/
  11739. * @author kile / http://kile.stravaganza.org/
  11740. * @author alteredq / http://alteredqualia.com/
  11741. * @author mikael emtinger / http://gomo.se/
  11742. * @author zz85 / http://www.lab4games.net/zz85/blog
  11743. * @author bhouston / http://clara.io
  11744. */
  11745. function Geometry() {
  11746. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  11747. this.uuid = _Math.generateUUID();
  11748. this.name = '';
  11749. this.type = 'Geometry';
  11750. this.vertices = [];
  11751. this.colors = [];
  11752. this.faces = [];
  11753. this.faceVertexUvs = [ [] ];
  11754. this.morphTargets = [];
  11755. this.morphNormals = [];
  11756. this.skinWeights = [];
  11757. this.skinIndices = [];
  11758. this.lineDistances = [];
  11759. this.boundingBox = null;
  11760. this.boundingSphere = null;
  11761. // update flags
  11762. this.elementsNeedUpdate = false;
  11763. this.verticesNeedUpdate = false;
  11764. this.uvsNeedUpdate = false;
  11765. this.normalsNeedUpdate = false;
  11766. this.colorsNeedUpdate = false;
  11767. this.lineDistancesNeedUpdate = false;
  11768. this.groupsNeedUpdate = false;
  11769. }
  11770. Object.assign( Geometry.prototype, EventDispatcher.prototype, {
  11771. isGeometry: true,
  11772. applyMatrix: function ( matrix ) {
  11773. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  11774. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  11775. var vertex = this.vertices[ i ];
  11776. vertex.applyMatrix4( matrix );
  11777. }
  11778. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  11779. var face = this.faces[ i ];
  11780. face.normal.applyMatrix3( normalMatrix ).normalize();
  11781. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  11782. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  11783. }
  11784. }
  11785. if ( this.boundingBox !== null ) {
  11786. this.computeBoundingBox();
  11787. }
  11788. if ( this.boundingSphere !== null ) {
  11789. this.computeBoundingSphere();
  11790. }
  11791. this.verticesNeedUpdate = true;
  11792. this.normalsNeedUpdate = true;
  11793. return this;
  11794. },
  11795. rotateX: function () {
  11796. // rotate geometry around world x-axis
  11797. var m1;
  11798. return function rotateX( angle ) {
  11799. if ( m1 === undefined ) m1 = new Matrix4();
  11800. m1.makeRotationX( angle );
  11801. this.applyMatrix( m1 );
  11802. return this;
  11803. };
  11804. }(),
  11805. rotateY: function () {
  11806. // rotate geometry around world y-axis
  11807. var m1;
  11808. return function rotateY( angle ) {
  11809. if ( m1 === undefined ) m1 = new Matrix4();
  11810. m1.makeRotationY( angle );
  11811. this.applyMatrix( m1 );
  11812. return this;
  11813. };
  11814. }(),
  11815. rotateZ: function () {
  11816. // rotate geometry around world z-axis
  11817. var m1;
  11818. return function rotateZ( angle ) {
  11819. if ( m1 === undefined ) m1 = new Matrix4();
  11820. m1.makeRotationZ( angle );
  11821. this.applyMatrix( m1 );
  11822. return this;
  11823. };
  11824. }(),
  11825. translate: function () {
  11826. // translate geometry
  11827. var m1;
  11828. return function translate( x, y, z ) {
  11829. if ( m1 === undefined ) m1 = new Matrix4();
  11830. m1.makeTranslation( x, y, z );
  11831. this.applyMatrix( m1 );
  11832. return this;
  11833. };
  11834. }(),
  11835. scale: function () {
  11836. // scale geometry
  11837. var m1;
  11838. return function scale( x, y, z ) {
  11839. if ( m1 === undefined ) m1 = new Matrix4();
  11840. m1.makeScale( x, y, z );
  11841. this.applyMatrix( m1 );
  11842. return this;
  11843. };
  11844. }(),
  11845. lookAt: function () {
  11846. var obj;
  11847. return function lookAt( vector ) {
  11848. if ( obj === undefined ) obj = new Object3D();
  11849. obj.lookAt( vector );
  11850. obj.updateMatrix();
  11851. this.applyMatrix( obj.matrix );
  11852. };
  11853. }(),
  11854. fromBufferGeometry: function ( geometry ) {
  11855. var scope = this;
  11856. var indices = geometry.index !== null ? geometry.index.array : undefined;
  11857. var attributes = geometry.attributes;
  11858. var positions = attributes.position.array;
  11859. var normals = attributes.normal !== undefined ? attributes.normal.array : undefined;
  11860. var colors = attributes.color !== undefined ? attributes.color.array : undefined;
  11861. var uvs = attributes.uv !== undefined ? attributes.uv.array : undefined;
  11862. var uvs2 = attributes.uv2 !== undefined ? attributes.uv2.array : undefined;
  11863. if ( uvs2 !== undefined ) this.faceVertexUvs[ 1 ] = [];
  11864. var tempNormals = [];
  11865. var tempUVs = [];
  11866. var tempUVs2 = [];
  11867. for ( var i = 0, j = 0; i < positions.length; i += 3, j += 2 ) {
  11868. scope.vertices.push( new Vector3( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] ) );
  11869. if ( normals !== undefined ) {
  11870. tempNormals.push( new Vector3( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] ) );
  11871. }
  11872. if ( colors !== undefined ) {
  11873. scope.colors.push( new Color( colors[ i ], colors[ i + 1 ], colors[ i + 2 ] ) );
  11874. }
  11875. if ( uvs !== undefined ) {
  11876. tempUVs.push( new Vector2( uvs[ j ], uvs[ j + 1 ] ) );
  11877. }
  11878. if ( uvs2 !== undefined ) {
  11879. tempUVs2.push( new Vector2( uvs2[ j ], uvs2[ j + 1 ] ) );
  11880. }
  11881. }
  11882. function addFace( a, b, c, materialIndex ) {
  11883. var vertexNormals = normals !== undefined ? [ tempNormals[ a ].clone(), tempNormals[ b ].clone(), tempNormals[ c ].clone() ] : [];
  11884. var vertexColors = colors !== undefined ? [ scope.colors[ a ].clone(), scope.colors[ b ].clone(), scope.colors[ c ].clone() ] : [];
  11885. var face = new Face3( a, b, c, vertexNormals, vertexColors, materialIndex );
  11886. scope.faces.push( face );
  11887. if ( uvs !== undefined ) {
  11888. scope.faceVertexUvs[ 0 ].push( [ tempUVs[ a ].clone(), tempUVs[ b ].clone(), tempUVs[ c ].clone() ] );
  11889. }
  11890. if ( uvs2 !== undefined ) {
  11891. scope.faceVertexUvs[ 1 ].push( [ tempUVs2[ a ].clone(), tempUVs2[ b ].clone(), tempUVs2[ c ].clone() ] );
  11892. }
  11893. }
  11894. if ( indices !== undefined ) {
  11895. var groups = geometry.groups;
  11896. if ( groups.length > 0 ) {
  11897. for ( var i = 0; i < groups.length; i ++ ) {
  11898. var group = groups[ i ];
  11899. var start = group.start;
  11900. var count = group.count;
  11901. for ( var j = start, jl = start + count; j < jl; j += 3 ) {
  11902. addFace( indices[ j ], indices[ j + 1 ], indices[ j + 2 ], group.materialIndex );
  11903. }
  11904. }
  11905. } else {
  11906. for ( var i = 0; i < indices.length; i += 3 ) {
  11907. addFace( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  11908. }
  11909. }
  11910. } else {
  11911. for ( var i = 0; i < positions.length / 3; i += 3 ) {
  11912. addFace( i, i + 1, i + 2 );
  11913. }
  11914. }
  11915. this.computeFaceNormals();
  11916. if ( geometry.boundingBox !== null ) {
  11917. this.boundingBox = geometry.boundingBox.clone();
  11918. }
  11919. if ( geometry.boundingSphere !== null ) {
  11920. this.boundingSphere = geometry.boundingSphere.clone();
  11921. }
  11922. return this;
  11923. },
  11924. center: function () {
  11925. this.computeBoundingBox();
  11926. var offset = this.boundingBox.getCenter().negate();
  11927. this.translate( offset.x, offset.y, offset.z );
  11928. return offset;
  11929. },
  11930. normalize: function () {
  11931. this.computeBoundingSphere();
  11932. var center = this.boundingSphere.center;
  11933. var radius = this.boundingSphere.radius;
  11934. var s = radius === 0 ? 1 : 1.0 / radius;
  11935. var matrix = new Matrix4();
  11936. matrix.set(
  11937. s, 0, 0, - s * center.x,
  11938. 0, s, 0, - s * center.y,
  11939. 0, 0, s, - s * center.z,
  11940. 0, 0, 0, 1
  11941. );
  11942. this.applyMatrix( matrix );
  11943. return this;
  11944. },
  11945. computeFaceNormals: function () {
  11946. var cb = new Vector3(), ab = new Vector3();
  11947. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11948. var face = this.faces[ f ];
  11949. var vA = this.vertices[ face.a ];
  11950. var vB = this.vertices[ face.b ];
  11951. var vC = this.vertices[ face.c ];
  11952. cb.subVectors( vC, vB );
  11953. ab.subVectors( vA, vB );
  11954. cb.cross( ab );
  11955. cb.normalize();
  11956. face.normal.copy( cb );
  11957. }
  11958. },
  11959. computeVertexNormals: function ( areaWeighted ) {
  11960. if ( areaWeighted === undefined ) areaWeighted = true;
  11961. var v, vl, f, fl, face, vertices;
  11962. vertices = new Array( this.vertices.length );
  11963. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11964. vertices[ v ] = new Vector3();
  11965. }
  11966. if ( areaWeighted ) {
  11967. // vertex normals weighted by triangle areas
  11968. // http://www.iquilezles.org/www/articles/normals/normals.htm
  11969. var vA, vB, vC;
  11970. var cb = new Vector3(), ab = new Vector3();
  11971. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11972. face = this.faces[ f ];
  11973. vA = this.vertices[ face.a ];
  11974. vB = this.vertices[ face.b ];
  11975. vC = this.vertices[ face.c ];
  11976. cb.subVectors( vC, vB );
  11977. ab.subVectors( vA, vB );
  11978. cb.cross( ab );
  11979. vertices[ face.a ].add( cb );
  11980. vertices[ face.b ].add( cb );
  11981. vertices[ face.c ].add( cb );
  11982. }
  11983. } else {
  11984. this.computeFaceNormals();
  11985. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11986. face = this.faces[ f ];
  11987. vertices[ face.a ].add( face.normal );
  11988. vertices[ face.b ].add( face.normal );
  11989. vertices[ face.c ].add( face.normal );
  11990. }
  11991. }
  11992. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  11993. vertices[ v ].normalize();
  11994. }
  11995. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  11996. face = this.faces[ f ];
  11997. var vertexNormals = face.vertexNormals;
  11998. if ( vertexNormals.length === 3 ) {
  11999. vertexNormals[ 0 ].copy( vertices[ face.a ] );
  12000. vertexNormals[ 1 ].copy( vertices[ face.b ] );
  12001. vertexNormals[ 2 ].copy( vertices[ face.c ] );
  12002. } else {
  12003. vertexNormals[ 0 ] = vertices[ face.a ].clone();
  12004. vertexNormals[ 1 ] = vertices[ face.b ].clone();
  12005. vertexNormals[ 2 ] = vertices[ face.c ].clone();
  12006. }
  12007. }
  12008. if ( this.faces.length > 0 ) {
  12009. this.normalsNeedUpdate = true;
  12010. }
  12011. },
  12012. computeFlatVertexNormals: function () {
  12013. var f, fl, face;
  12014. this.computeFaceNormals();
  12015. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12016. face = this.faces[ f ];
  12017. var vertexNormals = face.vertexNormals;
  12018. if ( vertexNormals.length === 3 ) {
  12019. vertexNormals[ 0 ].copy( face.normal );
  12020. vertexNormals[ 1 ].copy( face.normal );
  12021. vertexNormals[ 2 ].copy( face.normal );
  12022. } else {
  12023. vertexNormals[ 0 ] = face.normal.clone();
  12024. vertexNormals[ 1 ] = face.normal.clone();
  12025. vertexNormals[ 2 ] = face.normal.clone();
  12026. }
  12027. }
  12028. if ( this.faces.length > 0 ) {
  12029. this.normalsNeedUpdate = true;
  12030. }
  12031. },
  12032. computeMorphNormals: function () {
  12033. var i, il, f, fl, face;
  12034. // save original normals
  12035. // - create temp variables on first access
  12036. // otherwise just copy (for faster repeated calls)
  12037. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12038. face = this.faces[ f ];
  12039. if ( ! face.__originalFaceNormal ) {
  12040. face.__originalFaceNormal = face.normal.clone();
  12041. } else {
  12042. face.__originalFaceNormal.copy( face.normal );
  12043. }
  12044. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  12045. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  12046. if ( ! face.__originalVertexNormals[ i ] ) {
  12047. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  12048. } else {
  12049. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  12050. }
  12051. }
  12052. }
  12053. // use temp geometry to compute face and vertex normals for each morph
  12054. var tmpGeo = new Geometry();
  12055. tmpGeo.faces = this.faces;
  12056. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  12057. // create on first access
  12058. if ( ! this.morphNormals[ i ] ) {
  12059. this.morphNormals[ i ] = {};
  12060. this.morphNormals[ i ].faceNormals = [];
  12061. this.morphNormals[ i ].vertexNormals = [];
  12062. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  12063. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  12064. var faceNormal, vertexNormals;
  12065. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12066. faceNormal = new Vector3();
  12067. vertexNormals = { a: new Vector3(), b: new Vector3(), c: new Vector3() };
  12068. dstNormalsFace.push( faceNormal );
  12069. dstNormalsVertex.push( vertexNormals );
  12070. }
  12071. }
  12072. var morphNormals = this.morphNormals[ i ];
  12073. // set vertices to morph target
  12074. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  12075. // compute morph normals
  12076. tmpGeo.computeFaceNormals();
  12077. tmpGeo.computeVertexNormals();
  12078. // store morph normals
  12079. var faceNormal, vertexNormals;
  12080. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12081. face = this.faces[ f ];
  12082. faceNormal = morphNormals.faceNormals[ f ];
  12083. vertexNormals = morphNormals.vertexNormals[ f ];
  12084. faceNormal.copy( face.normal );
  12085. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  12086. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  12087. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  12088. }
  12089. }
  12090. // restore original normals
  12091. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  12092. face = this.faces[ f ];
  12093. face.normal = face.__originalFaceNormal;
  12094. face.vertexNormals = face.__originalVertexNormals;
  12095. }
  12096. },
  12097. computeLineDistances: function () {
  12098. var d = 0;
  12099. var vertices = this.vertices;
  12100. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  12101. if ( i > 0 ) {
  12102. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  12103. }
  12104. this.lineDistances[ i ] = d;
  12105. }
  12106. },
  12107. computeBoundingBox: function () {
  12108. if ( this.boundingBox === null ) {
  12109. this.boundingBox = new Box3();
  12110. }
  12111. this.boundingBox.setFromPoints( this.vertices );
  12112. },
  12113. computeBoundingSphere: function () {
  12114. if ( this.boundingSphere === null ) {
  12115. this.boundingSphere = new Sphere();
  12116. }
  12117. this.boundingSphere.setFromPoints( this.vertices );
  12118. },
  12119. merge: function ( geometry, matrix, materialIndexOffset ) {
  12120. if ( (geometry && geometry.isGeometry) === false ) {
  12121. console.error( 'THREE.Geometry.merge(): geometry not an instance of THREE.Geometry.', geometry );
  12122. return;
  12123. }
  12124. var normalMatrix,
  12125. vertexOffset = this.vertices.length,
  12126. vertices1 = this.vertices,
  12127. vertices2 = geometry.vertices,
  12128. faces1 = this.faces,
  12129. faces2 = geometry.faces,
  12130. uvs1 = this.faceVertexUvs[ 0 ],
  12131. uvs2 = geometry.faceVertexUvs[ 0 ],
  12132. colors1 = this.colors,
  12133. colors2 = geometry.colors;
  12134. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  12135. if ( matrix !== undefined ) {
  12136. normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12137. }
  12138. // vertices
  12139. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  12140. var vertex = vertices2[ i ];
  12141. var vertexCopy = vertex.clone();
  12142. if ( matrix !== undefined ) vertexCopy.applyMatrix4( matrix );
  12143. vertices1.push( vertexCopy );
  12144. }
  12145. // colors
  12146. for ( var i = 0, il = colors2.length; i < il; i ++ ) {
  12147. colors1.push( colors2[ i ].clone() );
  12148. }
  12149. // faces
  12150. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  12151. var face = faces2[ i ], faceCopy, normal, color,
  12152. faceVertexNormals = face.vertexNormals,
  12153. faceVertexColors = face.vertexColors;
  12154. faceCopy = new Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  12155. faceCopy.normal.copy( face.normal );
  12156. if ( normalMatrix !== undefined ) {
  12157. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  12158. }
  12159. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  12160. normal = faceVertexNormals[ j ].clone();
  12161. if ( normalMatrix !== undefined ) {
  12162. normal.applyMatrix3( normalMatrix ).normalize();
  12163. }
  12164. faceCopy.vertexNormals.push( normal );
  12165. }
  12166. faceCopy.color.copy( face.color );
  12167. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  12168. color = faceVertexColors[ j ];
  12169. faceCopy.vertexColors.push( color.clone() );
  12170. }
  12171. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  12172. faces1.push( faceCopy );
  12173. }
  12174. // uvs
  12175. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  12176. var uv = uvs2[ i ], uvCopy = [];
  12177. if ( uv === undefined ) {
  12178. continue;
  12179. }
  12180. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  12181. uvCopy.push( uv[ j ].clone() );
  12182. }
  12183. uvs1.push( uvCopy );
  12184. }
  12185. },
  12186. mergeMesh: function ( mesh ) {
  12187. if ( (mesh && mesh.isMesh) === false ) {
  12188. console.error( 'THREE.Geometry.mergeMesh(): mesh not an instance of THREE.Mesh.', mesh );
  12189. return;
  12190. }
  12191. mesh.matrixAutoUpdate && mesh.updateMatrix();
  12192. this.merge( mesh.geometry, mesh.matrix );
  12193. },
  12194. /*
  12195. * Checks for duplicate vertices with hashmap.
  12196. * Duplicated vertices are removed
  12197. * and faces' vertices are updated.
  12198. */
  12199. mergeVertices: function () {
  12200. var verticesMap = {}; // Hashmap for looking up vertices by position coordinates (and making sure they are unique)
  12201. var unique = [], changes = [];
  12202. var v, key;
  12203. var precisionPoints = 4; // number of decimal points, e.g. 4 for epsilon of 0.0001
  12204. var precision = Math.pow( 10, precisionPoints );
  12205. var i, il, face;
  12206. var indices, j, jl;
  12207. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  12208. v = this.vertices[ i ];
  12209. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  12210. if ( verticesMap[ key ] === undefined ) {
  12211. verticesMap[ key ] = i;
  12212. unique.push( this.vertices[ i ] );
  12213. changes[ i ] = unique.length - 1;
  12214. } else {
  12215. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  12216. changes[ i ] = changes[ verticesMap[ key ] ];
  12217. }
  12218. }
  12219. // if faces are completely degenerate after merging vertices, we
  12220. // have to remove them from the geometry.
  12221. var faceIndicesToRemove = [];
  12222. for ( i = 0, il = this.faces.length; i < il; i ++ ) {
  12223. face = this.faces[ i ];
  12224. face.a = changes[ face.a ];
  12225. face.b = changes[ face.b ];
  12226. face.c = changes[ face.c ];
  12227. indices = [ face.a, face.b, face.c ];
  12228. var dupIndex = - 1;
  12229. // if any duplicate vertices are found in a Face3
  12230. // we have to remove the face as nothing can be saved
  12231. for ( var n = 0; n < 3; n ++ ) {
  12232. if ( indices[ n ] === indices[ ( n + 1 ) % 3 ] ) {
  12233. dupIndex = n;
  12234. faceIndicesToRemove.push( i );
  12235. break;
  12236. }
  12237. }
  12238. }
  12239. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  12240. var idx = faceIndicesToRemove[ i ];
  12241. this.faces.splice( idx, 1 );
  12242. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  12243. this.faceVertexUvs[ j ].splice( idx, 1 );
  12244. }
  12245. }
  12246. // Use unique set of vertices
  12247. var diff = this.vertices.length - unique.length;
  12248. this.vertices = unique;
  12249. return diff;
  12250. },
  12251. sortFacesByMaterialIndex: function () {
  12252. var faces = this.faces;
  12253. var length = faces.length;
  12254. // tag faces
  12255. for ( var i = 0; i < length; i ++ ) {
  12256. faces[ i ]._id = i;
  12257. }
  12258. // sort faces
  12259. function materialIndexSort( a, b ) {
  12260. return a.materialIndex - b.materialIndex;
  12261. }
  12262. faces.sort( materialIndexSort );
  12263. // sort uvs
  12264. var uvs1 = this.faceVertexUvs[ 0 ];
  12265. var uvs2 = this.faceVertexUvs[ 1 ];
  12266. var newUvs1, newUvs2;
  12267. if ( uvs1 && uvs1.length === length ) newUvs1 = [];
  12268. if ( uvs2 && uvs2.length === length ) newUvs2 = [];
  12269. for ( var i = 0; i < length; i ++ ) {
  12270. var id = faces[ i ]._id;
  12271. if ( newUvs1 ) newUvs1.push( uvs1[ id ] );
  12272. if ( newUvs2 ) newUvs2.push( uvs2[ id ] );
  12273. }
  12274. if ( newUvs1 ) this.faceVertexUvs[ 0 ] = newUvs1;
  12275. if ( newUvs2 ) this.faceVertexUvs[ 1 ] = newUvs2;
  12276. },
  12277. toJSON: function () {
  12278. var data = {
  12279. metadata: {
  12280. version: 4.4,
  12281. type: 'Geometry',
  12282. generator: 'Geometry.toJSON'
  12283. }
  12284. };
  12285. // standard Geometry serialization
  12286. data.uuid = this.uuid;
  12287. data.type = this.type;
  12288. if ( this.name !== '' ) data.name = this.name;
  12289. if ( this.parameters !== undefined ) {
  12290. var parameters = this.parameters;
  12291. for ( var key in parameters ) {
  12292. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12293. }
  12294. return data;
  12295. }
  12296. var vertices = [];
  12297. for ( var i = 0; i < this.vertices.length; i ++ ) {
  12298. var vertex = this.vertices[ i ];
  12299. vertices.push( vertex.x, vertex.y, vertex.z );
  12300. }
  12301. var faces = [];
  12302. var normals = [];
  12303. var normalsHash = {};
  12304. var colors = [];
  12305. var colorsHash = {};
  12306. var uvs = [];
  12307. var uvsHash = {};
  12308. for ( var i = 0; i < this.faces.length; i ++ ) {
  12309. var face = this.faces[ i ];
  12310. var hasMaterial = true;
  12311. var hasFaceUv = false; // deprecated
  12312. var hasFaceVertexUv = this.faceVertexUvs[ 0 ][ i ] !== undefined;
  12313. var hasFaceNormal = face.normal.length() > 0;
  12314. var hasFaceVertexNormal = face.vertexNormals.length > 0;
  12315. var hasFaceColor = face.color.r !== 1 || face.color.g !== 1 || face.color.b !== 1;
  12316. var hasFaceVertexColor = face.vertexColors.length > 0;
  12317. var faceType = 0;
  12318. faceType = setBit( faceType, 0, 0 ); // isQuad
  12319. faceType = setBit( faceType, 1, hasMaterial );
  12320. faceType = setBit( faceType, 2, hasFaceUv );
  12321. faceType = setBit( faceType, 3, hasFaceVertexUv );
  12322. faceType = setBit( faceType, 4, hasFaceNormal );
  12323. faceType = setBit( faceType, 5, hasFaceVertexNormal );
  12324. faceType = setBit( faceType, 6, hasFaceColor );
  12325. faceType = setBit( faceType, 7, hasFaceVertexColor );
  12326. faces.push( faceType );
  12327. faces.push( face.a, face.b, face.c );
  12328. faces.push( face.materialIndex );
  12329. if ( hasFaceVertexUv ) {
  12330. var faceVertexUvs = this.faceVertexUvs[ 0 ][ i ];
  12331. faces.push(
  12332. getUvIndex( faceVertexUvs[ 0 ] ),
  12333. getUvIndex( faceVertexUvs[ 1 ] ),
  12334. getUvIndex( faceVertexUvs[ 2 ] )
  12335. );
  12336. }
  12337. if ( hasFaceNormal ) {
  12338. faces.push( getNormalIndex( face.normal ) );
  12339. }
  12340. if ( hasFaceVertexNormal ) {
  12341. var vertexNormals = face.vertexNormals;
  12342. faces.push(
  12343. getNormalIndex( vertexNormals[ 0 ] ),
  12344. getNormalIndex( vertexNormals[ 1 ] ),
  12345. getNormalIndex( vertexNormals[ 2 ] )
  12346. );
  12347. }
  12348. if ( hasFaceColor ) {
  12349. faces.push( getColorIndex( face.color ) );
  12350. }
  12351. if ( hasFaceVertexColor ) {
  12352. var vertexColors = face.vertexColors;
  12353. faces.push(
  12354. getColorIndex( vertexColors[ 0 ] ),
  12355. getColorIndex( vertexColors[ 1 ] ),
  12356. getColorIndex( vertexColors[ 2 ] )
  12357. );
  12358. }
  12359. }
  12360. function setBit( value, position, enabled ) {
  12361. return enabled ? value | ( 1 << position ) : value & ( ~ ( 1 << position ) );
  12362. }
  12363. function getNormalIndex( normal ) {
  12364. var hash = normal.x.toString() + normal.y.toString() + normal.z.toString();
  12365. if ( normalsHash[ hash ] !== undefined ) {
  12366. return normalsHash[ hash ];
  12367. }
  12368. normalsHash[ hash ] = normals.length / 3;
  12369. normals.push( normal.x, normal.y, normal.z );
  12370. return normalsHash[ hash ];
  12371. }
  12372. function getColorIndex( color ) {
  12373. var hash = color.r.toString() + color.g.toString() + color.b.toString();
  12374. if ( colorsHash[ hash ] !== undefined ) {
  12375. return colorsHash[ hash ];
  12376. }
  12377. colorsHash[ hash ] = colors.length;
  12378. colors.push( color.getHex() );
  12379. return colorsHash[ hash ];
  12380. }
  12381. function getUvIndex( uv ) {
  12382. var hash = uv.x.toString() + uv.y.toString();
  12383. if ( uvsHash[ hash ] !== undefined ) {
  12384. return uvsHash[ hash ];
  12385. }
  12386. uvsHash[ hash ] = uvs.length / 2;
  12387. uvs.push( uv.x, uv.y );
  12388. return uvsHash[ hash ];
  12389. }
  12390. data.data = {};
  12391. data.data.vertices = vertices;
  12392. data.data.normals = normals;
  12393. if ( colors.length > 0 ) data.data.colors = colors;
  12394. if ( uvs.length > 0 ) data.data.uvs = [ uvs ]; // temporal backward compatibility
  12395. data.data.faces = faces;
  12396. return data;
  12397. },
  12398. clone: function () {
  12399. /*
  12400. // Handle primitives
  12401. var parameters = this.parameters;
  12402. if ( parameters !== undefined ) {
  12403. var values = [];
  12404. for ( var key in parameters ) {
  12405. values.push( parameters[ key ] );
  12406. }
  12407. var geometry = Object.create( this.constructor.prototype );
  12408. this.constructor.apply( geometry, values );
  12409. return geometry;
  12410. }
  12411. return new this.constructor().copy( this );
  12412. */
  12413. return new Geometry().copy( this );
  12414. },
  12415. copy: function ( source ) {
  12416. this.vertices = [];
  12417. this.faces = [];
  12418. this.faceVertexUvs = [ [] ];
  12419. this.colors = [];
  12420. var vertices = source.vertices;
  12421. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  12422. this.vertices.push( vertices[ i ].clone() );
  12423. }
  12424. var colors = source.colors;
  12425. for ( var i = 0, il = colors.length; i < il; i ++ ) {
  12426. this.colors.push( colors[ i ].clone() );
  12427. }
  12428. var faces = source.faces;
  12429. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  12430. this.faces.push( faces[ i ].clone() );
  12431. }
  12432. for ( var i = 0, il = source.faceVertexUvs.length; i < il; i ++ ) {
  12433. var faceVertexUvs = source.faceVertexUvs[ i ];
  12434. if ( this.faceVertexUvs[ i ] === undefined ) {
  12435. this.faceVertexUvs[ i ] = [];
  12436. }
  12437. for ( var j = 0, jl = faceVertexUvs.length; j < jl; j ++ ) {
  12438. var uvs = faceVertexUvs[ j ], uvsCopy = [];
  12439. for ( var k = 0, kl = uvs.length; k < kl; k ++ ) {
  12440. var uv = uvs[ k ];
  12441. uvsCopy.push( uv.clone() );
  12442. }
  12443. this.faceVertexUvs[ i ].push( uvsCopy );
  12444. }
  12445. }
  12446. return this;
  12447. },
  12448. dispose: function () {
  12449. this.dispatchEvent( { type: 'dispose' } );
  12450. }
  12451. } );
  12452. var count = 0;
  12453. function GeometryIdCount() { return count++; }
  12454. /**
  12455. * @author alteredq / http://alteredqualia.com/
  12456. * @author mrdoob / http://mrdoob.com/
  12457. */
  12458. function BufferGeometry() {
  12459. Object.defineProperty( this, 'id', { value: GeometryIdCount() } );
  12460. this.uuid = _Math.generateUUID();
  12461. this.name = '';
  12462. this.type = 'BufferGeometry';
  12463. this.index = null;
  12464. this.attributes = {};
  12465. this.morphAttributes = {};
  12466. this.groups = [];
  12467. this.boundingBox = null;
  12468. this.boundingSphere = null;
  12469. this.drawRange = { start: 0, count: Infinity };
  12470. }
  12471. Object.assign( BufferGeometry.prototype, EventDispatcher.prototype, {
  12472. isBufferGeometry: true,
  12473. getIndex: function () {
  12474. return this.index;
  12475. },
  12476. setIndex: function ( index ) {
  12477. this.index = index;
  12478. },
  12479. addAttribute: function ( name, attribute ) {
  12480. if ( ( attribute && attribute.isBufferAttribute ) === false && ( attribute && attribute.isInterleavedBufferAttribute ) === false ) {
  12481. console.warn( 'THREE.BufferGeometry: .addAttribute() now expects ( name, attribute ).' );
  12482. this.addAttribute( name, new BufferAttribute( arguments[ 1 ], arguments[ 2 ] ) );
  12483. return;
  12484. }
  12485. if ( name === 'index' ) {
  12486. console.warn( 'THREE.BufferGeometry.addAttribute: Use .setIndex() for index attribute.' );
  12487. this.setIndex( attribute );
  12488. return;
  12489. }
  12490. this.attributes[ name ] = attribute;
  12491. return this;
  12492. },
  12493. getAttribute: function ( name ) {
  12494. return this.attributes[ name ];
  12495. },
  12496. removeAttribute: function ( name ) {
  12497. delete this.attributes[ name ];
  12498. return this;
  12499. },
  12500. addGroup: function ( start, count, materialIndex ) {
  12501. this.groups.push( {
  12502. start: start,
  12503. count: count,
  12504. materialIndex: materialIndex !== undefined ? materialIndex : 0
  12505. } );
  12506. },
  12507. clearGroups: function () {
  12508. this.groups = [];
  12509. },
  12510. setDrawRange: function ( start, count ) {
  12511. this.drawRange.start = start;
  12512. this.drawRange.count = count;
  12513. },
  12514. applyMatrix: function ( matrix ) {
  12515. var position = this.attributes.position;
  12516. if ( position !== undefined ) {
  12517. matrix.applyToVector3Array( position.array );
  12518. position.needsUpdate = true;
  12519. }
  12520. var normal = this.attributes.normal;
  12521. if ( normal !== undefined ) {
  12522. var normalMatrix = new Matrix3().getNormalMatrix( matrix );
  12523. normalMatrix.applyToVector3Array( normal.array );
  12524. normal.needsUpdate = true;
  12525. }
  12526. if ( this.boundingBox !== null ) {
  12527. this.computeBoundingBox();
  12528. }
  12529. if ( this.boundingSphere !== null ) {
  12530. this.computeBoundingSphere();
  12531. }
  12532. return this;
  12533. },
  12534. rotateX: function () {
  12535. // rotate geometry around world x-axis
  12536. var m1;
  12537. return function rotateX( angle ) {
  12538. if ( m1 === undefined ) m1 = new Matrix4();
  12539. m1.makeRotationX( angle );
  12540. this.applyMatrix( m1 );
  12541. return this;
  12542. };
  12543. }(),
  12544. rotateY: function () {
  12545. // rotate geometry around world y-axis
  12546. var m1;
  12547. return function rotateY( angle ) {
  12548. if ( m1 === undefined ) m1 = new Matrix4();
  12549. m1.makeRotationY( angle );
  12550. this.applyMatrix( m1 );
  12551. return this;
  12552. };
  12553. }(),
  12554. rotateZ: function () {
  12555. // rotate geometry around world z-axis
  12556. var m1;
  12557. return function rotateZ( angle ) {
  12558. if ( m1 === undefined ) m1 = new Matrix4();
  12559. m1.makeRotationZ( angle );
  12560. this.applyMatrix( m1 );
  12561. return this;
  12562. };
  12563. }(),
  12564. translate: function () {
  12565. // translate geometry
  12566. var m1;
  12567. return function translate( x, y, z ) {
  12568. if ( m1 === undefined ) m1 = new Matrix4();
  12569. m1.makeTranslation( x, y, z );
  12570. this.applyMatrix( m1 );
  12571. return this;
  12572. };
  12573. }(),
  12574. scale: function () {
  12575. // scale geometry
  12576. var m1;
  12577. return function scale( x, y, z ) {
  12578. if ( m1 === undefined ) m1 = new Matrix4();
  12579. m1.makeScale( x, y, z );
  12580. this.applyMatrix( m1 );
  12581. return this;
  12582. };
  12583. }(),
  12584. lookAt: function () {
  12585. var obj;
  12586. return function lookAt( vector ) {
  12587. if ( obj === undefined ) obj = new Object3D();
  12588. obj.lookAt( vector );
  12589. obj.updateMatrix();
  12590. this.applyMatrix( obj.matrix );
  12591. };
  12592. }(),
  12593. center: function () {
  12594. this.computeBoundingBox();
  12595. var offset = this.boundingBox.getCenter().negate();
  12596. this.translate( offset.x, offset.y, offset.z );
  12597. return offset;
  12598. },
  12599. setFromObject: function ( object ) {
  12600. // console.log( 'THREE.BufferGeometry.setFromObject(). Converting', object, this );
  12601. var geometry = object.geometry;
  12602. if ( object.isPoints || object.isLine ) {
  12603. var positions = new Float32BufferAttribute( geometry.vertices.length * 3, 3 );
  12604. var colors = new Float32BufferAttribute( geometry.colors.length * 3, 3 );
  12605. this.addAttribute( 'position', positions.copyVector3sArray( geometry.vertices ) );
  12606. this.addAttribute( 'color', colors.copyColorsArray( geometry.colors ) );
  12607. if ( geometry.lineDistances && geometry.lineDistances.length === geometry.vertices.length ) {
  12608. var lineDistances = new Float32BufferAttribute( geometry.lineDistances.length, 1 );
  12609. this.addAttribute( 'lineDistance', lineDistances.copyArray( geometry.lineDistances ) );
  12610. }
  12611. if ( geometry.boundingSphere !== null ) {
  12612. this.boundingSphere = geometry.boundingSphere.clone();
  12613. }
  12614. if ( geometry.boundingBox !== null ) {
  12615. this.boundingBox = geometry.boundingBox.clone();
  12616. }
  12617. } else if ( object.isMesh ) {
  12618. if ( geometry && geometry.isGeometry ) {
  12619. this.fromGeometry( geometry );
  12620. }
  12621. }
  12622. return this;
  12623. },
  12624. updateFromObject: function ( object ) {
  12625. var geometry = object.geometry;
  12626. if ( object.isMesh ) {
  12627. var direct = geometry.__directGeometry;
  12628. if ( geometry.elementsNeedUpdate === true ) {
  12629. direct = undefined;
  12630. geometry.elementsNeedUpdate = false;
  12631. }
  12632. if ( direct === undefined ) {
  12633. return this.fromGeometry( geometry );
  12634. }
  12635. direct.verticesNeedUpdate = geometry.verticesNeedUpdate;
  12636. direct.normalsNeedUpdate = geometry.normalsNeedUpdate;
  12637. direct.colorsNeedUpdate = geometry.colorsNeedUpdate;
  12638. direct.uvsNeedUpdate = geometry.uvsNeedUpdate;
  12639. direct.groupsNeedUpdate = geometry.groupsNeedUpdate;
  12640. geometry.verticesNeedUpdate = false;
  12641. geometry.normalsNeedUpdate = false;
  12642. geometry.colorsNeedUpdate = false;
  12643. geometry.uvsNeedUpdate = false;
  12644. geometry.groupsNeedUpdate = false;
  12645. geometry = direct;
  12646. }
  12647. var attribute;
  12648. if ( geometry.verticesNeedUpdate === true ) {
  12649. attribute = this.attributes.position;
  12650. if ( attribute !== undefined ) {
  12651. attribute.copyVector3sArray( geometry.vertices );
  12652. attribute.needsUpdate = true;
  12653. }
  12654. geometry.verticesNeedUpdate = false;
  12655. }
  12656. if ( geometry.normalsNeedUpdate === true ) {
  12657. attribute = this.attributes.normal;
  12658. if ( attribute !== undefined ) {
  12659. attribute.copyVector3sArray( geometry.normals );
  12660. attribute.needsUpdate = true;
  12661. }
  12662. geometry.normalsNeedUpdate = false;
  12663. }
  12664. if ( geometry.colorsNeedUpdate === true ) {
  12665. attribute = this.attributes.color;
  12666. if ( attribute !== undefined ) {
  12667. attribute.copyColorsArray( geometry.colors );
  12668. attribute.needsUpdate = true;
  12669. }
  12670. geometry.colorsNeedUpdate = false;
  12671. }
  12672. if ( geometry.uvsNeedUpdate ) {
  12673. attribute = this.attributes.uv;
  12674. if ( attribute !== undefined ) {
  12675. attribute.copyVector2sArray( geometry.uvs );
  12676. attribute.needsUpdate = true;
  12677. }
  12678. geometry.uvsNeedUpdate = false;
  12679. }
  12680. if ( geometry.lineDistancesNeedUpdate ) {
  12681. attribute = this.attributes.lineDistance;
  12682. if ( attribute !== undefined ) {
  12683. attribute.copyArray( geometry.lineDistances );
  12684. attribute.needsUpdate = true;
  12685. }
  12686. geometry.lineDistancesNeedUpdate = false;
  12687. }
  12688. if ( geometry.groupsNeedUpdate ) {
  12689. geometry.computeGroups( object.geometry );
  12690. this.groups = geometry.groups;
  12691. geometry.groupsNeedUpdate = false;
  12692. }
  12693. return this;
  12694. },
  12695. fromGeometry: function ( geometry ) {
  12696. geometry.__directGeometry = new DirectGeometry().fromGeometry( geometry );
  12697. return this.fromDirectGeometry( geometry.__directGeometry );
  12698. },
  12699. fromDirectGeometry: function ( geometry ) {
  12700. var positions = new Float32Array( geometry.vertices.length * 3 );
  12701. this.addAttribute( 'position', new BufferAttribute( positions, 3 ).copyVector3sArray( geometry.vertices ) );
  12702. if ( geometry.normals.length > 0 ) {
  12703. var normals = new Float32Array( geometry.normals.length * 3 );
  12704. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ).copyVector3sArray( geometry.normals ) );
  12705. }
  12706. if ( geometry.colors.length > 0 ) {
  12707. var colors = new Float32Array( geometry.colors.length * 3 );
  12708. this.addAttribute( 'color', new BufferAttribute( colors, 3 ).copyColorsArray( geometry.colors ) );
  12709. }
  12710. if ( geometry.uvs.length > 0 ) {
  12711. var uvs = new Float32Array( geometry.uvs.length * 2 );
  12712. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ).copyVector2sArray( geometry.uvs ) );
  12713. }
  12714. if ( geometry.uvs2.length > 0 ) {
  12715. var uvs2 = new Float32Array( geometry.uvs2.length * 2 );
  12716. this.addAttribute( 'uv2', new BufferAttribute( uvs2, 2 ).copyVector2sArray( geometry.uvs2 ) );
  12717. }
  12718. if ( geometry.indices.length > 0 ) {
  12719. var TypeArray = geometry.vertices.length > 65535 ? Uint32Array : Uint16Array;
  12720. var indices = new TypeArray( geometry.indices.length * 3 );
  12721. this.setIndex( new BufferAttribute( indices, 1 ).copyIndicesArray( geometry.indices ) );
  12722. }
  12723. // groups
  12724. this.groups = geometry.groups;
  12725. // morphs
  12726. for ( var name in geometry.morphTargets ) {
  12727. var array = [];
  12728. var morphTargets = geometry.morphTargets[ name ];
  12729. for ( var i = 0, l = morphTargets.length; i < l; i ++ ) {
  12730. var morphTarget = morphTargets[ i ];
  12731. var attribute = new Float32BufferAttribute( morphTarget.length * 3, 3 );
  12732. array.push( attribute.copyVector3sArray( morphTarget ) );
  12733. }
  12734. this.morphAttributes[ name ] = array;
  12735. }
  12736. // skinning
  12737. if ( geometry.skinIndices.length > 0 ) {
  12738. var skinIndices = new Float32BufferAttribute( geometry.skinIndices.length * 4, 4 );
  12739. this.addAttribute( 'skinIndex', skinIndices.copyVector4sArray( geometry.skinIndices ) );
  12740. }
  12741. if ( geometry.skinWeights.length > 0 ) {
  12742. var skinWeights = new Float32BufferAttribute( geometry.skinWeights.length * 4, 4 );
  12743. this.addAttribute( 'skinWeight', skinWeights.copyVector4sArray( geometry.skinWeights ) );
  12744. }
  12745. //
  12746. if ( geometry.boundingSphere !== null ) {
  12747. this.boundingSphere = geometry.boundingSphere.clone();
  12748. }
  12749. if ( geometry.boundingBox !== null ) {
  12750. this.boundingBox = geometry.boundingBox.clone();
  12751. }
  12752. return this;
  12753. },
  12754. computeBoundingBox: function () {
  12755. if ( this.boundingBox === null ) {
  12756. this.boundingBox = new Box3();
  12757. }
  12758. var position = this.attributes.position;
  12759. if ( position !== undefined ) {
  12760. this.boundingBox.setFromBufferAttribute( position );
  12761. } else {
  12762. this.boundingBox.makeEmpty();
  12763. }
  12764. if ( isNaN( this.boundingBox.min.x ) || isNaN( this.boundingBox.min.y ) || isNaN( this.boundingBox.min.z ) ) {
  12765. console.error( 'THREE.BufferGeometry.computeBoundingBox: Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this );
  12766. }
  12767. },
  12768. computeBoundingSphere: function () {
  12769. var box = new Box3();
  12770. var vector = new Vector3();
  12771. return function computeBoundingSphere() {
  12772. if ( this.boundingSphere === null ) {
  12773. this.boundingSphere = new Sphere();
  12774. }
  12775. var position = this.attributes.position;
  12776. if ( position ) {
  12777. var center = this.boundingSphere.center;
  12778. box.setFromBufferAttribute( position );
  12779. box.getCenter( center );
  12780. // hoping to find a boundingSphere with a radius smaller than the
  12781. // boundingSphere of the boundingBox: sqrt(3) smaller in the best case
  12782. var maxRadiusSq = 0;
  12783. for ( var i = 0, il = position.count; i < il; i ++ ) {
  12784. vector.x = position.getX( i );
  12785. vector.y = position.getY( i );
  12786. vector.z = position.getZ( i );
  12787. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  12788. }
  12789. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  12790. if ( isNaN( this.boundingSphere.radius ) ) {
  12791. console.error( 'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this );
  12792. }
  12793. }
  12794. };
  12795. }(),
  12796. computeFaceNormals: function () {
  12797. // backwards compatibility
  12798. },
  12799. computeVertexNormals: function () {
  12800. var index = this.index;
  12801. var attributes = this.attributes;
  12802. var groups = this.groups;
  12803. if ( attributes.position ) {
  12804. var positions = attributes.position.array;
  12805. if ( attributes.normal === undefined ) {
  12806. this.addAttribute( 'normal', new BufferAttribute( new Float32Array( positions.length ), 3 ) );
  12807. } else {
  12808. // reset existing normals to zero
  12809. var array = attributes.normal.array;
  12810. for ( var i = 0, il = array.length; i < il; i ++ ) {
  12811. array[ i ] = 0;
  12812. }
  12813. }
  12814. var normals = attributes.normal.array;
  12815. var vA, vB, vC;
  12816. var pA = new Vector3(), pB = new Vector3(), pC = new Vector3();
  12817. var cb = new Vector3(), ab = new Vector3();
  12818. // indexed elements
  12819. if ( index ) {
  12820. var indices = index.array;
  12821. if ( groups.length === 0 ) {
  12822. this.addGroup( 0, indices.length );
  12823. }
  12824. for ( var j = 0, jl = groups.length; j < jl; ++ j ) {
  12825. var group = groups[ j ];
  12826. var start = group.start;
  12827. var count = group.count;
  12828. for ( var i = start, il = start + count; i < il; i += 3 ) {
  12829. vA = indices[ i + 0 ] * 3;
  12830. vB = indices[ i + 1 ] * 3;
  12831. vC = indices[ i + 2 ] * 3;
  12832. pA.fromArray( positions, vA );
  12833. pB.fromArray( positions, vB );
  12834. pC.fromArray( positions, vC );
  12835. cb.subVectors( pC, pB );
  12836. ab.subVectors( pA, pB );
  12837. cb.cross( ab );
  12838. normals[ vA ] += cb.x;
  12839. normals[ vA + 1 ] += cb.y;
  12840. normals[ vA + 2 ] += cb.z;
  12841. normals[ vB ] += cb.x;
  12842. normals[ vB + 1 ] += cb.y;
  12843. normals[ vB + 2 ] += cb.z;
  12844. normals[ vC ] += cb.x;
  12845. normals[ vC + 1 ] += cb.y;
  12846. normals[ vC + 2 ] += cb.z;
  12847. }
  12848. }
  12849. } else {
  12850. // non-indexed elements (unconnected triangle soup)
  12851. for ( var i = 0, il = positions.length; i < il; i += 9 ) {
  12852. pA.fromArray( positions, i );
  12853. pB.fromArray( positions, i + 3 );
  12854. pC.fromArray( positions, i + 6 );
  12855. cb.subVectors( pC, pB );
  12856. ab.subVectors( pA, pB );
  12857. cb.cross( ab );
  12858. normals[ i ] = cb.x;
  12859. normals[ i + 1 ] = cb.y;
  12860. normals[ i + 2 ] = cb.z;
  12861. normals[ i + 3 ] = cb.x;
  12862. normals[ i + 4 ] = cb.y;
  12863. normals[ i + 5 ] = cb.z;
  12864. normals[ i + 6 ] = cb.x;
  12865. normals[ i + 7 ] = cb.y;
  12866. normals[ i + 8 ] = cb.z;
  12867. }
  12868. }
  12869. this.normalizeNormals();
  12870. attributes.normal.needsUpdate = true;
  12871. }
  12872. },
  12873. merge: function ( geometry, offset ) {
  12874. if ( ( geometry && geometry.isBufferGeometry ) === false ) {
  12875. console.error( 'THREE.BufferGeometry.merge(): geometry not an instance of THREE.BufferGeometry.', geometry );
  12876. return;
  12877. }
  12878. if ( offset === undefined ) offset = 0;
  12879. var attributes = this.attributes;
  12880. for ( var key in attributes ) {
  12881. if ( geometry.attributes[ key ] === undefined ) continue;
  12882. var attribute1 = attributes[ key ];
  12883. var attributeArray1 = attribute1.array;
  12884. var attribute2 = geometry.attributes[ key ];
  12885. var attributeArray2 = attribute2.array;
  12886. var attributeSize = attribute2.itemSize;
  12887. for ( var i = 0, j = attributeSize * offset; i < attributeArray2.length; i ++, j ++ ) {
  12888. attributeArray1[ j ] = attributeArray2[ i ];
  12889. }
  12890. }
  12891. return this;
  12892. },
  12893. normalizeNormals: function () {
  12894. var normals = this.attributes.normal.array;
  12895. var x, y, z, n;
  12896. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  12897. x = normals[ i ];
  12898. y = normals[ i + 1 ];
  12899. z = normals[ i + 2 ];
  12900. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  12901. normals[ i ] *= n;
  12902. normals[ i + 1 ] *= n;
  12903. normals[ i + 2 ] *= n;
  12904. }
  12905. },
  12906. toNonIndexed: function () {
  12907. if ( this.index === null ) {
  12908. console.warn( 'THREE.BufferGeometry.toNonIndexed(): Geometry is already non-indexed.' );
  12909. return this;
  12910. }
  12911. var geometry2 = new BufferGeometry();
  12912. var indices = this.index.array;
  12913. var attributes = this.attributes;
  12914. for ( var name in attributes ) {
  12915. var attribute = attributes[ name ];
  12916. var array = attribute.array;
  12917. var itemSize = attribute.itemSize;
  12918. var array2 = new array.constructor( indices.length * itemSize );
  12919. var index = 0, index2 = 0;
  12920. for ( var i = 0, l = indices.length; i < l; i ++ ) {
  12921. index = indices[ i ] * itemSize;
  12922. for ( var j = 0; j < itemSize; j ++ ) {
  12923. array2[ index2 ++ ] = array[ index ++ ];
  12924. }
  12925. }
  12926. geometry2.addAttribute( name, new BufferAttribute( array2, itemSize ) );
  12927. }
  12928. return geometry2;
  12929. },
  12930. toJSON: function () {
  12931. var data = {
  12932. metadata: {
  12933. version: 4.4,
  12934. type: 'BufferGeometry',
  12935. generator: 'BufferGeometry.toJSON'
  12936. }
  12937. };
  12938. // standard BufferGeometry serialization
  12939. data.uuid = this.uuid;
  12940. data.type = this.type;
  12941. if ( this.name !== '' ) data.name = this.name;
  12942. if ( this.parameters !== undefined ) {
  12943. var parameters = this.parameters;
  12944. for ( var key in parameters ) {
  12945. if ( parameters[ key ] !== undefined ) data[ key ] = parameters[ key ];
  12946. }
  12947. return data;
  12948. }
  12949. data.data = { attributes: {} };
  12950. var index = this.index;
  12951. if ( index !== null ) {
  12952. var array = Array.prototype.slice.call( index.array );
  12953. data.data.index = {
  12954. type: index.array.constructor.name,
  12955. array: array
  12956. };
  12957. }
  12958. var attributes = this.attributes;
  12959. for ( var key in attributes ) {
  12960. var attribute = attributes[ key ];
  12961. var array = Array.prototype.slice.call( attribute.array );
  12962. data.data.attributes[ key ] = {
  12963. itemSize: attribute.itemSize,
  12964. type: attribute.array.constructor.name,
  12965. array: array,
  12966. normalized: attribute.normalized
  12967. };
  12968. }
  12969. var groups = this.groups;
  12970. if ( groups.length > 0 ) {
  12971. data.data.groups = JSON.parse( JSON.stringify( groups ) );
  12972. }
  12973. var boundingSphere = this.boundingSphere;
  12974. if ( boundingSphere !== null ) {
  12975. data.data.boundingSphere = {
  12976. center: boundingSphere.center.toArray(),
  12977. radius: boundingSphere.radius
  12978. };
  12979. }
  12980. return data;
  12981. },
  12982. clone: function () {
  12983. /*
  12984. // Handle primitives
  12985. var parameters = this.parameters;
  12986. if ( parameters !== undefined ) {
  12987. var values = [];
  12988. for ( var key in parameters ) {
  12989. values.push( parameters[ key ] );
  12990. }
  12991. var geometry = Object.create( this.constructor.prototype );
  12992. this.constructor.apply( geometry, values );
  12993. return geometry;
  12994. }
  12995. return new this.constructor().copy( this );
  12996. */
  12997. return new BufferGeometry().copy( this );
  12998. },
  12999. copy: function ( source ) {
  13000. var index = source.index;
  13001. if ( index !== null ) {
  13002. this.setIndex( index.clone() );
  13003. }
  13004. var attributes = source.attributes;
  13005. for ( var name in attributes ) {
  13006. var attribute = attributes[ name ];
  13007. this.addAttribute( name, attribute.clone() );
  13008. }
  13009. var groups = source.groups;
  13010. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  13011. var group = groups[ i ];
  13012. this.addGroup( group.start, group.count, group.materialIndex );
  13013. }
  13014. return this;
  13015. },
  13016. dispose: function () {
  13017. this.dispatchEvent( { type: 'dispose' } );
  13018. }
  13019. } );
  13020. BufferGeometry.MaxIndex = 65535;
  13021. /**
  13022. * @author mrdoob / http://mrdoob.com/
  13023. * @author alteredq / http://alteredqualia.com/
  13024. * @author mikael emtinger / http://gomo.se/
  13025. * @author jonobr1 / http://jonobr1.com/
  13026. */
  13027. function Mesh( geometry, material ) {
  13028. Object3D.call( this );
  13029. this.type = 'Mesh';
  13030. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  13031. this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  13032. this.drawMode = TrianglesDrawMode;
  13033. this.updateMorphTargets();
  13034. }
  13035. Mesh.prototype = Object.assign( Object.create( Object3D.prototype ), {
  13036. constructor: Mesh,
  13037. isMesh: true,
  13038. setDrawMode: function ( value ) {
  13039. this.drawMode = value;
  13040. },
  13041. copy: function ( source ) {
  13042. Object3D.prototype.copy.call( this, source );
  13043. this.drawMode = source.drawMode;
  13044. return this;
  13045. },
  13046. updateMorphTargets: function () {
  13047. var morphTargets = this.geometry.morphTargets;
  13048. if ( morphTargets !== undefined && morphTargets.length > 0 ) {
  13049. this.morphTargetInfluences = [];
  13050. this.morphTargetDictionary = {};
  13051. for ( var m = 0, ml = morphTargets.length; m < ml; m ++ ) {
  13052. this.morphTargetInfluences.push( 0 );
  13053. this.morphTargetDictionary[ morphTargets[ m ].name ] = m;
  13054. }
  13055. }
  13056. },
  13057. raycast: ( function () {
  13058. var inverseMatrix = new Matrix4();
  13059. var ray = new Ray();
  13060. var sphere = new Sphere();
  13061. var vA = new Vector3();
  13062. var vB = new Vector3();
  13063. var vC = new Vector3();
  13064. var tempA = new Vector3();
  13065. var tempB = new Vector3();
  13066. var tempC = new Vector3();
  13067. var uvA = new Vector2();
  13068. var uvB = new Vector2();
  13069. var uvC = new Vector2();
  13070. var barycoord = new Vector3();
  13071. var intersectionPoint = new Vector3();
  13072. var intersectionPointWorld = new Vector3();
  13073. function uvIntersection( point, p1, p2, p3, uv1, uv2, uv3 ) {
  13074. Triangle.barycoordFromPoint( point, p1, p2, p3, barycoord );
  13075. uv1.multiplyScalar( barycoord.x );
  13076. uv2.multiplyScalar( barycoord.y );
  13077. uv3.multiplyScalar( barycoord.z );
  13078. uv1.add( uv2 ).add( uv3 );
  13079. return uv1.clone();
  13080. }
  13081. function checkIntersection( object, raycaster, ray, pA, pB, pC, point ) {
  13082. var intersect;
  13083. var material = object.material;
  13084. if ( material.side === BackSide ) {
  13085. intersect = ray.intersectTriangle( pC, pB, pA, true, point );
  13086. } else {
  13087. intersect = ray.intersectTriangle( pA, pB, pC, material.side !== DoubleSide, point );
  13088. }
  13089. if ( intersect === null ) return null;
  13090. intersectionPointWorld.copy( point );
  13091. intersectionPointWorld.applyMatrix4( object.matrixWorld );
  13092. var distance = raycaster.ray.origin.distanceTo( intersectionPointWorld );
  13093. if ( distance < raycaster.near || distance > raycaster.far ) return null;
  13094. return {
  13095. distance: distance,
  13096. point: intersectionPointWorld.clone(),
  13097. object: object
  13098. };
  13099. }
  13100. function checkBufferGeometryIntersection( object, raycaster, ray, positions, uvs, a, b, c ) {
  13101. vA.fromArray( positions, a * 3 );
  13102. vB.fromArray( positions, b * 3 );
  13103. vC.fromArray( positions, c * 3 );
  13104. var intersection = checkIntersection( object, raycaster, ray, vA, vB, vC, intersectionPoint );
  13105. if ( intersection ) {
  13106. if ( uvs ) {
  13107. uvA.fromArray( uvs, a * 2 );
  13108. uvB.fromArray( uvs, b * 2 );
  13109. uvC.fromArray( uvs, c * 2 );
  13110. intersection.uv = uvIntersection( intersectionPoint, vA, vB, vC, uvA, uvB, uvC );
  13111. }
  13112. intersection.face = new Face3( a, b, c, Triangle.normal( vA, vB, vC ) );
  13113. intersection.faceIndex = a;
  13114. }
  13115. return intersection;
  13116. }
  13117. return function raycast( raycaster, intersects ) {
  13118. var geometry = this.geometry;
  13119. var material = this.material;
  13120. var matrixWorld = this.matrixWorld;
  13121. if ( material === undefined ) return;
  13122. // Checking boundingSphere distance to ray
  13123. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  13124. sphere.copy( geometry.boundingSphere );
  13125. sphere.applyMatrix4( matrixWorld );
  13126. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  13127. //
  13128. inverseMatrix.getInverse( matrixWorld );
  13129. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  13130. // Check boundingBox before continuing
  13131. if ( geometry.boundingBox !== null ) {
  13132. if ( ray.intersectsBox( geometry.boundingBox ) === false ) return;
  13133. }
  13134. var uvs, intersection;
  13135. if ( geometry.isBufferGeometry ) {
  13136. var a, b, c;
  13137. var index = geometry.index;
  13138. var attributes = geometry.attributes;
  13139. var positions = attributes.position.array;
  13140. if ( attributes.uv !== undefined ) {
  13141. uvs = attributes.uv.array;
  13142. }
  13143. if ( index !== null ) {
  13144. var indices = index.array;
  13145. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  13146. a = indices[ i ];
  13147. b = indices[ i + 1 ];
  13148. c = indices[ i + 2 ];
  13149. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13150. if ( intersection ) {
  13151. intersection.faceIndex = Math.floor( i / 3 ); // triangle number in indices buffer semantics
  13152. intersects.push( intersection );
  13153. }
  13154. }
  13155. } else {
  13156. for ( var i = 0, l = positions.length; i < l; i += 9 ) {
  13157. a = i / 3;
  13158. b = a + 1;
  13159. c = a + 2;
  13160. intersection = checkBufferGeometryIntersection( this, raycaster, ray, positions, uvs, a, b, c );
  13161. if ( intersection ) {
  13162. intersection.index = a; // triangle number in positions buffer semantics
  13163. intersects.push( intersection );
  13164. }
  13165. }
  13166. }
  13167. } else if ( geometry.isGeometry ) {
  13168. var fvA, fvB, fvC;
  13169. var isFaceMaterial = (material && material.isMultiMaterial);
  13170. var materials = isFaceMaterial === true ? material.materials : null;
  13171. var vertices = geometry.vertices;
  13172. var faces = geometry.faces;
  13173. var faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  13174. if ( faceVertexUvs.length > 0 ) uvs = faceVertexUvs;
  13175. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  13176. var face = faces[ f ];
  13177. var faceMaterial = isFaceMaterial === true ? materials[ face.materialIndex ] : material;
  13178. if ( faceMaterial === undefined ) continue;
  13179. fvA = vertices[ face.a ];
  13180. fvB = vertices[ face.b ];
  13181. fvC = vertices[ face.c ];
  13182. if ( faceMaterial.morphTargets === true ) {
  13183. var morphTargets = geometry.morphTargets;
  13184. var morphInfluences = this.morphTargetInfluences;
  13185. vA.set( 0, 0, 0 );
  13186. vB.set( 0, 0, 0 );
  13187. vC.set( 0, 0, 0 );
  13188. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  13189. var influence = morphInfluences[ t ];
  13190. if ( influence === 0 ) continue;
  13191. var targets = morphTargets[ t ].vertices;
  13192. vA.addScaledVector( tempA.subVectors( targets[ face.a ], fvA ), influence );
  13193. vB.addScaledVector( tempB.subVectors( targets[ face.b ], fvB ), influence );
  13194. vC.addScaledVector( tempC.subVectors( targets[ face.c ], fvC ), influence );
  13195. }
  13196. vA.add( fvA );
  13197. vB.add( fvB );
  13198. vC.add( fvC );
  13199. fvA = vA;
  13200. fvB = vB;
  13201. fvC = vC;
  13202. }
  13203. intersection = checkIntersection( this, raycaster, ray, fvA, fvB, fvC, intersectionPoint );
  13204. if ( intersection ) {
  13205. if ( uvs ) {
  13206. var uvs_f = uvs[ f ];
  13207. uvA.copy( uvs_f[ 0 ] );
  13208. uvB.copy( uvs_f[ 1 ] );
  13209. uvC.copy( uvs_f[ 2 ] );
  13210. intersection.uv = uvIntersection( intersectionPoint, fvA, fvB, fvC, uvA, uvB, uvC );
  13211. }
  13212. intersection.face = face;
  13213. intersection.faceIndex = f;
  13214. intersects.push( intersection );
  13215. }
  13216. }
  13217. }
  13218. };
  13219. }() ),
  13220. clone: function () {
  13221. return new this.constructor( this.geometry, this.material ).copy( this );
  13222. }
  13223. } );
  13224. /**
  13225. * @author Mugen87 / https://github.com/Mugen87
  13226. */
  13227. function BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  13228. BufferGeometry.call( this );
  13229. this.type = 'BoxBufferGeometry';
  13230. this.parameters = {
  13231. width: width,
  13232. height: height,
  13233. depth: depth,
  13234. widthSegments: widthSegments,
  13235. heightSegments: heightSegments,
  13236. depthSegments: depthSegments
  13237. };
  13238. var scope = this;
  13239. // segments
  13240. widthSegments = Math.floor( widthSegments ) || 1;
  13241. heightSegments = Math.floor( heightSegments ) || 1;
  13242. depthSegments = Math.floor( depthSegments ) || 1;
  13243. // these are used to calculate buffer length
  13244. var vertexCount = calculateVertexCount( widthSegments, heightSegments, depthSegments );
  13245. var indexCount = calculateIndexCount( widthSegments, heightSegments, depthSegments );
  13246. // buffers
  13247. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  13248. var vertices = new Float32Array( vertexCount * 3 );
  13249. var normals = new Float32Array( vertexCount * 3 );
  13250. var uvs = new Float32Array( vertexCount * 2 );
  13251. // offset variables
  13252. var vertexBufferOffset = 0;
  13253. var uvBufferOffset = 0;
  13254. var indexBufferOffset = 0;
  13255. var numberOfVertices = 0;
  13256. // group variables
  13257. var groupStart = 0;
  13258. // build each side of the box geometry
  13259. buildPlane( 'z', 'y', 'x', - 1, - 1, depth, height, width, depthSegments, heightSegments, 0 ); // px
  13260. buildPlane( 'z', 'y', 'x', 1, - 1, depth, height, - width, depthSegments, heightSegments, 1 ); // nx
  13261. buildPlane( 'x', 'z', 'y', 1, 1, width, depth, height, widthSegments, depthSegments, 2 ); // py
  13262. buildPlane( 'x', 'z', 'y', 1, - 1, width, depth, - height, widthSegments, depthSegments, 3 ); // ny
  13263. buildPlane( 'x', 'y', 'z', 1, - 1, width, height, depth, widthSegments, heightSegments, 4 ); // pz
  13264. buildPlane( 'x', 'y', 'z', - 1, - 1, width, height, - depth, widthSegments, heightSegments, 5 ); // nz
  13265. // build geometry
  13266. this.setIndex( new BufferAttribute( indices, 1 ) );
  13267. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  13268. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  13269. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  13270. // helper functions
  13271. function calculateVertexCount( w, h, d ) {
  13272. var vertices = 0;
  13273. // calculate the amount of vertices for each side (plane)
  13274. vertices += (w + 1) * (h + 1) * 2; // xy
  13275. vertices += (w + 1) * (d + 1) * 2; // xz
  13276. vertices += (d + 1) * (h + 1) * 2; // zy
  13277. return vertices;
  13278. }
  13279. function calculateIndexCount( w, h, d ) {
  13280. var index = 0;
  13281. // calculate the amount of squares for each side
  13282. index += w * h * 2; // xy
  13283. index += w * d * 2; // xz
  13284. index += d * h * 2; // zy
  13285. return index * 6; // two triangles per square => six vertices per square
  13286. }
  13287. function buildPlane( u, v, w, udir, vdir, width, height, depth, gridX, gridY, materialIndex ) {
  13288. var segmentWidth = width / gridX;
  13289. var segmentHeight = height / gridY;
  13290. var widthHalf = width / 2;
  13291. var heightHalf = height / 2;
  13292. var depthHalf = depth / 2;
  13293. var gridX1 = gridX + 1;
  13294. var gridY1 = gridY + 1;
  13295. var vertexCounter = 0;
  13296. var groupCount = 0;
  13297. var vector = new Vector3();
  13298. // generate vertices, normals and uvs
  13299. for ( var iy = 0; iy < gridY1; iy ++ ) {
  13300. var y = iy * segmentHeight - heightHalf;
  13301. for ( var ix = 0; ix < gridX1; ix ++ ) {
  13302. var x = ix * segmentWidth - widthHalf;
  13303. // set values to correct vector component
  13304. vector[ u ] = x * udir;
  13305. vector[ v ] = y * vdir;
  13306. vector[ w ] = depthHalf;
  13307. // now apply vector to vertex buffer
  13308. vertices[ vertexBufferOffset ] = vector.x;
  13309. vertices[ vertexBufferOffset + 1 ] = vector.y;
  13310. vertices[ vertexBufferOffset + 2 ] = vector.z;
  13311. // set values to correct vector component
  13312. vector[ u ] = 0;
  13313. vector[ v ] = 0;
  13314. vector[ w ] = depth > 0 ? 1 : - 1;
  13315. // now apply vector to normal buffer
  13316. normals[ vertexBufferOffset ] = vector.x;
  13317. normals[ vertexBufferOffset + 1 ] = vector.y;
  13318. normals[ vertexBufferOffset + 2 ] = vector.z;
  13319. // uvs
  13320. uvs[ uvBufferOffset ] = ix / gridX;
  13321. uvs[ uvBufferOffset + 1 ] = 1 - ( iy / gridY );
  13322. // update offsets and counters
  13323. vertexBufferOffset += 3;
  13324. uvBufferOffset += 2;
  13325. vertexCounter += 1;
  13326. }
  13327. }
  13328. // 1. you need three indices to draw a single face
  13329. // 2. a single segment consists of two faces
  13330. // 3. so we need to generate six (2*3) indices per segment
  13331. for ( iy = 0; iy < gridY; iy ++ ) {
  13332. for ( ix = 0; ix < gridX; ix ++ ) {
  13333. // indices
  13334. var a = numberOfVertices + ix + gridX1 * iy;
  13335. var b = numberOfVertices + ix + gridX1 * ( iy + 1 );
  13336. var c = numberOfVertices + ( ix + 1 ) + gridX1 * ( iy + 1 );
  13337. var d = numberOfVertices + ( ix + 1 ) + gridX1 * iy;
  13338. // face one
  13339. indices[ indexBufferOffset ] = a;
  13340. indices[ indexBufferOffset + 1 ] = b;
  13341. indices[ indexBufferOffset + 2 ] = d;
  13342. // face two
  13343. indices[ indexBufferOffset + 3 ] = b;
  13344. indices[ indexBufferOffset + 4 ] = c;
  13345. indices[ indexBufferOffset + 5 ] = d;
  13346. // update offsets and counters
  13347. indexBufferOffset += 6;
  13348. groupCount += 6;
  13349. }
  13350. }
  13351. // add a group to the geometry. this will ensure multi material support
  13352. scope.addGroup( groupStart, groupCount, materialIndex );
  13353. // calculate new start value for groups
  13354. groupStart += groupCount;
  13355. // update total number of vertices
  13356. numberOfVertices += vertexCounter;
  13357. }
  13358. }
  13359. BoxBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13360. BoxBufferGeometry.prototype.constructor = BoxBufferGeometry;
  13361. /**
  13362. * @author mrdoob / http://mrdoob.com/
  13363. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  13364. */
  13365. function PlaneBufferGeometry( width, height, widthSegments, heightSegments ) {
  13366. BufferGeometry.call( this );
  13367. this.type = 'PlaneBufferGeometry';
  13368. this.parameters = {
  13369. width: width,
  13370. height: height,
  13371. widthSegments: widthSegments,
  13372. heightSegments: heightSegments
  13373. };
  13374. var width_half = width / 2;
  13375. var height_half = height / 2;
  13376. var gridX = Math.floor( widthSegments ) || 1;
  13377. var gridY = Math.floor( heightSegments ) || 1;
  13378. var gridX1 = gridX + 1;
  13379. var gridY1 = gridY + 1;
  13380. var segment_width = width / gridX;
  13381. var segment_height = height / gridY;
  13382. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  13383. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  13384. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  13385. var offset = 0;
  13386. var offset2 = 0;
  13387. for ( var iy = 0; iy < gridY1; iy ++ ) {
  13388. var y = iy * segment_height - height_half;
  13389. for ( var ix = 0; ix < gridX1; ix ++ ) {
  13390. var x = ix * segment_width - width_half;
  13391. vertices[ offset ] = x;
  13392. vertices[ offset + 1 ] = - y;
  13393. normals[ offset + 2 ] = 1;
  13394. uvs[ offset2 ] = ix / gridX;
  13395. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  13396. offset += 3;
  13397. offset2 += 2;
  13398. }
  13399. }
  13400. offset = 0;
  13401. var indices = new ( ( vertices.length / 3 ) > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  13402. for ( var iy = 0; iy < gridY; iy ++ ) {
  13403. for ( var ix = 0; ix < gridX; ix ++ ) {
  13404. var a = ix + gridX1 * iy;
  13405. var b = ix + gridX1 * ( iy + 1 );
  13406. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  13407. var d = ( ix + 1 ) + gridX1 * iy;
  13408. indices[ offset ] = a;
  13409. indices[ offset + 1 ] = b;
  13410. indices[ offset + 2 ] = d;
  13411. indices[ offset + 3 ] = b;
  13412. indices[ offset + 4 ] = c;
  13413. indices[ offset + 5 ] = d;
  13414. offset += 6;
  13415. }
  13416. }
  13417. this.setIndex( new BufferAttribute( indices, 1 ) );
  13418. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  13419. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  13420. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  13421. }
  13422. PlaneBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  13423. PlaneBufferGeometry.prototype.constructor = PlaneBufferGeometry;
  13424. /**
  13425. * @author mrdoob / http://mrdoob.com/
  13426. * @author mikael emtinger / http://gomo.se/
  13427. * @author WestLangley / http://github.com/WestLangley
  13428. */
  13429. function Camera() {
  13430. Object3D.call( this );
  13431. this.type = 'Camera';
  13432. this.matrixWorldInverse = new Matrix4();
  13433. this.projectionMatrix = new Matrix4();
  13434. }
  13435. Camera.prototype = Object.create( Object3D.prototype );
  13436. Camera.prototype.constructor = Camera;
  13437. Camera.prototype.isCamera = true;
  13438. Camera.prototype.getWorldDirection = function () {
  13439. var quaternion = new Quaternion();
  13440. return function getWorldDirection( optionalTarget ) {
  13441. var result = optionalTarget || new Vector3();
  13442. this.getWorldQuaternion( quaternion );
  13443. return result.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  13444. };
  13445. }();
  13446. Camera.prototype.lookAt = function () {
  13447. // This routine does not support cameras with rotated and/or translated parent(s)
  13448. var m1 = new Matrix4();
  13449. return function lookAt( vector ) {
  13450. m1.lookAt( this.position, vector, this.up );
  13451. this.quaternion.setFromRotationMatrix( m1 );
  13452. };
  13453. }();
  13454. Camera.prototype.clone = function () {
  13455. return new this.constructor().copy( this );
  13456. };
  13457. Camera.prototype.copy = function ( source ) {
  13458. Object3D.prototype.copy.call( this, source );
  13459. this.matrixWorldInverse.copy( source.matrixWorldInverse );
  13460. this.projectionMatrix.copy( source.projectionMatrix );
  13461. return this;
  13462. };
  13463. /**
  13464. * @author mrdoob / http://mrdoob.com/
  13465. * @author greggman / http://games.greggman.com/
  13466. * @author zz85 / http://www.lab4games.net/zz85/blog
  13467. * @author tschw
  13468. */
  13469. function PerspectiveCamera( fov, aspect, near, far ) {
  13470. Camera.call( this );
  13471. this.type = 'PerspectiveCamera';
  13472. this.fov = fov !== undefined ? fov : 50;
  13473. this.zoom = 1;
  13474. this.near = near !== undefined ? near : 0.1;
  13475. this.far = far !== undefined ? far : 2000;
  13476. this.focus = 10;
  13477. this.aspect = aspect !== undefined ? aspect : 1;
  13478. this.view = null;
  13479. this.filmGauge = 35; // width of the film (default in millimeters)
  13480. this.filmOffset = 0; // horizontal film offset (same unit as gauge)
  13481. this.updateProjectionMatrix();
  13482. }
  13483. PerspectiveCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13484. constructor: PerspectiveCamera,
  13485. isPerspectiveCamera: true,
  13486. copy: function ( source ) {
  13487. Camera.prototype.copy.call( this, source );
  13488. this.fov = source.fov;
  13489. this.zoom = source.zoom;
  13490. this.near = source.near;
  13491. this.far = source.far;
  13492. this.focus = source.focus;
  13493. this.aspect = source.aspect;
  13494. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13495. this.filmGauge = source.filmGauge;
  13496. this.filmOffset = source.filmOffset;
  13497. return this;
  13498. },
  13499. /**
  13500. * Sets the FOV by focal length in respect to the current .filmGauge.
  13501. *
  13502. * The default film gauge is 35, so that the focal length can be specified for
  13503. * a 35mm (full frame) camera.
  13504. *
  13505. * Values for focal length and film gauge must have the same unit.
  13506. */
  13507. setFocalLength: function ( focalLength ) {
  13508. // see http://www.bobatkins.com/photography/technical/field_of_view.html
  13509. var vExtentSlope = 0.5 * this.getFilmHeight() / focalLength;
  13510. this.fov = _Math.RAD2DEG * 2 * Math.atan( vExtentSlope );
  13511. this.updateProjectionMatrix();
  13512. },
  13513. /**
  13514. * Calculates the focal length from the current .fov and .filmGauge.
  13515. */
  13516. getFocalLength: function () {
  13517. var vExtentSlope = Math.tan( _Math.DEG2RAD * 0.5 * this.fov );
  13518. return 0.5 * this.getFilmHeight() / vExtentSlope;
  13519. },
  13520. getEffectiveFOV: function () {
  13521. return _Math.RAD2DEG * 2 * Math.atan(
  13522. Math.tan( _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom );
  13523. },
  13524. getFilmWidth: function () {
  13525. // film not completely covered in portrait format (aspect < 1)
  13526. return this.filmGauge * Math.min( this.aspect, 1 );
  13527. },
  13528. getFilmHeight: function () {
  13529. // film not completely covered in landscape format (aspect > 1)
  13530. return this.filmGauge / Math.max( this.aspect, 1 );
  13531. },
  13532. /**
  13533. * Sets an offset in a larger frustum. This is useful for multi-window or
  13534. * multi-monitor/multi-machine setups.
  13535. *
  13536. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  13537. * the monitors are in grid like this
  13538. *
  13539. * +---+---+---+
  13540. * | A | B | C |
  13541. * +---+---+---+
  13542. * | D | E | F |
  13543. * +---+---+---+
  13544. *
  13545. * then for each monitor you would call it like this
  13546. *
  13547. * var w = 1920;
  13548. * var h = 1080;
  13549. * var fullWidth = w * 3;
  13550. * var fullHeight = h * 2;
  13551. *
  13552. * --A--
  13553. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  13554. * --B--
  13555. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  13556. * --C--
  13557. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  13558. * --D--
  13559. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  13560. * --E--
  13561. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  13562. * --F--
  13563. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  13564. *
  13565. * Note there is no reason monitors have to be the same size or in a grid.
  13566. */
  13567. setViewOffset: function ( fullWidth, fullHeight, x, y, width, height ) {
  13568. this.aspect = fullWidth / fullHeight;
  13569. this.view = {
  13570. fullWidth: fullWidth,
  13571. fullHeight: fullHeight,
  13572. offsetX: x,
  13573. offsetY: y,
  13574. width: width,
  13575. height: height
  13576. };
  13577. this.updateProjectionMatrix();
  13578. },
  13579. clearViewOffset: function() {
  13580. this.view = null;
  13581. this.updateProjectionMatrix();
  13582. },
  13583. updateProjectionMatrix: function () {
  13584. var near = this.near,
  13585. top = near * Math.tan(
  13586. _Math.DEG2RAD * 0.5 * this.fov ) / this.zoom,
  13587. height = 2 * top,
  13588. width = this.aspect * height,
  13589. left = - 0.5 * width,
  13590. view = this.view;
  13591. if ( view !== null ) {
  13592. var fullWidth = view.fullWidth,
  13593. fullHeight = view.fullHeight;
  13594. left += view.offsetX * width / fullWidth;
  13595. top -= view.offsetY * height / fullHeight;
  13596. width *= view.width / fullWidth;
  13597. height *= view.height / fullHeight;
  13598. }
  13599. var skew = this.filmOffset;
  13600. if ( skew !== 0 ) left += near * skew / this.getFilmWidth();
  13601. this.projectionMatrix.makeFrustum(
  13602. left, left + width, top - height, top, near, this.far );
  13603. },
  13604. toJSON: function ( meta ) {
  13605. var data = Object3D.prototype.toJSON.call( this, meta );
  13606. data.object.fov = this.fov;
  13607. data.object.zoom = this.zoom;
  13608. data.object.near = this.near;
  13609. data.object.far = this.far;
  13610. data.object.focus = this.focus;
  13611. data.object.aspect = this.aspect;
  13612. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  13613. data.object.filmGauge = this.filmGauge;
  13614. data.object.filmOffset = this.filmOffset;
  13615. return data;
  13616. }
  13617. } );
  13618. /**
  13619. * @author alteredq / http://alteredqualia.com/
  13620. * @author arose / http://github.com/arose
  13621. */
  13622. function OrthographicCamera( left, right, top, bottom, near, far ) {
  13623. Camera.call( this );
  13624. this.type = 'OrthographicCamera';
  13625. this.zoom = 1;
  13626. this.view = null;
  13627. this.left = left;
  13628. this.right = right;
  13629. this.top = top;
  13630. this.bottom = bottom;
  13631. this.near = ( near !== undefined ) ? near : 0.1;
  13632. this.far = ( far !== undefined ) ? far : 2000;
  13633. this.updateProjectionMatrix();
  13634. }
  13635. OrthographicCamera.prototype = Object.assign( Object.create( Camera.prototype ), {
  13636. constructor: OrthographicCamera,
  13637. isOrthographicCamera: true,
  13638. copy: function ( source ) {
  13639. Camera.prototype.copy.call( this, source );
  13640. this.left = source.left;
  13641. this.right = source.right;
  13642. this.top = source.top;
  13643. this.bottom = source.bottom;
  13644. this.near = source.near;
  13645. this.far = source.far;
  13646. this.zoom = source.zoom;
  13647. this.view = source.view === null ? null : Object.assign( {}, source.view );
  13648. return this;
  13649. },
  13650. setViewOffset: function( fullWidth, fullHeight, x, y, width, height ) {
  13651. this.view = {
  13652. fullWidth: fullWidth,
  13653. fullHeight: fullHeight,
  13654. offsetX: x,
  13655. offsetY: y,
  13656. width: width,
  13657. height: height
  13658. };
  13659. this.updateProjectionMatrix();
  13660. },
  13661. clearViewOffset: function() {
  13662. this.view = null;
  13663. this.updateProjectionMatrix();
  13664. },
  13665. updateProjectionMatrix: function () {
  13666. var dx = ( this.right - this.left ) / ( 2 * this.zoom );
  13667. var dy = ( this.top - this.bottom ) / ( 2 * this.zoom );
  13668. var cx = ( this.right + this.left ) / 2;
  13669. var cy = ( this.top + this.bottom ) / 2;
  13670. var left = cx - dx;
  13671. var right = cx + dx;
  13672. var top = cy + dy;
  13673. var bottom = cy - dy;
  13674. if ( this.view !== null ) {
  13675. var zoomW = this.zoom / ( this.view.width / this.view.fullWidth );
  13676. var zoomH = this.zoom / ( this.view.height / this.view.fullHeight );
  13677. var scaleW = ( this.right - this.left ) / this.view.width;
  13678. var scaleH = ( this.top - this.bottom ) / this.view.height;
  13679. left += scaleW * ( this.view.offsetX / zoomW );
  13680. right = left + scaleW * ( this.view.width / zoomW );
  13681. top -= scaleH * ( this.view.offsetY / zoomH );
  13682. bottom = top - scaleH * ( this.view.height / zoomH );
  13683. }
  13684. this.projectionMatrix.makeOrthographic( left, right, top, bottom, this.near, this.far );
  13685. },
  13686. toJSON: function ( meta ) {
  13687. var data = Object3D.prototype.toJSON.call( this, meta );
  13688. data.object.zoom = this.zoom;
  13689. data.object.left = this.left;
  13690. data.object.right = this.right;
  13691. data.object.top = this.top;
  13692. data.object.bottom = this.bottom;
  13693. data.object.near = this.near;
  13694. data.object.far = this.far;
  13695. if ( this.view !== null ) data.object.view = Object.assign( {}, this.view );
  13696. return data;
  13697. }
  13698. } );
  13699. /**
  13700. * @author mrdoob / http://mrdoob.com/
  13701. */
  13702. function WebGLIndexedBufferRenderer( gl, extensions, infoRender ) {
  13703. var mode;
  13704. function setMode( value ) {
  13705. mode = value;
  13706. }
  13707. var type, size;
  13708. function setIndex( index ) {
  13709. if ( index.array instanceof Uint32Array && extensions.get( 'OES_element_index_uint' ) ) {
  13710. type = gl.UNSIGNED_INT;
  13711. size = 4;
  13712. } else if ( index.array instanceof Uint16Array ) {
  13713. type = gl.UNSIGNED_SHORT;
  13714. size = 2;
  13715. } else {
  13716. type = gl.UNSIGNED_BYTE;
  13717. size = 1;
  13718. }
  13719. }
  13720. function render( start, count ) {
  13721. gl.drawElements( mode, count, type, start * size );
  13722. infoRender.calls ++;
  13723. infoRender.vertices += count;
  13724. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  13725. }
  13726. function renderInstances( geometry, start, count ) {
  13727. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13728. if ( extension === null ) {
  13729. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13730. return;
  13731. }
  13732. extension.drawElementsInstancedANGLE( mode, count, type, start * size, geometry.maxInstancedCount );
  13733. infoRender.calls ++;
  13734. infoRender.vertices += count * geometry.maxInstancedCount;
  13735. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  13736. }
  13737. return {
  13738. setMode: setMode,
  13739. setIndex: setIndex,
  13740. render: render,
  13741. renderInstances: renderInstances
  13742. };
  13743. }
  13744. /**
  13745. * @author mrdoob / http://mrdoob.com/
  13746. */
  13747. function WebGLBufferRenderer( gl, extensions, infoRender ) {
  13748. var mode;
  13749. function setMode( value ) {
  13750. mode = value;
  13751. }
  13752. function render( start, count ) {
  13753. gl.drawArrays( mode, start, count );
  13754. infoRender.calls ++;
  13755. infoRender.vertices += count;
  13756. if ( mode === gl.TRIANGLES ) infoRender.faces += count / 3;
  13757. }
  13758. function renderInstances( geometry ) {
  13759. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  13760. if ( extension === null ) {
  13761. console.error( 'THREE.WebGLBufferRenderer: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  13762. return;
  13763. }
  13764. var position = geometry.attributes.position;
  13765. var count = 0;
  13766. if ( position.isInterleavedBufferAttribute ) {
  13767. count = position.data.count;
  13768. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  13769. } else {
  13770. count = position.count;
  13771. extension.drawArraysInstancedANGLE( mode, 0, count, geometry.maxInstancedCount );
  13772. }
  13773. infoRender.calls ++;
  13774. infoRender.vertices += count * geometry.maxInstancedCount;
  13775. if ( mode === gl.TRIANGLES ) infoRender.faces += geometry.maxInstancedCount * count / 3;
  13776. }
  13777. return {
  13778. setMode: setMode,
  13779. render: render,
  13780. renderInstances: renderInstances
  13781. };
  13782. }
  13783. /**
  13784. * @author mrdoob / http://mrdoob.com/
  13785. */
  13786. function WebGLLights() {
  13787. var lights = {};
  13788. return {
  13789. get: function ( light ) {
  13790. if ( lights[ light.id ] !== undefined ) {
  13791. return lights[ light.id ];
  13792. }
  13793. var uniforms;
  13794. switch ( light.type ) {
  13795. case 'DirectionalLight':
  13796. uniforms = {
  13797. direction: new Vector3(),
  13798. color: new Color(),
  13799. shadow: false,
  13800. shadowBias: 0,
  13801. shadowRadius: 1,
  13802. shadowMapSize: new Vector2()
  13803. };
  13804. break;
  13805. case 'SpotLight':
  13806. uniforms = {
  13807. position: new Vector3(),
  13808. direction: new Vector3(),
  13809. color: new Color(),
  13810. distance: 0,
  13811. coneCos: 0,
  13812. penumbraCos: 0,
  13813. decay: 0,
  13814. shadow: false,
  13815. shadowBias: 0,
  13816. shadowRadius: 1,
  13817. shadowMapSize: new Vector2()
  13818. };
  13819. break;
  13820. case 'PointLight':
  13821. uniforms = {
  13822. position: new Vector3(),
  13823. color: new Color(),
  13824. distance: 0,
  13825. decay: 0,
  13826. shadow: false,
  13827. shadowBias: 0,
  13828. shadowRadius: 1,
  13829. shadowMapSize: new Vector2()
  13830. };
  13831. break;
  13832. case 'HemisphereLight':
  13833. uniforms = {
  13834. direction: new Vector3(),
  13835. skyColor: new Color(),
  13836. groundColor: new Color()
  13837. };
  13838. break;
  13839. case 'RectAreaLight':
  13840. uniforms = {
  13841. color: new Color(),
  13842. position: new Vector3(),
  13843. halfWidth: new Vector3(),
  13844. halfHeight: new Vector3()
  13845. // TODO (abelnation): set RectAreaLight shadow uniforms
  13846. };
  13847. break;
  13848. }
  13849. lights[ light.id ] = uniforms;
  13850. return uniforms;
  13851. }
  13852. };
  13853. }
  13854. /**
  13855. * @author mrdoob / http://mrdoob.com/
  13856. */
  13857. function addLineNumbers( string ) {
  13858. var lines = string.split( '\n' );
  13859. for ( var i = 0; i < lines.length; i ++ ) {
  13860. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  13861. }
  13862. return lines.join( '\n' );
  13863. }
  13864. function WebGLShader( gl, type, string ) {
  13865. var shader = gl.createShader( type );
  13866. gl.shaderSource( shader, string );
  13867. gl.compileShader( shader );
  13868. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  13869. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  13870. }
  13871. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  13872. console.warn( 'THREE.WebGLShader: gl.getShaderInfoLog()', type === gl.VERTEX_SHADER ? 'vertex' : 'fragment', gl.getShaderInfoLog( shader ), addLineNumbers( string ) );
  13873. }
  13874. // --enable-privileged-webgl-extension
  13875. // console.log( type, gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( shader ) );
  13876. return shader;
  13877. }
  13878. /**
  13879. * @author mrdoob / http://mrdoob.com/
  13880. */
  13881. var programIdCount = 0;
  13882. function getEncodingComponents( encoding ) {
  13883. switch ( encoding ) {
  13884. case LinearEncoding:
  13885. return [ 'Linear','( value )' ];
  13886. case sRGBEncoding:
  13887. return [ 'sRGB','( value )' ];
  13888. case RGBEEncoding:
  13889. return [ 'RGBE','( value )' ];
  13890. case RGBM7Encoding:
  13891. return [ 'RGBM','( value, 7.0 )' ];
  13892. case RGBM16Encoding:
  13893. return [ 'RGBM','( value, 16.0 )' ];
  13894. case RGBDEncoding:
  13895. return [ 'RGBD','( value, 256.0 )' ];
  13896. case GammaEncoding:
  13897. return [ 'Gamma','( value, float( GAMMA_FACTOR ) )' ];
  13898. default:
  13899. throw new Error( 'unsupported encoding: ' + encoding );
  13900. }
  13901. }
  13902. function getTexelDecodingFunction( functionName, encoding ) {
  13903. var components = getEncodingComponents( encoding );
  13904. return "vec4 " + functionName + "( vec4 value ) { return " + components[ 0 ] + "ToLinear" + components[ 1 ] + "; }";
  13905. }
  13906. function getTexelEncodingFunction( functionName, encoding ) {
  13907. var components = getEncodingComponents( encoding );
  13908. return "vec4 " + functionName + "( vec4 value ) { return LinearTo" + components[ 0 ] + components[ 1 ] + "; }";
  13909. }
  13910. function getToneMappingFunction( functionName, toneMapping ) {
  13911. var toneMappingName;
  13912. switch ( toneMapping ) {
  13913. case LinearToneMapping:
  13914. toneMappingName = "Linear";
  13915. break;
  13916. case ReinhardToneMapping:
  13917. toneMappingName = "Reinhard";
  13918. break;
  13919. case Uncharted2ToneMapping:
  13920. toneMappingName = "Uncharted2";
  13921. break;
  13922. case CineonToneMapping:
  13923. toneMappingName = "OptimizedCineon";
  13924. break;
  13925. default:
  13926. throw new Error( 'unsupported toneMapping: ' + toneMapping );
  13927. }
  13928. return "vec3 " + functionName + "( vec3 color ) { return " + toneMappingName + "ToneMapping( color ); }";
  13929. }
  13930. function generateExtensions( extensions, parameters, rendererExtensions ) {
  13931. extensions = extensions || {};
  13932. var chunks = [
  13933. ( extensions.derivatives || parameters.envMapCubeUV || parameters.bumpMap || parameters.normalMap || parameters.flatShading ) ? '#extension GL_OES_standard_derivatives : enable' : '',
  13934. ( extensions.fragDepth || parameters.logarithmicDepthBuffer ) && rendererExtensions.get( 'EXT_frag_depth' ) ? '#extension GL_EXT_frag_depth : enable' : '',
  13935. ( extensions.drawBuffers ) && rendererExtensions.get( 'WEBGL_draw_buffers' ) ? '#extension GL_EXT_draw_buffers : require' : '',
  13936. ( extensions.shaderTextureLOD || parameters.envMap ) && rendererExtensions.get( 'EXT_shader_texture_lod' ) ? '#extension GL_EXT_shader_texture_lod : enable' : ''
  13937. ];
  13938. return chunks.filter( filterEmptyLine ).join( '\n' );
  13939. }
  13940. function generateDefines( defines ) {
  13941. var chunks = [];
  13942. for ( var name in defines ) {
  13943. var value = defines[ name ];
  13944. if ( value === false ) continue;
  13945. chunks.push( '#define ' + name + ' ' + value );
  13946. }
  13947. return chunks.join( '\n' );
  13948. }
  13949. function fetchAttributeLocations( gl, program, identifiers ) {
  13950. var attributes = {};
  13951. var n = gl.getProgramParameter( program, gl.ACTIVE_ATTRIBUTES );
  13952. for ( var i = 0; i < n; i ++ ) {
  13953. var info = gl.getActiveAttrib( program, i );
  13954. var name = info.name;
  13955. // console.log("THREE.WebGLProgram: ACTIVE VERTEX ATTRIBUTE:", name, i );
  13956. attributes[ name ] = gl.getAttribLocation( program, name );
  13957. }
  13958. return attributes;
  13959. }
  13960. function filterEmptyLine( string ) {
  13961. return string !== '';
  13962. }
  13963. function replaceLightNums( string, parameters ) {
  13964. return string
  13965. .replace( /NUM_DIR_LIGHTS/g, parameters.numDirLights )
  13966. .replace( /NUM_SPOT_LIGHTS/g, parameters.numSpotLights )
  13967. .replace( /NUM_RECT_AREA_LIGHTS/g, parameters.numRectAreaLights )
  13968. .replace( /NUM_POINT_LIGHTS/g, parameters.numPointLights )
  13969. .replace( /NUM_HEMI_LIGHTS/g, parameters.numHemiLights );
  13970. }
  13971. function parseIncludes( string ) {
  13972. var pattern = /#include +<([\w\d.]+)>/g;
  13973. function replace( match, include ) {
  13974. var replace = ShaderChunk[ include ];
  13975. if ( replace === undefined ) {
  13976. throw new Error( 'Can not resolve #include <' + include + '>' );
  13977. }
  13978. return parseIncludes( replace );
  13979. }
  13980. return string.replace( pattern, replace );
  13981. }
  13982. function unrollLoops( string ) {
  13983. var pattern = /for \( int i \= (\d+)\; i < (\d+)\; i \+\+ \) \{([\s\S]+?)(?=\})\}/g;
  13984. function replace( match, start, end, snippet ) {
  13985. var unroll = '';
  13986. for ( var i = parseInt( start ); i < parseInt( end ); i ++ ) {
  13987. unroll += snippet.replace( /\[ i \]/g, '[ ' + i + ' ]' );
  13988. }
  13989. return unroll;
  13990. }
  13991. return string.replace( pattern, replace );
  13992. }
  13993. function WebGLProgram( renderer, code, material, parameters ) {
  13994. var gl = renderer.context;
  13995. var extensions = material.extensions;
  13996. var defines = material.defines;
  13997. var vertexShader = material.__webglShader.vertexShader;
  13998. var fragmentShader = material.__webglShader.fragmentShader;
  13999. var shadowMapTypeDefine = 'SHADOWMAP_TYPE_BASIC';
  14000. if ( parameters.shadowMapType === PCFShadowMap ) {
  14001. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF';
  14002. } else if ( parameters.shadowMapType === PCFSoftShadowMap ) {
  14003. shadowMapTypeDefine = 'SHADOWMAP_TYPE_PCF_SOFT';
  14004. }
  14005. var envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14006. var envMapModeDefine = 'ENVMAP_MODE_REFLECTION';
  14007. var envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14008. if ( parameters.envMap ) {
  14009. switch ( material.envMap.mapping ) {
  14010. case CubeReflectionMapping:
  14011. case CubeRefractionMapping:
  14012. envMapTypeDefine = 'ENVMAP_TYPE_CUBE';
  14013. break;
  14014. case CubeUVReflectionMapping:
  14015. case CubeUVRefractionMapping:
  14016. envMapTypeDefine = 'ENVMAP_TYPE_CUBE_UV';
  14017. break;
  14018. case EquirectangularReflectionMapping:
  14019. case EquirectangularRefractionMapping:
  14020. envMapTypeDefine = 'ENVMAP_TYPE_EQUIREC';
  14021. break;
  14022. case SphericalReflectionMapping:
  14023. envMapTypeDefine = 'ENVMAP_TYPE_SPHERE';
  14024. break;
  14025. }
  14026. switch ( material.envMap.mapping ) {
  14027. case CubeRefractionMapping:
  14028. case EquirectangularRefractionMapping:
  14029. envMapModeDefine = 'ENVMAP_MODE_REFRACTION';
  14030. break;
  14031. }
  14032. switch ( material.combine ) {
  14033. case MultiplyOperation:
  14034. envMapBlendingDefine = 'ENVMAP_BLENDING_MULTIPLY';
  14035. break;
  14036. case MixOperation:
  14037. envMapBlendingDefine = 'ENVMAP_BLENDING_MIX';
  14038. break;
  14039. case AddOperation:
  14040. envMapBlendingDefine = 'ENVMAP_BLENDING_ADD';
  14041. break;
  14042. }
  14043. }
  14044. var gammaFactorDefine = ( renderer.gammaFactor > 0 ) ? renderer.gammaFactor : 1.0;
  14045. // console.log( 'building new program ' );
  14046. //
  14047. var customExtensions = generateExtensions( extensions, parameters, renderer.extensions );
  14048. var customDefines = generateDefines( defines );
  14049. //
  14050. var program = gl.createProgram();
  14051. var prefixVertex, prefixFragment;
  14052. if ( material.isRawShaderMaterial ) {
  14053. prefixVertex = [
  14054. customDefines,
  14055. '\n'
  14056. ].filter( filterEmptyLine ).join( '\n' );
  14057. prefixFragment = [
  14058. customExtensions,
  14059. customDefines,
  14060. '\n'
  14061. ].filter( filterEmptyLine ).join( '\n' );
  14062. } else {
  14063. prefixVertex = [
  14064. 'precision ' + parameters.precision + ' float;',
  14065. 'precision ' + parameters.precision + ' int;',
  14066. '#define SHADER_NAME ' + material.__webglShader.name,
  14067. customDefines,
  14068. parameters.supportsVertexTextures ? '#define VERTEX_TEXTURES' : '',
  14069. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14070. '#define MAX_BONES ' + parameters.maxBones,
  14071. parameters.map ? '#define USE_MAP' : '',
  14072. parameters.envMap ? '#define USE_ENVMAP' : '',
  14073. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14074. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14075. parameters.aoMap ? '#define USE_AOMAP' : '',
  14076. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14077. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14078. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14079. parameters.displacementMap && parameters.supportsVertexTextures ? '#define USE_DISPLACEMENTMAP' : '',
  14080. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14081. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14082. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14083. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14084. parameters.vertexColors ? '#define USE_COLOR' : '',
  14085. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14086. parameters.skinning ? '#define USE_SKINNING' : '',
  14087. parameters.useVertexTexture ? '#define BONE_TEXTURE' : '',
  14088. parameters.morphTargets ? '#define USE_MORPHTARGETS' : '',
  14089. parameters.morphNormals && parameters.flatShading === false ? '#define USE_MORPHNORMALS' : '',
  14090. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14091. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14092. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14093. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14094. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14095. parameters.sizeAttenuation ? '#define USE_SIZEATTENUATION' : '',
  14096. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14097. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14098. 'uniform mat4 modelMatrix;',
  14099. 'uniform mat4 modelViewMatrix;',
  14100. 'uniform mat4 projectionMatrix;',
  14101. 'uniform mat4 viewMatrix;',
  14102. 'uniform mat3 normalMatrix;',
  14103. 'uniform vec3 cameraPosition;',
  14104. 'attribute vec3 position;',
  14105. 'attribute vec3 normal;',
  14106. 'attribute vec2 uv;',
  14107. '#ifdef USE_COLOR',
  14108. ' attribute vec3 color;',
  14109. '#endif',
  14110. '#ifdef USE_MORPHTARGETS',
  14111. ' attribute vec3 morphTarget0;',
  14112. ' attribute vec3 morphTarget1;',
  14113. ' attribute vec3 morphTarget2;',
  14114. ' attribute vec3 morphTarget3;',
  14115. ' #ifdef USE_MORPHNORMALS',
  14116. ' attribute vec3 morphNormal0;',
  14117. ' attribute vec3 morphNormal1;',
  14118. ' attribute vec3 morphNormal2;',
  14119. ' attribute vec3 morphNormal3;',
  14120. ' #else',
  14121. ' attribute vec3 morphTarget4;',
  14122. ' attribute vec3 morphTarget5;',
  14123. ' attribute vec3 morphTarget6;',
  14124. ' attribute vec3 morphTarget7;',
  14125. ' #endif',
  14126. '#endif',
  14127. '#ifdef USE_SKINNING',
  14128. ' attribute vec4 skinIndex;',
  14129. ' attribute vec4 skinWeight;',
  14130. '#endif',
  14131. '\n'
  14132. ].filter( filterEmptyLine ).join( '\n' );
  14133. prefixFragment = [
  14134. customExtensions,
  14135. 'precision ' + parameters.precision + ' float;',
  14136. 'precision ' + parameters.precision + ' int;',
  14137. '#define SHADER_NAME ' + material.__webglShader.name,
  14138. customDefines,
  14139. parameters.alphaTest ? '#define ALPHATEST ' + parameters.alphaTest : '',
  14140. '#define GAMMA_FACTOR ' + gammaFactorDefine,
  14141. ( parameters.useFog && parameters.fog ) ? '#define USE_FOG' : '',
  14142. ( parameters.useFog && parameters.fogExp ) ? '#define FOG_EXP2' : '',
  14143. parameters.map ? '#define USE_MAP' : '',
  14144. parameters.envMap ? '#define USE_ENVMAP' : '',
  14145. parameters.envMap ? '#define ' + envMapTypeDefine : '',
  14146. parameters.envMap ? '#define ' + envMapModeDefine : '',
  14147. parameters.envMap ? '#define ' + envMapBlendingDefine : '',
  14148. parameters.lightMap ? '#define USE_LIGHTMAP' : '',
  14149. parameters.aoMap ? '#define USE_AOMAP' : '',
  14150. parameters.emissiveMap ? '#define USE_EMISSIVEMAP' : '',
  14151. parameters.bumpMap ? '#define USE_BUMPMAP' : '',
  14152. parameters.normalMap ? '#define USE_NORMALMAP' : '',
  14153. parameters.specularMap ? '#define USE_SPECULARMAP' : '',
  14154. parameters.roughnessMap ? '#define USE_ROUGHNESSMAP' : '',
  14155. parameters.metalnessMap ? '#define USE_METALNESSMAP' : '',
  14156. parameters.alphaMap ? '#define USE_ALPHAMAP' : '',
  14157. parameters.vertexColors ? '#define USE_COLOR' : '',
  14158. parameters.gradientMap ? '#define USE_GRADIENTMAP' : '',
  14159. parameters.flatShading ? '#define FLAT_SHADED' : '',
  14160. parameters.doubleSided ? '#define DOUBLE_SIDED' : '',
  14161. parameters.flipSided ? '#define FLIP_SIDED' : '',
  14162. '#define NUM_CLIPPING_PLANES ' + parameters.numClippingPlanes,
  14163. '#define UNION_CLIPPING_PLANES ' + (parameters.numClippingPlanes - parameters.numClipIntersection),
  14164. parameters.shadowMapEnabled ? '#define USE_SHADOWMAP' : '',
  14165. parameters.shadowMapEnabled ? '#define ' + shadowMapTypeDefine : '',
  14166. parameters.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : '',
  14167. parameters.physicallyCorrectLights ? "#define PHYSICALLY_CORRECT_LIGHTS" : '',
  14168. parameters.logarithmicDepthBuffer ? '#define USE_LOGDEPTHBUF' : '',
  14169. parameters.logarithmicDepthBuffer && renderer.extensions.get( 'EXT_frag_depth' ) ? '#define USE_LOGDEPTHBUF_EXT' : '',
  14170. parameters.envMap && renderer.extensions.get( 'EXT_shader_texture_lod' ) ? '#define TEXTURE_LOD_EXT' : '',
  14171. 'uniform mat4 viewMatrix;',
  14172. 'uniform vec3 cameraPosition;',
  14173. ( parameters.toneMapping !== NoToneMapping ) ? "#define TONE_MAPPING" : '',
  14174. ( parameters.toneMapping !== NoToneMapping ) ? ShaderChunk[ 'tonemapping_pars_fragment' ] : '', // this code is required here because it is used by the toneMapping() function defined below
  14175. ( parameters.toneMapping !== NoToneMapping ) ? getToneMappingFunction( "toneMapping", parameters.toneMapping ) : '',
  14176. ( 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
  14177. parameters.mapEncoding ? getTexelDecodingFunction( 'mapTexelToLinear', parameters.mapEncoding ) : '',
  14178. parameters.envMapEncoding ? getTexelDecodingFunction( 'envMapTexelToLinear', parameters.envMapEncoding ) : '',
  14179. parameters.emissiveMapEncoding ? getTexelDecodingFunction( 'emissiveMapTexelToLinear', parameters.emissiveMapEncoding ) : '',
  14180. parameters.outputEncoding ? getTexelEncodingFunction( "linearToOutputTexel", parameters.outputEncoding ) : '',
  14181. parameters.depthPacking ? "#define DEPTH_PACKING " + material.depthPacking : '',
  14182. '\n'
  14183. ].filter( filterEmptyLine ).join( '\n' );
  14184. }
  14185. vertexShader = parseIncludes( vertexShader, parameters );
  14186. vertexShader = replaceLightNums( vertexShader, parameters );
  14187. fragmentShader = parseIncludes( fragmentShader, parameters );
  14188. fragmentShader = replaceLightNums( fragmentShader, parameters );
  14189. if ( ! material.isShaderMaterial ) {
  14190. vertexShader = unrollLoops( vertexShader );
  14191. fragmentShader = unrollLoops( fragmentShader );
  14192. }
  14193. var vertexGlsl = prefixVertex + vertexShader;
  14194. var fragmentGlsl = prefixFragment + fragmentShader;
  14195. // console.log( '*VERTEX*', vertexGlsl );
  14196. // console.log( '*FRAGMENT*', fragmentGlsl );
  14197. var glVertexShader = WebGLShader( gl, gl.VERTEX_SHADER, vertexGlsl );
  14198. var glFragmentShader = WebGLShader( gl, gl.FRAGMENT_SHADER, fragmentGlsl );
  14199. gl.attachShader( program, glVertexShader );
  14200. gl.attachShader( program, glFragmentShader );
  14201. // Force a particular attribute to index 0.
  14202. if ( material.index0AttributeName !== undefined ) {
  14203. gl.bindAttribLocation( program, 0, material.index0AttributeName );
  14204. } else if ( parameters.morphTargets === true ) {
  14205. // programs with morphTargets displace position out of attribute 0
  14206. gl.bindAttribLocation( program, 0, 'position' );
  14207. }
  14208. gl.linkProgram( program );
  14209. var programLog = gl.getProgramInfoLog( program );
  14210. var vertexLog = gl.getShaderInfoLog( glVertexShader );
  14211. var fragmentLog = gl.getShaderInfoLog( glFragmentShader );
  14212. var runnable = true;
  14213. var haveDiagnostics = true;
  14214. // console.log( '**VERTEX**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glVertexShader ) );
  14215. // console.log( '**FRAGMENT**', gl.getExtension( 'WEBGL_debug_shaders' ).getTranslatedShaderSource( glFragmentShader ) );
  14216. if ( gl.getProgramParameter( program, gl.LINK_STATUS ) === false ) {
  14217. runnable = false;
  14218. console.error( 'THREE.WebGLProgram: shader error: ', gl.getError(), 'gl.VALIDATE_STATUS', gl.getProgramParameter( program, gl.VALIDATE_STATUS ), 'gl.getProgramInfoLog', programLog, vertexLog, fragmentLog );
  14219. } else if ( programLog !== '' ) {
  14220. console.warn( 'THREE.WebGLProgram: gl.getProgramInfoLog()', programLog );
  14221. } else if ( vertexLog === '' || fragmentLog === '' ) {
  14222. haveDiagnostics = false;
  14223. }
  14224. if ( haveDiagnostics ) {
  14225. this.diagnostics = {
  14226. runnable: runnable,
  14227. material: material,
  14228. programLog: programLog,
  14229. vertexShader: {
  14230. log: vertexLog,
  14231. prefix: prefixVertex
  14232. },
  14233. fragmentShader: {
  14234. log: fragmentLog,
  14235. prefix: prefixFragment
  14236. }
  14237. };
  14238. }
  14239. // clean up
  14240. gl.deleteShader( glVertexShader );
  14241. gl.deleteShader( glFragmentShader );
  14242. // set up caching for uniform locations
  14243. var cachedUniforms;
  14244. this.getUniforms = function() {
  14245. if ( cachedUniforms === undefined ) {
  14246. cachedUniforms =
  14247. new WebGLUniforms( gl, program, renderer );
  14248. }
  14249. return cachedUniforms;
  14250. };
  14251. // set up caching for attribute locations
  14252. var cachedAttributes;
  14253. this.getAttributes = function() {
  14254. if ( cachedAttributes === undefined ) {
  14255. cachedAttributes = fetchAttributeLocations( gl, program );
  14256. }
  14257. return cachedAttributes;
  14258. };
  14259. // free resource
  14260. this.destroy = function() {
  14261. gl.deleteProgram( program );
  14262. this.program = undefined;
  14263. };
  14264. // DEPRECATED
  14265. Object.defineProperties( this, {
  14266. uniforms: {
  14267. get: function() {
  14268. console.warn( 'THREE.WebGLProgram: .uniforms is now .getUniforms().' );
  14269. return this.getUniforms();
  14270. }
  14271. },
  14272. attributes: {
  14273. get: function() {
  14274. console.warn( 'THREE.WebGLProgram: .attributes is now .getAttributes().' );
  14275. return this.getAttributes();
  14276. }
  14277. }
  14278. } );
  14279. //
  14280. this.id = programIdCount ++;
  14281. this.code = code;
  14282. this.usedTimes = 1;
  14283. this.program = program;
  14284. this.vertexShader = glVertexShader;
  14285. this.fragmentShader = glFragmentShader;
  14286. return this;
  14287. }
  14288. /**
  14289. * @author mrdoob / http://mrdoob.com/
  14290. */
  14291. function WebGLPrograms( renderer, capabilities ) {
  14292. var programs = [];
  14293. var shaderIDs = {
  14294. MeshDepthMaterial: 'depth',
  14295. MeshNormalMaterial: 'normal',
  14296. MeshBasicMaterial: 'basic',
  14297. MeshLambertMaterial: 'lambert',
  14298. MeshPhongMaterial: 'phong',
  14299. MeshToonMaterial: 'phong',
  14300. MeshStandardMaterial: 'physical',
  14301. MeshPhysicalMaterial: 'physical',
  14302. LineBasicMaterial: 'basic',
  14303. LineDashedMaterial: 'dashed',
  14304. PointsMaterial: 'points'
  14305. };
  14306. var parameterNames = [
  14307. "precision", "supportsVertexTextures", "map", "mapEncoding", "envMap", "envMapMode", "envMapEncoding",
  14308. "lightMap", "aoMap", "emissiveMap", "emissiveMapEncoding", "bumpMap", "normalMap", "displacementMap", "specularMap",
  14309. "roughnessMap", "metalnessMap", "gradientMap",
  14310. "alphaMap", "combine", "vertexColors", "fog", "useFog", "fogExp",
  14311. "flatShading", "sizeAttenuation", "logarithmicDepthBuffer", "skinning",
  14312. "maxBones", "useVertexTexture", "morphTargets", "morphNormals",
  14313. "maxMorphTargets", "maxMorphNormals", "premultipliedAlpha",
  14314. "numDirLights", "numPointLights", "numSpotLights", "numHemiLights", "numRectAreaLights",
  14315. "shadowMapEnabled", "shadowMapType", "toneMapping", 'physicallyCorrectLights',
  14316. "alphaTest", "doubleSided", "flipSided", "numClippingPlanes", "numClipIntersection", "depthPacking"
  14317. ];
  14318. function allocateBones( object ) {
  14319. if ( capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture ) {
  14320. return 1024;
  14321. } else {
  14322. // default for when object is not specified
  14323. // ( for example when prebuilding shader to be used with multiple objects )
  14324. //
  14325. // - leave some extra space for other uniforms
  14326. // - limit here is ANGLE's 254 max uniform vectors
  14327. // (up to 54 should be safe)
  14328. var nVertexUniforms = capabilities.maxVertexUniforms;
  14329. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14330. var maxBones = nVertexMatrices;
  14331. if ( object !== undefined && (object && object.isSkinnedMesh) ) {
  14332. maxBones = Math.min( object.skeleton.bones.length, maxBones );
  14333. if ( maxBones < object.skeleton.bones.length ) {
  14334. console.warn( 'WebGLRenderer: too many bones - ' + object.skeleton.bones.length + ', this GPU supports just ' + maxBones + ' (try OpenGL instead of ANGLE)' );
  14335. }
  14336. }
  14337. return maxBones;
  14338. }
  14339. }
  14340. function getTextureEncodingFromMap( map, gammaOverrideLinear ) {
  14341. var encoding;
  14342. if ( ! map ) {
  14343. encoding = LinearEncoding;
  14344. } else if ( map.isTexture ) {
  14345. encoding = map.encoding;
  14346. } else if ( map.isWebGLRenderTarget ) {
  14347. console.warn( "THREE.WebGLPrograms.getTextureEncodingFromMap: don't use render targets as textures. Use their .texture property instead." );
  14348. encoding = map.texture.encoding;
  14349. }
  14350. // add backwards compatibility for WebGLRenderer.gammaInput/gammaOutput parameter, should probably be removed at some point.
  14351. if ( encoding === LinearEncoding && gammaOverrideLinear ) {
  14352. encoding = GammaEncoding;
  14353. }
  14354. return encoding;
  14355. }
  14356. this.getParameters = function ( material, lights, fog, nClipPlanes, nClipIntersection, object ) {
  14357. var shaderID = shaderIDs[ material.type ];
  14358. // heuristics to create shader parameters according to lights in the scene
  14359. // (not to blow over maxLights budget)
  14360. var maxBones = allocateBones( object );
  14361. var precision = renderer.getPrecision();
  14362. if ( material.precision !== null ) {
  14363. precision = capabilities.getMaxPrecision( material.precision );
  14364. if ( precision !== material.precision ) {
  14365. console.warn( 'THREE.WebGLProgram.getParameters:', material.precision, 'not supported, using', precision, 'instead.' );
  14366. }
  14367. }
  14368. var currentRenderTarget = renderer.getCurrentRenderTarget();
  14369. var parameters = {
  14370. shaderID: shaderID,
  14371. precision: precision,
  14372. supportsVertexTextures: capabilities.vertexTextures,
  14373. outputEncoding: getTextureEncodingFromMap( ( ! currentRenderTarget ) ? null : currentRenderTarget.texture, renderer.gammaOutput ),
  14374. map: !! material.map,
  14375. mapEncoding: getTextureEncodingFromMap( material.map, renderer.gammaInput ),
  14376. envMap: !! material.envMap,
  14377. envMapMode: material.envMap && material.envMap.mapping,
  14378. envMapEncoding: getTextureEncodingFromMap( material.envMap, renderer.gammaInput ),
  14379. envMapCubeUV: ( !! material.envMap ) && ( ( material.envMap.mapping === CubeUVReflectionMapping ) || ( material.envMap.mapping === CubeUVRefractionMapping ) ),
  14380. lightMap: !! material.lightMap,
  14381. aoMap: !! material.aoMap,
  14382. emissiveMap: !! material.emissiveMap,
  14383. emissiveMapEncoding: getTextureEncodingFromMap( material.emissiveMap, renderer.gammaInput ),
  14384. bumpMap: !! material.bumpMap,
  14385. normalMap: !! material.normalMap,
  14386. displacementMap: !! material.displacementMap,
  14387. roughnessMap: !! material.roughnessMap,
  14388. metalnessMap: !! material.metalnessMap,
  14389. specularMap: !! material.specularMap,
  14390. alphaMap: !! material.alphaMap,
  14391. gradientMap: !! material.gradientMap,
  14392. combine: material.combine,
  14393. vertexColors: material.vertexColors,
  14394. fog: !! fog,
  14395. useFog: material.fog,
  14396. fogExp: (fog && fog.isFogExp2),
  14397. flatShading: material.shading === FlatShading,
  14398. sizeAttenuation: material.sizeAttenuation,
  14399. logarithmicDepthBuffer: capabilities.logarithmicDepthBuffer,
  14400. skinning: material.skinning,
  14401. maxBones: maxBones,
  14402. useVertexTexture: capabilities.floatVertexTextures && object && object.skeleton && object.skeleton.useVertexTexture,
  14403. morphTargets: material.morphTargets,
  14404. morphNormals: material.morphNormals,
  14405. maxMorphTargets: renderer.maxMorphTargets,
  14406. maxMorphNormals: renderer.maxMorphNormals,
  14407. numDirLights: lights.directional.length,
  14408. numPointLights: lights.point.length,
  14409. numSpotLights: lights.spot.length,
  14410. numRectAreaLights: lights.rectArea.length,
  14411. numHemiLights: lights.hemi.length,
  14412. numClippingPlanes: nClipPlanes,
  14413. numClipIntersection: nClipIntersection,
  14414. shadowMapEnabled: renderer.shadowMap.enabled && object.receiveShadow && lights.shadows.length > 0,
  14415. shadowMapType: renderer.shadowMap.type,
  14416. toneMapping: renderer.toneMapping,
  14417. physicallyCorrectLights: renderer.physicallyCorrectLights,
  14418. premultipliedAlpha: material.premultipliedAlpha,
  14419. alphaTest: material.alphaTest,
  14420. doubleSided: material.side === DoubleSide,
  14421. flipSided: material.side === BackSide,
  14422. depthPacking: ( material.depthPacking !== undefined ) ? material.depthPacking : false
  14423. };
  14424. return parameters;
  14425. };
  14426. this.getProgramCode = function ( material, parameters ) {
  14427. var array = [];
  14428. if ( parameters.shaderID ) {
  14429. array.push( parameters.shaderID );
  14430. } else {
  14431. array.push( material.fragmentShader );
  14432. array.push( material.vertexShader );
  14433. }
  14434. if ( material.defines !== undefined ) {
  14435. for ( var name in material.defines ) {
  14436. array.push( name );
  14437. array.push( material.defines[ name ] );
  14438. }
  14439. }
  14440. for ( var i = 0; i < parameterNames.length; i ++ ) {
  14441. array.push( parameters[ parameterNames[ i ] ] );
  14442. }
  14443. return array.join();
  14444. };
  14445. this.acquireProgram = function ( material, parameters, code ) {
  14446. var program;
  14447. // Check if code has been already compiled
  14448. for ( var p = 0, pl = programs.length; p < pl; p ++ ) {
  14449. var programInfo = programs[ p ];
  14450. if ( programInfo.code === code ) {
  14451. program = programInfo;
  14452. ++ program.usedTimes;
  14453. break;
  14454. }
  14455. }
  14456. if ( program === undefined ) {
  14457. program = new WebGLProgram( renderer, code, material, parameters );
  14458. programs.push( program );
  14459. }
  14460. return program;
  14461. };
  14462. this.releaseProgram = function( program ) {
  14463. if ( -- program.usedTimes === 0 ) {
  14464. // Remove from unordered set
  14465. var i = programs.indexOf( program );
  14466. programs[ i ] = programs[ programs.length - 1 ];
  14467. programs.pop();
  14468. // Free WebGL resources
  14469. program.destroy();
  14470. }
  14471. };
  14472. // Exposed for resource monitoring & error feedback via renderer.info:
  14473. this.programs = programs;
  14474. }
  14475. /**
  14476. * @author mrdoob / http://mrdoob.com/
  14477. */
  14478. function WebGLGeometries( gl, properties, info ) {
  14479. var geometries = {};
  14480. function onGeometryDispose( event ) {
  14481. var geometry = event.target;
  14482. var buffergeometry = geometries[ geometry.id ];
  14483. if ( buffergeometry.index !== null ) {
  14484. deleteAttribute( buffergeometry.index );
  14485. }
  14486. deleteAttributes( buffergeometry.attributes );
  14487. geometry.removeEventListener( 'dispose', onGeometryDispose );
  14488. delete geometries[ geometry.id ];
  14489. // TODO
  14490. var property = properties.get( geometry );
  14491. if ( property.wireframe ) {
  14492. deleteAttribute( property.wireframe );
  14493. }
  14494. properties.delete( geometry );
  14495. var bufferproperty = properties.get( buffergeometry );
  14496. if ( bufferproperty.wireframe ) {
  14497. deleteAttribute( bufferproperty.wireframe );
  14498. }
  14499. properties.delete( buffergeometry );
  14500. //
  14501. info.memory.geometries --;
  14502. }
  14503. function getAttributeBuffer( attribute ) {
  14504. if ( attribute.isInterleavedBufferAttribute ) {
  14505. return properties.get( attribute.data ).__webglBuffer;
  14506. }
  14507. return properties.get( attribute ).__webglBuffer;
  14508. }
  14509. function deleteAttribute( attribute ) {
  14510. var buffer = getAttributeBuffer( attribute );
  14511. if ( buffer !== undefined ) {
  14512. gl.deleteBuffer( buffer );
  14513. removeAttributeBuffer( attribute );
  14514. }
  14515. }
  14516. function deleteAttributes( attributes ) {
  14517. for ( var name in attributes ) {
  14518. deleteAttribute( attributes[ name ] );
  14519. }
  14520. }
  14521. function removeAttributeBuffer( attribute ) {
  14522. if ( attribute.isInterleavedBufferAttribute ) {
  14523. properties.delete( attribute.data );
  14524. } else {
  14525. properties.delete( attribute );
  14526. }
  14527. }
  14528. return {
  14529. get: function ( object ) {
  14530. var geometry = object.geometry;
  14531. if ( geometries[ geometry.id ] !== undefined ) {
  14532. return geometries[ geometry.id ];
  14533. }
  14534. geometry.addEventListener( 'dispose', onGeometryDispose );
  14535. var buffergeometry;
  14536. if ( geometry.isBufferGeometry ) {
  14537. buffergeometry = geometry;
  14538. } else if ( geometry.isGeometry ) {
  14539. if ( geometry._bufferGeometry === undefined ) {
  14540. geometry._bufferGeometry = new BufferGeometry().setFromObject( object );
  14541. }
  14542. buffergeometry = geometry._bufferGeometry;
  14543. }
  14544. geometries[ geometry.id ] = buffergeometry;
  14545. info.memory.geometries ++;
  14546. return buffergeometry;
  14547. }
  14548. };
  14549. }
  14550. /**
  14551. * @author mrdoob / http://mrdoob.com/
  14552. */
  14553. function WebGLObjects( gl, properties, info ) {
  14554. var geometries = new WebGLGeometries( gl, properties, info );
  14555. //
  14556. function update( object ) {
  14557. // TODO: Avoid updating twice (when using shadowMap). Maybe add frame counter.
  14558. var geometry = geometries.get( object );
  14559. if ( object.geometry.isGeometry ) {
  14560. geometry.updateFromObject( object );
  14561. }
  14562. var index = geometry.index;
  14563. var attributes = geometry.attributes;
  14564. if ( index !== null ) {
  14565. updateAttribute( index, gl.ELEMENT_ARRAY_BUFFER );
  14566. }
  14567. for ( var name in attributes ) {
  14568. updateAttribute( attributes[ name ], gl.ARRAY_BUFFER );
  14569. }
  14570. // morph targets
  14571. var morphAttributes = geometry.morphAttributes;
  14572. for ( var name in morphAttributes ) {
  14573. var array = morphAttributes[ name ];
  14574. for ( var i = 0, l = array.length; i < l; i ++ ) {
  14575. updateAttribute( array[ i ], gl.ARRAY_BUFFER );
  14576. }
  14577. }
  14578. return geometry;
  14579. }
  14580. function updateAttribute( attribute, bufferType ) {
  14581. var data = ( attribute.isInterleavedBufferAttribute ) ? attribute.data : attribute;
  14582. var attributeProperties = properties.get( data );
  14583. if ( attributeProperties.__webglBuffer === undefined ) {
  14584. createBuffer( attributeProperties, data, bufferType );
  14585. } else if ( attributeProperties.version !== data.version ) {
  14586. updateBuffer( attributeProperties, data, bufferType );
  14587. }
  14588. }
  14589. function createBuffer( attributeProperties, data, bufferType ) {
  14590. attributeProperties.__webglBuffer = gl.createBuffer();
  14591. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  14592. var usage = data.dynamic ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW;
  14593. gl.bufferData( bufferType, data.array, usage );
  14594. var type = gl.FLOAT;
  14595. var array = data.array;
  14596. if ( array instanceof Float32Array ) {
  14597. type = gl.FLOAT;
  14598. } else if ( array instanceof Float64Array ) {
  14599. console.warn( "Unsupported data buffer format: Float64Array" );
  14600. } else if ( array instanceof Uint16Array ) {
  14601. type = gl.UNSIGNED_SHORT;
  14602. } else if ( array instanceof Int16Array ) {
  14603. type = gl.SHORT;
  14604. } else if ( array instanceof Uint32Array ) {
  14605. type = gl.UNSIGNED_INT;
  14606. } else if ( array instanceof Int32Array ) {
  14607. type = gl.INT;
  14608. } else if ( array instanceof Int8Array ) {
  14609. type = gl.BYTE;
  14610. } else if ( array instanceof Uint8Array ) {
  14611. type = gl.UNSIGNED_BYTE;
  14612. }
  14613. attributeProperties.bytesPerElement = array.BYTES_PER_ELEMENT;
  14614. attributeProperties.type = type;
  14615. attributeProperties.version = data.version;
  14616. data.onUploadCallback();
  14617. }
  14618. function updateBuffer( attributeProperties, data, bufferType ) {
  14619. gl.bindBuffer( bufferType, attributeProperties.__webglBuffer );
  14620. if ( data.dynamic === false ) {
  14621. gl.bufferData( bufferType, data.array, gl.STATIC_DRAW );
  14622. } else if ( data.updateRange.count === - 1 ) {
  14623. // Not using update ranges
  14624. gl.bufferSubData( bufferType, 0, data.array );
  14625. } else if ( data.updateRange.count === 0 ) {
  14626. 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.' );
  14627. } else {
  14628. gl.bufferSubData( bufferType, data.updateRange.offset * data.array.BYTES_PER_ELEMENT,
  14629. data.array.subarray( data.updateRange.offset, data.updateRange.offset + data.updateRange.count ) );
  14630. data.updateRange.count = 0; // reset range
  14631. }
  14632. attributeProperties.version = data.version;
  14633. }
  14634. function getAttributeBuffer( attribute ) {
  14635. if ( attribute.isInterleavedBufferAttribute ) {
  14636. return properties.get( attribute.data ).__webglBuffer;
  14637. }
  14638. return properties.get( attribute ).__webglBuffer;
  14639. }
  14640. function getAttributeProperties( attribute ) {
  14641. if ( attribute.isInterleavedBufferAttribute ) {
  14642. return properties.get( attribute.data );
  14643. }
  14644. return properties.get( attribute );
  14645. }
  14646. function getWireframeAttribute( geometry ) {
  14647. var property = properties.get( geometry );
  14648. if ( property.wireframe !== undefined ) {
  14649. return property.wireframe;
  14650. }
  14651. var indices = [];
  14652. var index = geometry.index;
  14653. var attributes = geometry.attributes;
  14654. var position = attributes.position;
  14655. // console.time( 'wireframe' );
  14656. if ( index !== null ) {
  14657. var edges = {};
  14658. var array = index.array;
  14659. for ( var i = 0, l = array.length; i < l; i += 3 ) {
  14660. var a = array[ i + 0 ];
  14661. var b = array[ i + 1 ];
  14662. var c = array[ i + 2 ];
  14663. indices.push( a, b, b, c, c, a );
  14664. }
  14665. } else {
  14666. var array = attributes.position.array;
  14667. for ( var i = 0, l = ( array.length / 3 ) - 1; i < l; i += 3 ) {
  14668. var a = i + 0;
  14669. var b = i + 1;
  14670. var c = i + 2;
  14671. indices.push( a, b, b, c, c, a );
  14672. }
  14673. }
  14674. // console.timeEnd( 'wireframe' );
  14675. var TypeArray = position.count > 65535 ? Uint32Array : Uint16Array;
  14676. var attribute = new BufferAttribute( new TypeArray( indices ), 1 );
  14677. updateAttribute( attribute, gl.ELEMENT_ARRAY_BUFFER );
  14678. property.wireframe = attribute;
  14679. return attribute;
  14680. }
  14681. return {
  14682. getAttributeBuffer: getAttributeBuffer,
  14683. getAttributeProperties: getAttributeProperties,
  14684. getWireframeAttribute: getWireframeAttribute,
  14685. update: update
  14686. };
  14687. }
  14688. /**
  14689. * @author mrdoob / http://mrdoob.com/
  14690. */
  14691. function WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, info ) {
  14692. var _infoMemory = info.memory;
  14693. var _isWebGL2 = ( typeof WebGL2RenderingContext !== 'undefined' && _gl instanceof WebGL2RenderingContext );
  14694. //
  14695. function clampToMaxSize( image, maxSize ) {
  14696. if ( image.width > maxSize || image.height > maxSize ) {
  14697. // Warning: Scaling through the canvas will only work with images that use
  14698. // premultiplied alpha.
  14699. var scale = maxSize / Math.max( image.width, image.height );
  14700. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14701. canvas.width = Math.floor( image.width * scale );
  14702. canvas.height = Math.floor( image.height * scale );
  14703. var context = canvas.getContext( '2d' );
  14704. context.drawImage( image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height );
  14705. console.warn( 'THREE.WebGLRenderer: image is too big (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14706. return canvas;
  14707. }
  14708. return image;
  14709. }
  14710. function isPowerOfTwo( image ) {
  14711. return _Math.isPowerOfTwo( image.width ) && _Math.isPowerOfTwo( image.height );
  14712. }
  14713. function makePowerOfTwo( image ) {
  14714. if ( image instanceof HTMLImageElement || image instanceof HTMLCanvasElement ) {
  14715. var canvas = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  14716. canvas.width = _Math.nearestPowerOfTwo( image.width );
  14717. canvas.height = _Math.nearestPowerOfTwo( image.height );
  14718. var context = canvas.getContext( '2d' );
  14719. context.drawImage( image, 0, 0, canvas.width, canvas.height );
  14720. console.warn( 'THREE.WebGLRenderer: image is not power of two (' + image.width + 'x' + image.height + '). Resized to ' + canvas.width + 'x' + canvas.height, image );
  14721. return canvas;
  14722. }
  14723. return image;
  14724. }
  14725. function textureNeedsPowerOfTwo( texture ) {
  14726. return ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) ||
  14727. ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter );
  14728. }
  14729. // Fallback filters for non-power-of-2 textures
  14730. function filterFallback( f ) {
  14731. if ( f === NearestFilter || f === NearestMipMapNearestFilter || f === NearestMipMapLinearFilter ) {
  14732. return _gl.NEAREST;
  14733. }
  14734. return _gl.LINEAR;
  14735. }
  14736. //
  14737. function onTextureDispose( event ) {
  14738. var texture = event.target;
  14739. texture.removeEventListener( 'dispose', onTextureDispose );
  14740. deallocateTexture( texture );
  14741. _infoMemory.textures --;
  14742. }
  14743. function onRenderTargetDispose( event ) {
  14744. var renderTarget = event.target;
  14745. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  14746. deallocateRenderTarget( renderTarget );
  14747. _infoMemory.textures --;
  14748. }
  14749. //
  14750. function deallocateTexture( texture ) {
  14751. var textureProperties = properties.get( texture );
  14752. if ( texture.image && textureProperties.__image__webglTextureCube ) {
  14753. // cube texture
  14754. _gl.deleteTexture( textureProperties.__image__webglTextureCube );
  14755. } else {
  14756. // 2D texture
  14757. if ( textureProperties.__webglInit === undefined ) return;
  14758. _gl.deleteTexture( textureProperties.__webglTexture );
  14759. }
  14760. // remove all webgl properties
  14761. properties.delete( texture );
  14762. }
  14763. function deallocateRenderTarget( renderTarget ) {
  14764. var renderTargetProperties = properties.get( renderTarget );
  14765. var textureProperties = properties.get( renderTarget.texture );
  14766. if ( ! renderTarget ) return;
  14767. if ( textureProperties.__webglTexture !== undefined ) {
  14768. _gl.deleteTexture( textureProperties.__webglTexture );
  14769. }
  14770. if ( renderTarget.depthTexture ) {
  14771. renderTarget.depthTexture.dispose();
  14772. }
  14773. if ( renderTarget.isWebGLRenderTargetCube ) {
  14774. for ( var i = 0; i < 6; i ++ ) {
  14775. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer[ i ] );
  14776. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer[ i ] );
  14777. }
  14778. } else {
  14779. _gl.deleteFramebuffer( renderTargetProperties.__webglFramebuffer );
  14780. if ( renderTargetProperties.__webglDepthbuffer ) _gl.deleteRenderbuffer( renderTargetProperties.__webglDepthbuffer );
  14781. }
  14782. properties.delete( renderTarget.texture );
  14783. properties.delete( renderTarget );
  14784. }
  14785. //
  14786. function setTexture2D( texture, slot ) {
  14787. var textureProperties = properties.get( texture );
  14788. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14789. var image = texture.image;
  14790. if ( image === undefined ) {
  14791. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is undefined', texture );
  14792. } else if ( image.complete === false ) {
  14793. console.warn( 'THREE.WebGLRenderer: Texture marked for update but image is incomplete', texture );
  14794. } else {
  14795. uploadTexture( textureProperties, texture, slot );
  14796. return;
  14797. }
  14798. }
  14799. state.activeTexture( _gl.TEXTURE0 + slot );
  14800. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14801. }
  14802. function setTextureCube( texture, slot ) {
  14803. var textureProperties = properties.get( texture );
  14804. if ( texture.image.length === 6 ) {
  14805. if ( texture.version > 0 && textureProperties.__version !== texture.version ) {
  14806. if ( ! textureProperties.__image__webglTextureCube ) {
  14807. texture.addEventListener( 'dispose', onTextureDispose );
  14808. textureProperties.__image__webglTextureCube = _gl.createTexture();
  14809. _infoMemory.textures ++;
  14810. }
  14811. state.activeTexture( _gl.TEXTURE0 + slot );
  14812. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14813. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14814. var isCompressed = ( texture && texture.isCompressedTexture );
  14815. var isDataTexture = ( texture.image[ 0 ] && texture.image[ 0 ].isDataTexture );
  14816. var cubeImage = [];
  14817. for ( var i = 0; i < 6; i ++ ) {
  14818. if ( ! isCompressed && ! isDataTexture ) {
  14819. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], capabilities.maxCubemapSize );
  14820. } else {
  14821. cubeImage[ i ] = isDataTexture ? texture.image[ i ].image : texture.image[ i ];
  14822. }
  14823. }
  14824. var image = cubeImage[ 0 ],
  14825. isPowerOfTwoImage = isPowerOfTwo( image ),
  14826. glFormat = paramThreeToGL( texture.format ),
  14827. glType = paramThreeToGL( texture.type );
  14828. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isPowerOfTwoImage );
  14829. for ( var i = 0; i < 6; i ++ ) {
  14830. if ( ! isCompressed ) {
  14831. if ( isDataTexture ) {
  14832. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, cubeImage[ i ].width, cubeImage[ i ].height, 0, glFormat, glType, cubeImage[ i ].data );
  14833. } else {
  14834. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14835. }
  14836. } else {
  14837. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14838. for ( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14839. mipmap = mipmaps[ j ];
  14840. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14841. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14842. state.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14843. } else {
  14844. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()" );
  14845. }
  14846. } else {
  14847. state.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14848. }
  14849. }
  14850. }
  14851. }
  14852. if ( texture.generateMipmaps && isPowerOfTwoImage ) {
  14853. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14854. }
  14855. textureProperties.__version = texture.version;
  14856. if ( texture.onUpdate ) texture.onUpdate( texture );
  14857. } else {
  14858. state.activeTexture( _gl.TEXTURE0 + slot );
  14859. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__image__webglTextureCube );
  14860. }
  14861. }
  14862. }
  14863. function setTextureCubeDynamic( texture, slot ) {
  14864. state.activeTexture( _gl.TEXTURE0 + slot );
  14865. state.bindTexture( _gl.TEXTURE_CUBE_MAP, properties.get( texture ).__webglTexture );
  14866. }
  14867. function setTextureParameters( textureType, texture, isPowerOfTwoImage ) {
  14868. var extension;
  14869. if ( isPowerOfTwoImage ) {
  14870. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  14871. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  14872. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  14873. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  14874. } else {
  14875. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  14876. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  14877. if ( texture.wrapS !== ClampToEdgeWrapping || texture.wrapT !== ClampToEdgeWrapping ) {
  14878. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.wrapS and Texture.wrapT should be set to THREE.ClampToEdgeWrapping.', texture );
  14879. }
  14880. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  14881. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  14882. if ( texture.minFilter !== NearestFilter && texture.minFilter !== LinearFilter ) {
  14883. console.warn( 'THREE.WebGLRenderer: Texture is not power of two. Texture.minFilter should be set to THREE.NearestFilter or THREE.LinearFilter.', texture );
  14884. }
  14885. }
  14886. extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  14887. if ( extension ) {
  14888. if ( texture.type === FloatType && extensions.get( 'OES_texture_float_linear' ) === null ) return;
  14889. if ( texture.type === HalfFloatType && extensions.get( 'OES_texture_half_float_linear' ) === null ) return;
  14890. if ( texture.anisotropy > 1 || properties.get( texture ).__currentAnisotropy ) {
  14891. _gl.texParameterf( textureType, extension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, capabilities.getMaxAnisotropy() ) );
  14892. properties.get( texture ).__currentAnisotropy = texture.anisotropy;
  14893. }
  14894. }
  14895. }
  14896. function uploadTexture( textureProperties, texture, slot ) {
  14897. if ( textureProperties.__webglInit === undefined ) {
  14898. textureProperties.__webglInit = true;
  14899. texture.addEventListener( 'dispose', onTextureDispose );
  14900. textureProperties.__webglTexture = _gl.createTexture();
  14901. _infoMemory.textures ++;
  14902. }
  14903. state.activeTexture( _gl.TEXTURE0 + slot );
  14904. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  14905. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14906. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  14907. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  14908. var image = clampToMaxSize( texture.image, capabilities.maxTextureSize );
  14909. if ( textureNeedsPowerOfTwo( texture ) && isPowerOfTwo( image ) === false ) {
  14910. image = makePowerOfTwo( image );
  14911. }
  14912. var isPowerOfTwoImage = isPowerOfTwo( image ),
  14913. glFormat = paramThreeToGL( texture.format ),
  14914. glType = paramThreeToGL( texture.type );
  14915. setTextureParameters( _gl.TEXTURE_2D, texture, isPowerOfTwoImage );
  14916. var mipmap, mipmaps = texture.mipmaps;
  14917. if ( texture.isDepthTexture ) {
  14918. // populate depth texture with dummy data
  14919. var internalFormat = _gl.DEPTH_COMPONENT;
  14920. if ( texture.type === FloatType ) {
  14921. if ( !_isWebGL2 ) throw new Error('Float Depth Texture only supported in WebGL2.0');
  14922. internalFormat = _gl.DEPTH_COMPONENT32F;
  14923. } else if ( _isWebGL2 ) {
  14924. // WebGL 2.0 requires signed internalformat for glTexImage2D
  14925. internalFormat = _gl.DEPTH_COMPONENT16;
  14926. }
  14927. if ( texture.format === DepthFormat && internalFormat === _gl.DEPTH_COMPONENT ) {
  14928. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14929. // DEPTH_COMPONENT and type is not UNSIGNED_SHORT or UNSIGNED_INT
  14930. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14931. if ( texture.type !== UnsignedShortType && texture.type !== UnsignedIntType ) {
  14932. console.warn( 'THREE.WebGLRenderer: Use UnsignedShortType or UnsignedIntType for DepthFormat DepthTexture.' );
  14933. texture.type = UnsignedShortType;
  14934. glType = paramThreeToGL( texture.type );
  14935. }
  14936. }
  14937. // Depth stencil textures need the DEPTH_STENCIL internal format
  14938. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14939. if ( texture.format === DepthStencilFormat ) {
  14940. internalFormat = _gl.DEPTH_STENCIL;
  14941. // The error INVALID_OPERATION is generated by texImage2D if format and internalformat are
  14942. // DEPTH_STENCIL and type is not UNSIGNED_INT_24_8_WEBGL.
  14943. // (https://www.khronos.org/registry/webgl/extensions/WEBGL_depth_texture/)
  14944. if ( texture.type !== UnsignedInt248Type ) {
  14945. console.warn( 'THREE.WebGLRenderer: Use UnsignedInt248Type for DepthStencilFormat DepthTexture.' );
  14946. texture.type = UnsignedInt248Type;
  14947. glType = paramThreeToGL( texture.type );
  14948. }
  14949. }
  14950. state.texImage2D( _gl.TEXTURE_2D, 0, internalFormat, image.width, image.height, 0, glFormat, glType, null );
  14951. } else if ( texture.isDataTexture ) {
  14952. // use manually created mipmaps if available
  14953. // if there are no manual mipmaps
  14954. // set 0 level mipmap and then use GL to generate other mipmap levels
  14955. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  14956. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14957. mipmap = mipmaps[ i ];
  14958. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14959. }
  14960. texture.generateMipmaps = false;
  14961. } else {
  14962. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  14963. }
  14964. } else if ( texture.isCompressedTexture ) {
  14965. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14966. mipmap = mipmaps[ i ];
  14967. if ( texture.format !== RGBAFormat && texture.format !== RGBFormat ) {
  14968. if ( state.getCompressedTextureFormats().indexOf( glFormat ) > - 1 ) {
  14969. state.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14970. } else {
  14971. console.warn( "THREE.WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()" );
  14972. }
  14973. } else {
  14974. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  14975. }
  14976. }
  14977. } else {
  14978. // regular Texture (image, video, canvas)
  14979. // use manually created mipmaps if available
  14980. // if there are no manual mipmaps
  14981. // set 0 level mipmap and then use GL to generate other mipmap levels
  14982. if ( mipmaps.length > 0 && isPowerOfTwoImage ) {
  14983. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14984. mipmap = mipmaps[ i ];
  14985. state.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14986. }
  14987. texture.generateMipmaps = false;
  14988. } else {
  14989. state.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, image );
  14990. }
  14991. }
  14992. if ( texture.generateMipmaps && isPowerOfTwoImage ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14993. textureProperties.__version = texture.version;
  14994. if ( texture.onUpdate ) texture.onUpdate( texture );
  14995. }
  14996. // Render targets
  14997. // Setup storage for target texture and bind it to correct framebuffer
  14998. function setupFrameBufferTexture( framebuffer, renderTarget, attachment, textureTarget ) {
  14999. var glFormat = paramThreeToGL( renderTarget.texture.format );
  15000. var glType = paramThreeToGL( renderTarget.texture.type );
  15001. state.texImage2D( textureTarget, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15002. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15003. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, attachment, textureTarget, properties.get( renderTarget.texture ).__webglTexture, 0 );
  15004. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15005. }
  15006. // Setup storage for internal depth/stencil buffers and bind to correct framebuffer
  15007. function setupRenderBufferStorage( renderbuffer, renderTarget ) {
  15008. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15009. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15010. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15011. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15012. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15013. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15014. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15015. } else {
  15016. // FIXME: We don't support !depth !stencil
  15017. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15018. }
  15019. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15020. }
  15021. // Setup resources for a Depth Texture for a FBO (needs an extension)
  15022. function setupDepthTexture( framebuffer, renderTarget ) {
  15023. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  15024. if ( isCube ) throw new Error('Depth Texture with cube render targets is not supported!');
  15025. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15026. if ( !( renderTarget.depthTexture && renderTarget.depthTexture.isDepthTexture ) ) {
  15027. throw new Error('renderTarget.depthTexture must be an instance of THREE.DepthTexture');
  15028. }
  15029. // upload an empty depth texture with framebuffer size
  15030. if ( !properties.get( renderTarget.depthTexture ).__webglTexture ||
  15031. renderTarget.depthTexture.image.width !== renderTarget.width ||
  15032. renderTarget.depthTexture.image.height !== renderTarget.height ) {
  15033. renderTarget.depthTexture.image.width = renderTarget.width;
  15034. renderTarget.depthTexture.image.height = renderTarget.height;
  15035. renderTarget.depthTexture.needsUpdate = true;
  15036. }
  15037. setTexture2D( renderTarget.depthTexture, 0 );
  15038. var webglDepthTexture = properties.get( renderTarget.depthTexture ).__webglTexture;
  15039. if ( renderTarget.depthTexture.format === DepthFormat ) {
  15040. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15041. } else if ( renderTarget.depthTexture.format === DepthStencilFormat ) {
  15042. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.TEXTURE_2D, webglDepthTexture, 0 );
  15043. } else {
  15044. throw new Error('Unknown depthTexture format')
  15045. }
  15046. }
  15047. // Setup GL resources for a non-texture depth buffer
  15048. function setupDepthRenderbuffer( renderTarget ) {
  15049. var renderTargetProperties = properties.get( renderTarget );
  15050. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15051. if ( renderTarget.depthTexture ) {
  15052. if ( isCube ) throw new Error('target.depthTexture not supported in Cube render targets');
  15053. setupDepthTexture( renderTargetProperties.__webglFramebuffer, renderTarget );
  15054. } else {
  15055. if ( isCube ) {
  15056. renderTargetProperties.__webglDepthbuffer = [];
  15057. for ( var i = 0; i < 6; i ++ ) {
  15058. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer[ i ] );
  15059. renderTargetProperties.__webglDepthbuffer[ i ] = _gl.createRenderbuffer();
  15060. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer[ i ], renderTarget );
  15061. }
  15062. } else {
  15063. _gl.bindFramebuffer( _gl.FRAMEBUFFER, renderTargetProperties.__webglFramebuffer );
  15064. renderTargetProperties.__webglDepthbuffer = _gl.createRenderbuffer();
  15065. setupRenderBufferStorage( renderTargetProperties.__webglDepthbuffer, renderTarget );
  15066. }
  15067. }
  15068. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15069. }
  15070. // Set up GL resources for the render target
  15071. function setupRenderTarget( renderTarget ) {
  15072. var renderTargetProperties = properties.get( renderTarget );
  15073. var textureProperties = properties.get( renderTarget.texture );
  15074. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15075. textureProperties.__webglTexture = _gl.createTexture();
  15076. _infoMemory.textures ++;
  15077. var isCube = ( renderTarget.isWebGLRenderTargetCube === true );
  15078. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget );
  15079. // Setup framebuffer
  15080. if ( isCube ) {
  15081. renderTargetProperties.__webglFramebuffer = [];
  15082. for ( var i = 0; i < 6; i ++ ) {
  15083. renderTargetProperties.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15084. }
  15085. } else {
  15086. renderTargetProperties.__webglFramebuffer = _gl.createFramebuffer();
  15087. }
  15088. // Setup color buffer
  15089. if ( isCube ) {
  15090. state.bindTexture( _gl.TEXTURE_CUBE_MAP, textureProperties.__webglTexture );
  15091. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget.texture, isTargetPowerOfTwo );
  15092. for ( var i = 0; i < 6; i ++ ) {
  15093. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer[ i ], renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15094. }
  15095. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15096. state.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15097. } else {
  15098. state.bindTexture( _gl.TEXTURE_2D, textureProperties.__webglTexture );
  15099. setTextureParameters( _gl.TEXTURE_2D, renderTarget.texture, isTargetPowerOfTwo );
  15100. setupFrameBufferTexture( renderTargetProperties.__webglFramebuffer, renderTarget, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D );
  15101. if ( renderTarget.texture.generateMipmaps && isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15102. state.bindTexture( _gl.TEXTURE_2D, null );
  15103. }
  15104. // Setup depth and stencil buffers
  15105. if ( renderTarget.depthBuffer ) {
  15106. setupDepthRenderbuffer( renderTarget );
  15107. }
  15108. }
  15109. function updateRenderTargetMipmap( renderTarget ) {
  15110. var texture = renderTarget.texture;
  15111. if ( texture.generateMipmaps && isPowerOfTwo( renderTarget ) &&
  15112. texture.minFilter !== NearestFilter &&
  15113. texture.minFilter !== LinearFilter ) {
  15114. var target = (renderTarget && renderTarget.isWebGLRenderTargetCube) ? _gl.TEXTURE_CUBE_MAP : _gl.TEXTURE_2D;
  15115. var webglTexture = properties.get( texture ).__webglTexture;
  15116. state.bindTexture( target, webglTexture );
  15117. _gl.generateMipmap( target );
  15118. state.bindTexture( target, null );
  15119. }
  15120. }
  15121. this.setTexture2D = setTexture2D;
  15122. this.setTextureCube = setTextureCube;
  15123. this.setTextureCubeDynamic = setTextureCubeDynamic;
  15124. this.setupRenderTarget = setupRenderTarget;
  15125. this.updateRenderTargetMipmap = updateRenderTargetMipmap;
  15126. }
  15127. /**
  15128. * @author fordacious / fordacious.github.io
  15129. */
  15130. function WebGLProperties() {
  15131. var properties = {};
  15132. return {
  15133. get: function ( object ) {
  15134. var uuid = object.uuid;
  15135. var map = properties[ uuid ];
  15136. if ( map === undefined ) {
  15137. map = {};
  15138. properties[ uuid ] = map;
  15139. }
  15140. return map;
  15141. },
  15142. delete: function ( object ) {
  15143. delete properties[ object.uuid ];
  15144. },
  15145. clear: function () {
  15146. properties = {};
  15147. }
  15148. };
  15149. }
  15150. /**
  15151. * @author mrdoob / http://mrdoob.com/
  15152. */
  15153. function WebGLState( gl, extensions, paramThreeToGL ) {
  15154. function ColorBuffer() {
  15155. var locked = false;
  15156. var color = new Vector4();
  15157. var currentColorMask = null;
  15158. var currentColorClear = new Vector4();
  15159. return {
  15160. setMask: function ( colorMask ) {
  15161. if ( currentColorMask !== colorMask && ! locked ) {
  15162. gl.colorMask( colorMask, colorMask, colorMask, colorMask );
  15163. currentColorMask = colorMask;
  15164. }
  15165. },
  15166. setLocked: function ( lock ) {
  15167. locked = lock;
  15168. },
  15169. setClear: function ( r, g, b, a, premultipliedAlpha ) {
  15170. if ( premultipliedAlpha === true ) {
  15171. r *= a; g *= a; b *= a;
  15172. }
  15173. color.set( r, g, b, a );
  15174. if ( currentColorClear.equals( color ) === false ) {
  15175. gl.clearColor( r, g, b, a );
  15176. currentColorClear.copy( color );
  15177. }
  15178. },
  15179. reset: function () {
  15180. locked = false;
  15181. currentColorMask = null;
  15182. currentColorClear.set( 0, 0, 0, 1 );
  15183. }
  15184. };
  15185. }
  15186. function DepthBuffer() {
  15187. var locked = false;
  15188. var currentDepthMask = null;
  15189. var currentDepthFunc = null;
  15190. var currentDepthClear = null;
  15191. return {
  15192. setTest: function ( depthTest ) {
  15193. if ( depthTest ) {
  15194. enable( gl.DEPTH_TEST );
  15195. } else {
  15196. disable( gl.DEPTH_TEST );
  15197. }
  15198. },
  15199. setMask: function ( depthMask ) {
  15200. if ( currentDepthMask !== depthMask && ! locked ) {
  15201. gl.depthMask( depthMask );
  15202. currentDepthMask = depthMask;
  15203. }
  15204. },
  15205. setFunc: function ( depthFunc ) {
  15206. if ( currentDepthFunc !== depthFunc ) {
  15207. if ( depthFunc ) {
  15208. switch ( depthFunc ) {
  15209. case NeverDepth:
  15210. gl.depthFunc( gl.NEVER );
  15211. break;
  15212. case AlwaysDepth:
  15213. gl.depthFunc( gl.ALWAYS );
  15214. break;
  15215. case LessDepth:
  15216. gl.depthFunc( gl.LESS );
  15217. break;
  15218. case LessEqualDepth:
  15219. gl.depthFunc( gl.LEQUAL );
  15220. break;
  15221. case EqualDepth:
  15222. gl.depthFunc( gl.EQUAL );
  15223. break;
  15224. case GreaterEqualDepth:
  15225. gl.depthFunc( gl.GEQUAL );
  15226. break;
  15227. case GreaterDepth:
  15228. gl.depthFunc( gl.GREATER );
  15229. break;
  15230. case NotEqualDepth:
  15231. gl.depthFunc( gl.NOTEQUAL );
  15232. break;
  15233. default:
  15234. gl.depthFunc( gl.LEQUAL );
  15235. }
  15236. } else {
  15237. gl.depthFunc( gl.LEQUAL );
  15238. }
  15239. currentDepthFunc = depthFunc;
  15240. }
  15241. },
  15242. setLocked: function ( lock ) {
  15243. locked = lock;
  15244. },
  15245. setClear: function ( depth ) {
  15246. if ( currentDepthClear !== depth ) {
  15247. gl.clearDepth( depth );
  15248. currentDepthClear = depth;
  15249. }
  15250. },
  15251. reset: function () {
  15252. locked = false;
  15253. currentDepthMask = null;
  15254. currentDepthFunc = null;
  15255. currentDepthClear = null;
  15256. }
  15257. };
  15258. }
  15259. function StencilBuffer() {
  15260. var locked = false;
  15261. var currentStencilMask = null;
  15262. var currentStencilFunc = null;
  15263. var currentStencilRef = null;
  15264. var currentStencilFuncMask = null;
  15265. var currentStencilFail = null;
  15266. var currentStencilZFail = null;
  15267. var currentStencilZPass = null;
  15268. var currentStencilClear = null;
  15269. return {
  15270. setTest: function ( stencilTest ) {
  15271. if ( stencilTest ) {
  15272. enable( gl.STENCIL_TEST );
  15273. } else {
  15274. disable( gl.STENCIL_TEST );
  15275. }
  15276. },
  15277. setMask: function ( stencilMask ) {
  15278. if ( currentStencilMask !== stencilMask && ! locked ) {
  15279. gl.stencilMask( stencilMask );
  15280. currentStencilMask = stencilMask;
  15281. }
  15282. },
  15283. setFunc: function ( stencilFunc, stencilRef, stencilMask ) {
  15284. if ( currentStencilFunc !== stencilFunc ||
  15285. currentStencilRef !== stencilRef ||
  15286. currentStencilFuncMask !== stencilMask ) {
  15287. gl.stencilFunc( stencilFunc, stencilRef, stencilMask );
  15288. currentStencilFunc = stencilFunc;
  15289. currentStencilRef = stencilRef;
  15290. currentStencilFuncMask = stencilMask;
  15291. }
  15292. },
  15293. setOp: function ( stencilFail, stencilZFail, stencilZPass ) {
  15294. if ( currentStencilFail !== stencilFail ||
  15295. currentStencilZFail !== stencilZFail ||
  15296. currentStencilZPass !== stencilZPass ) {
  15297. gl.stencilOp( stencilFail, stencilZFail, stencilZPass );
  15298. currentStencilFail = stencilFail;
  15299. currentStencilZFail = stencilZFail;
  15300. currentStencilZPass = stencilZPass;
  15301. }
  15302. },
  15303. setLocked: function ( lock ) {
  15304. locked = lock;
  15305. },
  15306. setClear: function ( stencil ) {
  15307. if ( currentStencilClear !== stencil ) {
  15308. gl.clearStencil( stencil );
  15309. currentStencilClear = stencil;
  15310. }
  15311. },
  15312. reset: function () {
  15313. locked = false;
  15314. currentStencilMask = null;
  15315. currentStencilFunc = null;
  15316. currentStencilRef = null;
  15317. currentStencilFuncMask = null;
  15318. currentStencilFail = null;
  15319. currentStencilZFail = null;
  15320. currentStencilZPass = null;
  15321. currentStencilClear = null;
  15322. }
  15323. };
  15324. }
  15325. //
  15326. var colorBuffer = new ColorBuffer();
  15327. var depthBuffer = new DepthBuffer();
  15328. var stencilBuffer = new StencilBuffer();
  15329. var maxVertexAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15330. var newAttributes = new Uint8Array( maxVertexAttributes );
  15331. var enabledAttributes = new Uint8Array( maxVertexAttributes );
  15332. var attributeDivisors = new Uint8Array( maxVertexAttributes );
  15333. var capabilities = {};
  15334. var compressedTextureFormats = null;
  15335. var currentBlending = null;
  15336. var currentBlendEquation = null;
  15337. var currentBlendSrc = null;
  15338. var currentBlendDst = null;
  15339. var currentBlendEquationAlpha = null;
  15340. var currentBlendSrcAlpha = null;
  15341. var currentBlendDstAlpha = null;
  15342. var currentPremultipledAlpha = false;
  15343. var currentFlipSided = null;
  15344. var currentCullFace = null;
  15345. var currentLineWidth = null;
  15346. var currentPolygonOffsetFactor = null;
  15347. var currentPolygonOffsetUnits = null;
  15348. var currentScissorTest = null;
  15349. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15350. var version = parseFloat( /^WebGL\ ([0-9])/.exec( gl.getParameter( gl.VERSION ) )[ 1 ] );
  15351. var lineWidthAvailable = parseFloat( version ) >= 1.0;
  15352. var currentTextureSlot = null;
  15353. var currentBoundTextures = {};
  15354. var currentScissor = new Vector4();
  15355. var currentViewport = new Vector4();
  15356. function createTexture( type, target, count ) {
  15357. var data = new Uint8Array( 4 ); // 4 is required to match default unpack alignment of 4.
  15358. var texture = gl.createTexture();
  15359. gl.bindTexture( type, texture );
  15360. gl.texParameteri( type, gl.TEXTURE_MIN_FILTER, gl.NEAREST );
  15361. gl.texParameteri( type, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
  15362. for ( var i = 0; i < count; i ++ ) {
  15363. gl.texImage2D( target + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, data );
  15364. }
  15365. return texture;
  15366. }
  15367. var emptyTextures = {};
  15368. emptyTextures[ gl.TEXTURE_2D ] = createTexture( gl.TEXTURE_2D, gl.TEXTURE_2D, 1 );
  15369. emptyTextures[ gl.TEXTURE_CUBE_MAP ] = createTexture( gl.TEXTURE_CUBE_MAP, gl.TEXTURE_CUBE_MAP_POSITIVE_X, 6 );
  15370. //
  15371. function init() {
  15372. colorBuffer.setClear( 0, 0, 0, 1 );
  15373. depthBuffer.setClear( 1 );
  15374. stencilBuffer.setClear( 0 );
  15375. enable( gl.DEPTH_TEST );
  15376. setDepthFunc( LessEqualDepth );
  15377. setFlipSided( false );
  15378. setCullFace( CullFaceBack );
  15379. enable( gl.CULL_FACE );
  15380. enable( gl.BLEND );
  15381. setBlending( NormalBlending );
  15382. }
  15383. function initAttributes() {
  15384. for ( var i = 0, l = newAttributes.length; i < l; i ++ ) {
  15385. newAttributes[ i ] = 0;
  15386. }
  15387. }
  15388. function enableAttribute( attribute ) {
  15389. newAttributes[ attribute ] = 1;
  15390. if ( enabledAttributes[ attribute ] === 0 ) {
  15391. gl.enableVertexAttribArray( attribute );
  15392. enabledAttributes[ attribute ] = 1;
  15393. }
  15394. if ( attributeDivisors[ attribute ] !== 0 ) {
  15395. var extension = extensions.get( 'ANGLE_instanced_arrays' );
  15396. extension.vertexAttribDivisorANGLE( attribute, 0 );
  15397. attributeDivisors[ attribute ] = 0;
  15398. }
  15399. }
  15400. function enableAttributeAndDivisor( attribute, meshPerAttribute, extension ) {
  15401. newAttributes[ attribute ] = 1;
  15402. if ( enabledAttributes[ attribute ] === 0 ) {
  15403. gl.enableVertexAttribArray( attribute );
  15404. enabledAttributes[ attribute ] = 1;
  15405. }
  15406. if ( attributeDivisors[ attribute ] !== meshPerAttribute ) {
  15407. extension.vertexAttribDivisorANGLE( attribute, meshPerAttribute );
  15408. attributeDivisors[ attribute ] = meshPerAttribute;
  15409. }
  15410. }
  15411. function disableUnusedAttributes() {
  15412. for ( var i = 0, l = enabledAttributes.length; i !== l; ++ i ) {
  15413. if ( enabledAttributes[ i ] !== newAttributes[ i ] ) {
  15414. gl.disableVertexAttribArray( i );
  15415. enabledAttributes[ i ] = 0;
  15416. }
  15417. }
  15418. }
  15419. function enable( id ) {
  15420. if ( capabilities[ id ] !== true ) {
  15421. gl.enable( id );
  15422. capabilities[ id ] = true;
  15423. }
  15424. }
  15425. function disable( id ) {
  15426. if ( capabilities[ id ] !== false ) {
  15427. gl.disable( id );
  15428. capabilities[ id ] = false;
  15429. }
  15430. }
  15431. function getCompressedTextureFormats() {
  15432. if ( compressedTextureFormats === null ) {
  15433. compressedTextureFormats = [];
  15434. if ( extensions.get( 'WEBGL_compressed_texture_pvrtc' ) ||
  15435. extensions.get( 'WEBGL_compressed_texture_s3tc' ) ||
  15436. extensions.get( 'WEBGL_compressed_texture_etc1' ) ) {
  15437. var formats = gl.getParameter( gl.COMPRESSED_TEXTURE_FORMATS );
  15438. for ( var i = 0; i < formats.length; i ++ ) {
  15439. compressedTextureFormats.push( formats[ i ] );
  15440. }
  15441. }
  15442. }
  15443. return compressedTextureFormats;
  15444. }
  15445. function setBlending( blending, blendEquation, blendSrc, blendDst, blendEquationAlpha, blendSrcAlpha, blendDstAlpha, premultipliedAlpha ) {
  15446. if ( blending !== NoBlending ) {
  15447. enable( gl.BLEND );
  15448. } else {
  15449. disable( gl.BLEND );
  15450. }
  15451. if ( blending !== currentBlending || premultipliedAlpha !== currentPremultipledAlpha ) {
  15452. if ( blending === AdditiveBlending ) {
  15453. if ( premultipliedAlpha ) {
  15454. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15455. gl.blendFuncSeparate( gl.ONE, gl.ONE, gl.ONE, gl.ONE );
  15456. } else {
  15457. gl.blendEquation( gl.FUNC_ADD );
  15458. gl.blendFunc( gl.SRC_ALPHA, gl.ONE );
  15459. }
  15460. } else if ( blending === SubtractiveBlending ) {
  15461. if ( premultipliedAlpha ) {
  15462. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15463. gl.blendFuncSeparate( gl.ZERO, gl.ZERO, gl.ONE_MINUS_SRC_COLOR, gl.ONE_MINUS_SRC_ALPHA );
  15464. } else {
  15465. gl.blendEquation( gl.FUNC_ADD );
  15466. gl.blendFunc( gl.ZERO, gl.ONE_MINUS_SRC_COLOR );
  15467. }
  15468. } else if ( blending === MultiplyBlending ) {
  15469. if ( premultipliedAlpha ) {
  15470. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15471. gl.blendFuncSeparate( gl.ZERO, gl.SRC_COLOR, gl.ZERO, gl.SRC_ALPHA );
  15472. } else {
  15473. gl.blendEquation( gl.FUNC_ADD );
  15474. gl.blendFunc( gl.ZERO, gl.SRC_COLOR );
  15475. }
  15476. } else {
  15477. if ( premultipliedAlpha ) {
  15478. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15479. gl.blendFuncSeparate( gl.ONE, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15480. } else {
  15481. gl.blendEquationSeparate( gl.FUNC_ADD, gl.FUNC_ADD );
  15482. gl.blendFuncSeparate( gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA );
  15483. }
  15484. }
  15485. currentBlending = blending;
  15486. currentPremultipledAlpha = premultipliedAlpha;
  15487. }
  15488. if ( blending === CustomBlending ) {
  15489. blendEquationAlpha = blendEquationAlpha || blendEquation;
  15490. blendSrcAlpha = blendSrcAlpha || blendSrc;
  15491. blendDstAlpha = blendDstAlpha || blendDst;
  15492. if ( blendEquation !== currentBlendEquation || blendEquationAlpha !== currentBlendEquationAlpha ) {
  15493. gl.blendEquationSeparate( paramThreeToGL( blendEquation ), paramThreeToGL( blendEquationAlpha ) );
  15494. currentBlendEquation = blendEquation;
  15495. currentBlendEquationAlpha = blendEquationAlpha;
  15496. }
  15497. if ( blendSrc !== currentBlendSrc || blendDst !== currentBlendDst || blendSrcAlpha !== currentBlendSrcAlpha || blendDstAlpha !== currentBlendDstAlpha ) {
  15498. gl.blendFuncSeparate( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ), paramThreeToGL( blendSrcAlpha ), paramThreeToGL( blendDstAlpha ) );
  15499. currentBlendSrc = blendSrc;
  15500. currentBlendDst = blendDst;
  15501. currentBlendSrcAlpha = blendSrcAlpha;
  15502. currentBlendDstAlpha = blendDstAlpha;
  15503. }
  15504. } else {
  15505. currentBlendEquation = null;
  15506. currentBlendSrc = null;
  15507. currentBlendDst = null;
  15508. currentBlendEquationAlpha = null;
  15509. currentBlendSrcAlpha = null;
  15510. currentBlendDstAlpha = null;
  15511. }
  15512. }
  15513. // TODO Deprecate
  15514. function setColorWrite( colorWrite ) {
  15515. colorBuffer.setMask( colorWrite );
  15516. }
  15517. function setDepthTest( depthTest ) {
  15518. depthBuffer.setTest( depthTest );
  15519. }
  15520. function setDepthWrite( depthWrite ) {
  15521. depthBuffer.setMask( depthWrite );
  15522. }
  15523. function setDepthFunc( depthFunc ) {
  15524. depthBuffer.setFunc( depthFunc );
  15525. }
  15526. function setStencilTest( stencilTest ) {
  15527. stencilBuffer.setTest( stencilTest );
  15528. }
  15529. function setStencilWrite( stencilWrite ) {
  15530. stencilBuffer.setMask( stencilWrite );
  15531. }
  15532. function setStencilFunc( stencilFunc, stencilRef, stencilMask ) {
  15533. stencilBuffer.setFunc( stencilFunc, stencilRef, stencilMask );
  15534. }
  15535. function setStencilOp( stencilFail, stencilZFail, stencilZPass ) {
  15536. stencilBuffer.setOp( stencilFail, stencilZFail, stencilZPass );
  15537. }
  15538. //
  15539. function setFlipSided( flipSided ) {
  15540. if ( currentFlipSided !== flipSided ) {
  15541. if ( flipSided ) {
  15542. gl.frontFace( gl.CW );
  15543. } else {
  15544. gl.frontFace( gl.CCW );
  15545. }
  15546. currentFlipSided = flipSided;
  15547. }
  15548. }
  15549. function setCullFace( cullFace ) {
  15550. if ( cullFace !== CullFaceNone ) {
  15551. enable( gl.CULL_FACE );
  15552. if ( cullFace !== currentCullFace ) {
  15553. if ( cullFace === CullFaceBack ) {
  15554. gl.cullFace( gl.BACK );
  15555. } else if ( cullFace === CullFaceFront ) {
  15556. gl.cullFace( gl.FRONT );
  15557. } else {
  15558. gl.cullFace( gl.FRONT_AND_BACK );
  15559. }
  15560. }
  15561. } else {
  15562. disable( gl.CULL_FACE );
  15563. }
  15564. currentCullFace = cullFace;
  15565. }
  15566. function setLineWidth( width ) {
  15567. if ( width !== currentLineWidth ) {
  15568. if ( lineWidthAvailable ) gl.lineWidth( width );
  15569. currentLineWidth = width;
  15570. }
  15571. }
  15572. function setPolygonOffset( polygonOffset, factor, units ) {
  15573. if ( polygonOffset ) {
  15574. enable( gl.POLYGON_OFFSET_FILL );
  15575. if ( currentPolygonOffsetFactor !== factor || currentPolygonOffsetUnits !== units ) {
  15576. gl.polygonOffset( factor, units );
  15577. currentPolygonOffsetFactor = factor;
  15578. currentPolygonOffsetUnits = units;
  15579. }
  15580. } else {
  15581. disable( gl.POLYGON_OFFSET_FILL );
  15582. }
  15583. }
  15584. function getScissorTest() {
  15585. return currentScissorTest;
  15586. }
  15587. function setScissorTest( scissorTest ) {
  15588. currentScissorTest = scissorTest;
  15589. if ( scissorTest ) {
  15590. enable( gl.SCISSOR_TEST );
  15591. } else {
  15592. disable( gl.SCISSOR_TEST );
  15593. }
  15594. }
  15595. // texture
  15596. function activeTexture( webglSlot ) {
  15597. if ( webglSlot === undefined ) webglSlot = gl.TEXTURE0 + maxTextures - 1;
  15598. if ( currentTextureSlot !== webglSlot ) {
  15599. gl.activeTexture( webglSlot );
  15600. currentTextureSlot = webglSlot;
  15601. }
  15602. }
  15603. function bindTexture( webglType, webglTexture ) {
  15604. if ( currentTextureSlot === null ) {
  15605. activeTexture();
  15606. }
  15607. var boundTexture = currentBoundTextures[ currentTextureSlot ];
  15608. if ( boundTexture === undefined ) {
  15609. boundTexture = { type: undefined, texture: undefined };
  15610. currentBoundTextures[ currentTextureSlot ] = boundTexture;
  15611. }
  15612. if ( boundTexture.type !== webglType || boundTexture.texture !== webglTexture ) {
  15613. gl.bindTexture( webglType, webglTexture || emptyTextures[ webglType ] );
  15614. boundTexture.type = webglType;
  15615. boundTexture.texture = webglTexture;
  15616. }
  15617. }
  15618. function compressedTexImage2D() {
  15619. try {
  15620. gl.compressedTexImage2D.apply( gl, arguments );
  15621. } catch ( error ) {
  15622. console.error( error );
  15623. }
  15624. }
  15625. function texImage2D() {
  15626. try {
  15627. gl.texImage2D.apply( gl, arguments );
  15628. } catch ( error ) {
  15629. console.error( error );
  15630. }
  15631. }
  15632. //
  15633. function scissor( scissor ) {
  15634. if ( currentScissor.equals( scissor ) === false ) {
  15635. gl.scissor( scissor.x, scissor.y, scissor.z, scissor.w );
  15636. currentScissor.copy( scissor );
  15637. }
  15638. }
  15639. function viewport( viewport ) {
  15640. if ( currentViewport.equals( viewport ) === false ) {
  15641. gl.viewport( viewport.x, viewport.y, viewport.z, viewport.w );
  15642. currentViewport.copy( viewport );
  15643. }
  15644. }
  15645. //
  15646. function reset() {
  15647. for ( var i = 0; i < enabledAttributes.length; i ++ ) {
  15648. if ( enabledAttributes[ i ] === 1 ) {
  15649. gl.disableVertexAttribArray( i );
  15650. enabledAttributes[ i ] = 0;
  15651. }
  15652. }
  15653. capabilities = {};
  15654. compressedTextureFormats = null;
  15655. currentTextureSlot = null;
  15656. currentBoundTextures = {};
  15657. currentBlending = null;
  15658. currentFlipSided = null;
  15659. currentCullFace = null;
  15660. colorBuffer.reset();
  15661. depthBuffer.reset();
  15662. stencilBuffer.reset();
  15663. }
  15664. return {
  15665. buffers: {
  15666. color: colorBuffer,
  15667. depth: depthBuffer,
  15668. stencil: stencilBuffer
  15669. },
  15670. init: init,
  15671. initAttributes: initAttributes,
  15672. enableAttribute: enableAttribute,
  15673. enableAttributeAndDivisor: enableAttributeAndDivisor,
  15674. disableUnusedAttributes: disableUnusedAttributes,
  15675. enable: enable,
  15676. disable: disable,
  15677. getCompressedTextureFormats: getCompressedTextureFormats,
  15678. setBlending: setBlending,
  15679. setColorWrite: setColorWrite,
  15680. setDepthTest: setDepthTest,
  15681. setDepthWrite: setDepthWrite,
  15682. setDepthFunc: setDepthFunc,
  15683. setStencilTest: setStencilTest,
  15684. setStencilWrite: setStencilWrite,
  15685. setStencilFunc: setStencilFunc,
  15686. setStencilOp: setStencilOp,
  15687. setFlipSided: setFlipSided,
  15688. setCullFace: setCullFace,
  15689. setLineWidth: setLineWidth,
  15690. setPolygonOffset: setPolygonOffset,
  15691. getScissorTest: getScissorTest,
  15692. setScissorTest: setScissorTest,
  15693. activeTexture: activeTexture,
  15694. bindTexture: bindTexture,
  15695. compressedTexImage2D: compressedTexImage2D,
  15696. texImage2D: texImage2D,
  15697. scissor: scissor,
  15698. viewport: viewport,
  15699. reset: reset
  15700. };
  15701. }
  15702. /**
  15703. * @author mrdoob / http://mrdoob.com/
  15704. */
  15705. function WebGLCapabilities( gl, extensions, parameters ) {
  15706. var maxAnisotropy;
  15707. function getMaxAnisotropy() {
  15708. if ( maxAnisotropy !== undefined ) return maxAnisotropy;
  15709. var extension = extensions.get( 'EXT_texture_filter_anisotropic' );
  15710. if ( extension !== null ) {
  15711. maxAnisotropy = gl.getParameter( extension.MAX_TEXTURE_MAX_ANISOTROPY_EXT );
  15712. } else {
  15713. maxAnisotropy = 0;
  15714. }
  15715. return maxAnisotropy;
  15716. }
  15717. function getMaxPrecision( precision ) {
  15718. if ( precision === 'highp' ) {
  15719. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.HIGH_FLOAT ).precision > 0 &&
  15720. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.HIGH_FLOAT ).precision > 0 ) {
  15721. return 'highp';
  15722. }
  15723. precision = 'mediump';
  15724. }
  15725. if ( precision === 'mediump' ) {
  15726. if ( gl.getShaderPrecisionFormat( gl.VERTEX_SHADER, gl.MEDIUM_FLOAT ).precision > 0 &&
  15727. gl.getShaderPrecisionFormat( gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ).precision > 0 ) {
  15728. return 'mediump';
  15729. }
  15730. }
  15731. return 'lowp';
  15732. }
  15733. var precision = parameters.precision !== undefined ? parameters.precision : 'highp';
  15734. var maxPrecision = getMaxPrecision( precision );
  15735. if ( maxPrecision !== precision ) {
  15736. console.warn( 'THREE.WebGLRenderer:', precision, 'not supported, using', maxPrecision, 'instead.' );
  15737. precision = maxPrecision;
  15738. }
  15739. var logarithmicDepthBuffer = parameters.logarithmicDepthBuffer === true && !! extensions.get( 'EXT_frag_depth' );
  15740. var maxTextures = gl.getParameter( gl.MAX_TEXTURE_IMAGE_UNITS );
  15741. var maxVertexTextures = gl.getParameter( gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  15742. var maxTextureSize = gl.getParameter( gl.MAX_TEXTURE_SIZE );
  15743. var maxCubemapSize = gl.getParameter( gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  15744. var maxAttributes = gl.getParameter( gl.MAX_VERTEX_ATTRIBS );
  15745. var maxVertexUniforms = gl.getParameter( gl.MAX_VERTEX_UNIFORM_VECTORS );
  15746. var maxVaryings = gl.getParameter( gl.MAX_VARYING_VECTORS );
  15747. var maxFragmentUniforms = gl.getParameter( gl.MAX_FRAGMENT_UNIFORM_VECTORS );
  15748. var vertexTextures = maxVertexTextures > 0;
  15749. var floatFragmentTextures = !! extensions.get( 'OES_texture_float' );
  15750. var floatVertexTextures = vertexTextures && floatFragmentTextures;
  15751. return {
  15752. getMaxAnisotropy: getMaxAnisotropy,
  15753. getMaxPrecision: getMaxPrecision,
  15754. precision: precision,
  15755. logarithmicDepthBuffer: logarithmicDepthBuffer,
  15756. maxTextures: maxTextures,
  15757. maxVertexTextures: maxVertexTextures,
  15758. maxTextureSize: maxTextureSize,
  15759. maxCubemapSize: maxCubemapSize,
  15760. maxAttributes: maxAttributes,
  15761. maxVertexUniforms: maxVertexUniforms,
  15762. maxVaryings: maxVaryings,
  15763. maxFragmentUniforms: maxFragmentUniforms,
  15764. vertexTextures: vertexTextures,
  15765. floatFragmentTextures: floatFragmentTextures,
  15766. floatVertexTextures: floatVertexTextures
  15767. };
  15768. }
  15769. /**
  15770. * @author mrdoob / http://mrdoob.com/
  15771. */
  15772. function WebGLExtensions( gl ) {
  15773. var extensions = {};
  15774. return {
  15775. get: function ( name ) {
  15776. if ( extensions[ name ] !== undefined ) {
  15777. return extensions[ name ];
  15778. }
  15779. var extension;
  15780. switch ( name ) {
  15781. case 'WEBGL_depth_texture':
  15782. extension = gl.getExtension( 'WEBGL_depth_texture' ) || gl.getExtension( 'MOZ_WEBGL_depth_texture' ) || gl.getExtension( 'WEBKIT_WEBGL_depth_texture' );
  15783. break;
  15784. case 'EXT_texture_filter_anisotropic':
  15785. extension = gl.getExtension( 'EXT_texture_filter_anisotropic' ) || gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15786. break;
  15787. case 'WEBGL_compressed_texture_s3tc':
  15788. extension = gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15789. break;
  15790. case 'WEBGL_compressed_texture_pvrtc':
  15791. extension = gl.getExtension( 'WEBGL_compressed_texture_pvrtc' ) || gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_pvrtc' );
  15792. break;
  15793. case 'WEBGL_compressed_texture_etc1':
  15794. extension = gl.getExtension( 'WEBGL_compressed_texture_etc1' );
  15795. break;
  15796. default:
  15797. extension = gl.getExtension( name );
  15798. }
  15799. if ( extension === null ) {
  15800. console.warn( 'THREE.WebGLRenderer: ' + name + ' extension not supported.' );
  15801. }
  15802. extensions[ name ] = extension;
  15803. return extension;
  15804. }
  15805. };
  15806. }
  15807. /**
  15808. * @author tschw
  15809. */
  15810. function WebGLClipping() {
  15811. var scope = this,
  15812. globalState = null,
  15813. numGlobalPlanes = 0,
  15814. localClippingEnabled = false,
  15815. renderingShadows = false,
  15816. plane = new Plane(),
  15817. viewNormalMatrix = new Matrix3(),
  15818. uniform = { value: null, needsUpdate: false };
  15819. this.uniform = uniform;
  15820. this.numPlanes = 0;
  15821. this.numIntersection = 0;
  15822. this.init = function( planes, enableLocalClipping, camera ) {
  15823. var enabled =
  15824. planes.length !== 0 ||
  15825. enableLocalClipping ||
  15826. // enable state of previous frame - the clipping code has to
  15827. // run another frame in order to reset the state:
  15828. numGlobalPlanes !== 0 ||
  15829. localClippingEnabled;
  15830. localClippingEnabled = enableLocalClipping;
  15831. globalState = projectPlanes( planes, camera, 0 );
  15832. numGlobalPlanes = planes.length;
  15833. return enabled;
  15834. };
  15835. this.beginShadows = function() {
  15836. renderingShadows = true;
  15837. projectPlanes( null );
  15838. };
  15839. this.endShadows = function() {
  15840. renderingShadows = false;
  15841. resetGlobalState();
  15842. };
  15843. this.setState = function( planes, clipIntersection, clipShadows, camera, cache, fromCache ) {
  15844. if ( ! localClippingEnabled ||
  15845. planes === null || planes.length === 0 ||
  15846. renderingShadows && ! clipShadows ) {
  15847. // there's no local clipping
  15848. if ( renderingShadows ) {
  15849. // there's no global clipping
  15850. projectPlanes( null );
  15851. } else {
  15852. resetGlobalState();
  15853. }
  15854. } else {
  15855. var nGlobal = renderingShadows ? 0 : numGlobalPlanes,
  15856. lGlobal = nGlobal * 4,
  15857. dstArray = cache.clippingState || null;
  15858. uniform.value = dstArray; // ensure unique state
  15859. dstArray = projectPlanes( planes, camera, lGlobal, fromCache );
  15860. for ( var i = 0; i !== lGlobal; ++ i ) {
  15861. dstArray[ i ] = globalState[ i ];
  15862. }
  15863. cache.clippingState = dstArray;
  15864. this.numIntersection = clipIntersection ? this.numPlanes : 0;
  15865. this.numPlanes += nGlobal;
  15866. }
  15867. };
  15868. function resetGlobalState() {
  15869. if ( uniform.value !== globalState ) {
  15870. uniform.value = globalState;
  15871. uniform.needsUpdate = numGlobalPlanes > 0;
  15872. }
  15873. scope.numPlanes = numGlobalPlanes;
  15874. scope.numIntersection = 0;
  15875. }
  15876. function projectPlanes( planes, camera, dstOffset, skipTransform ) {
  15877. var nPlanes = planes !== null ? planes.length : 0,
  15878. dstArray = null;
  15879. if ( nPlanes !== 0 ) {
  15880. dstArray = uniform.value;
  15881. if ( skipTransform !== true || dstArray === null ) {
  15882. var flatSize = dstOffset + nPlanes * 4,
  15883. viewMatrix = camera.matrixWorldInverse;
  15884. viewNormalMatrix.getNormalMatrix( viewMatrix );
  15885. if ( dstArray === null || dstArray.length < flatSize ) {
  15886. dstArray = new Float32Array( flatSize );
  15887. }
  15888. for ( var i = 0, i4 = dstOffset;
  15889. i !== nPlanes; ++ i, i4 += 4 ) {
  15890. plane.copy( planes[ i ] ).
  15891. applyMatrix4( viewMatrix, viewNormalMatrix );
  15892. plane.normal.toArray( dstArray, i4 );
  15893. dstArray[ i4 + 3 ] = plane.constant;
  15894. }
  15895. }
  15896. uniform.value = dstArray;
  15897. uniform.needsUpdate = true;
  15898. }
  15899. scope.numPlanes = nPlanes;
  15900. return dstArray;
  15901. }
  15902. }
  15903. /**
  15904. * @author supereggbert / http://www.paulbrunt.co.uk/
  15905. * @author mrdoob / http://mrdoob.com/
  15906. * @author alteredq / http://alteredqualia.com/
  15907. * @author szimek / https://github.com/szimek/
  15908. * @author tschw
  15909. */
  15910. function WebGLRenderer( parameters ) {
  15911. console.log( 'THREE.WebGLRenderer', REVISION );
  15912. parameters = parameters || {};
  15913. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' ),
  15914. _context = parameters.context !== undefined ? parameters.context : null,
  15915. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  15916. _depth = parameters.depth !== undefined ? parameters.depth : true,
  15917. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  15918. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  15919. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  15920. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false;
  15921. var lights = [];
  15922. var opaqueObjects = [];
  15923. var opaqueObjectsLastIndex = - 1;
  15924. var transparentObjects = [];
  15925. var transparentObjectsLastIndex = - 1;
  15926. var morphInfluences = new Float32Array( 8 );
  15927. var sprites = [];
  15928. var lensFlares = [];
  15929. // public properties
  15930. this.domElement = _canvas;
  15931. this.context = null;
  15932. // clearing
  15933. this.autoClear = true;
  15934. this.autoClearColor = true;
  15935. this.autoClearDepth = true;
  15936. this.autoClearStencil = true;
  15937. // scene graph
  15938. this.sortObjects = true;
  15939. // user-defined clipping
  15940. this.clippingPlanes = [];
  15941. this.localClippingEnabled = false;
  15942. // physically based shading
  15943. this.gammaFactor = 2.0; // for backwards compatibility
  15944. this.gammaInput = false;
  15945. this.gammaOutput = false;
  15946. // physical lights
  15947. this.physicallyCorrectLights = false;
  15948. // tone mapping
  15949. this.toneMapping = LinearToneMapping;
  15950. this.toneMappingExposure = 1.0;
  15951. this.toneMappingWhitePoint = 1.0;
  15952. // morphs
  15953. this.maxMorphTargets = 8;
  15954. this.maxMorphNormals = 4;
  15955. // internal properties
  15956. var _this = this,
  15957. // internal state cache
  15958. _currentProgram = null,
  15959. _currentRenderTarget = null,
  15960. _currentFramebuffer = null,
  15961. _currentMaterialId = - 1,
  15962. _currentGeometryProgram = '',
  15963. _currentCamera = null,
  15964. _currentScissor = new Vector4(),
  15965. _currentScissorTest = null,
  15966. _currentViewport = new Vector4(),
  15967. //
  15968. _usedTextureUnits = 0,
  15969. //
  15970. _clearColor = new Color( 0x000000 ),
  15971. _clearAlpha = 0,
  15972. _width = _canvas.width,
  15973. _height = _canvas.height,
  15974. _pixelRatio = 1,
  15975. _scissor = new Vector4( 0, 0, _width, _height ),
  15976. _scissorTest = false,
  15977. _viewport = new Vector4( 0, 0, _width, _height ),
  15978. // frustum
  15979. _frustum = new Frustum(),
  15980. // clipping
  15981. _clipping = new WebGLClipping(),
  15982. _clippingEnabled = false,
  15983. _localClippingEnabled = false,
  15984. _sphere = new Sphere(),
  15985. // camera matrices cache
  15986. _projScreenMatrix = new Matrix4(),
  15987. _vector3 = new Vector3(),
  15988. _matrix4 = new Matrix4(),
  15989. _matrix42 = new Matrix4(),
  15990. // light arrays cache
  15991. _lights = {
  15992. hash: '',
  15993. ambient: [ 0, 0, 0 ],
  15994. directional: [],
  15995. directionalShadowMap: [],
  15996. directionalShadowMatrix: [],
  15997. spot: [],
  15998. spotShadowMap: [],
  15999. spotShadowMatrix: [],
  16000. rectArea: [],
  16001. point: [],
  16002. pointShadowMap: [],
  16003. pointShadowMatrix: [],
  16004. hemi: [],
  16005. shadows: []
  16006. },
  16007. // info
  16008. _infoRender = {
  16009. calls: 0,
  16010. vertices: 0,
  16011. faces: 0,
  16012. points: 0
  16013. };
  16014. this.info = {
  16015. render: _infoRender,
  16016. memory: {
  16017. geometries: 0,
  16018. textures: 0
  16019. },
  16020. programs: null
  16021. };
  16022. // initialize
  16023. var _gl;
  16024. try {
  16025. var attributes = {
  16026. alpha: _alpha,
  16027. depth: _depth,
  16028. stencil: _stencil,
  16029. antialias: _antialias,
  16030. premultipliedAlpha: _premultipliedAlpha,
  16031. preserveDrawingBuffer: _preserveDrawingBuffer
  16032. };
  16033. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  16034. if ( _gl === null ) {
  16035. if ( _canvas.getContext( 'webgl' ) !== null ) {
  16036. throw 'Error creating WebGL context with your selected attributes.';
  16037. } else {
  16038. throw 'Error creating WebGL context.';
  16039. }
  16040. }
  16041. // Some experimental-webgl implementations do not have getShaderPrecisionFormat
  16042. if ( _gl.getShaderPrecisionFormat === undefined ) {
  16043. _gl.getShaderPrecisionFormat = function () {
  16044. return { 'rangeMin': 1, 'rangeMax': 1, 'precision': 1 };
  16045. };
  16046. }
  16047. _canvas.addEventListener( 'webglcontextlost', onContextLost, false );
  16048. } catch ( error ) {
  16049. console.error( 'THREE.WebGLRenderer: ' + error );
  16050. }
  16051. var extensions = new WebGLExtensions( _gl );
  16052. extensions.get( 'WEBGL_depth_texture' );
  16053. extensions.get( 'OES_texture_float' );
  16054. extensions.get( 'OES_texture_float_linear' );
  16055. extensions.get( 'OES_texture_half_float' );
  16056. extensions.get( 'OES_texture_half_float_linear' );
  16057. extensions.get( 'OES_standard_derivatives' );
  16058. extensions.get( 'ANGLE_instanced_arrays' );
  16059. if ( extensions.get( 'OES_element_index_uint' ) ) {
  16060. BufferGeometry.MaxIndex = 4294967296;
  16061. }
  16062. var capabilities = new WebGLCapabilities( _gl, extensions, parameters );
  16063. var state = new WebGLState( _gl, extensions, paramThreeToGL );
  16064. var properties = new WebGLProperties();
  16065. var textures = new WebGLTextures( _gl, extensions, state, properties, capabilities, paramThreeToGL, this.info );
  16066. var objects = new WebGLObjects( _gl, properties, this.info );
  16067. var programCache = new WebGLPrograms( this, capabilities );
  16068. var lightCache = new WebGLLights();
  16069. this.info.programs = programCache.programs;
  16070. var bufferRenderer = new WebGLBufferRenderer( _gl, extensions, _infoRender );
  16071. var indexedBufferRenderer = new WebGLIndexedBufferRenderer( _gl, extensions, _infoRender );
  16072. //
  16073. var backgroundCamera = new OrthographicCamera( - 1, 1, 1, - 1, 0, 1 );
  16074. var backgroundCamera2 = new PerspectiveCamera();
  16075. var backgroundPlaneMesh = new Mesh(
  16076. new PlaneBufferGeometry( 2, 2 ),
  16077. new MeshBasicMaterial( { depthTest: false, depthWrite: false, fog: false } )
  16078. );
  16079. var backgroundBoxShader = ShaderLib[ 'cube' ];
  16080. var backgroundBoxMesh = new Mesh(
  16081. new BoxBufferGeometry( 5, 5, 5 ),
  16082. new ShaderMaterial( {
  16083. uniforms: backgroundBoxShader.uniforms,
  16084. vertexShader: backgroundBoxShader.vertexShader,
  16085. fragmentShader: backgroundBoxShader.fragmentShader,
  16086. side: BackSide,
  16087. depthTest: false,
  16088. depthWrite: false,
  16089. fog: false
  16090. } )
  16091. );
  16092. //
  16093. function getTargetPixelRatio() {
  16094. return _currentRenderTarget === null ? _pixelRatio : 1;
  16095. }
  16096. function setDefaultGLState() {
  16097. state.init();
  16098. state.scissor( _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio ) );
  16099. state.viewport( _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio ) );
  16100. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16101. }
  16102. function resetGLState() {
  16103. _currentProgram = null;
  16104. _currentCamera = null;
  16105. _currentGeometryProgram = '';
  16106. _currentMaterialId = - 1;
  16107. state.reset();
  16108. }
  16109. setDefaultGLState();
  16110. this.context = _gl;
  16111. this.capabilities = capabilities;
  16112. this.extensions = extensions;
  16113. this.properties = properties;
  16114. this.state = state;
  16115. // shadow map
  16116. var shadowMap = new WebGLShadowMap( this, _lights, objects, capabilities );
  16117. this.shadowMap = shadowMap;
  16118. // Plugins
  16119. var spritePlugin = new SpritePlugin( this, sprites );
  16120. var lensFlarePlugin = new LensFlarePlugin( this, lensFlares );
  16121. // API
  16122. this.getContext = function () {
  16123. return _gl;
  16124. };
  16125. this.getContextAttributes = function () {
  16126. return _gl.getContextAttributes();
  16127. };
  16128. this.forceContextLoss = function () {
  16129. extensions.get( 'WEBGL_lose_context' ).loseContext();
  16130. };
  16131. this.getMaxAnisotropy = function () {
  16132. return capabilities.getMaxAnisotropy();
  16133. };
  16134. this.getPrecision = function () {
  16135. return capabilities.precision;
  16136. };
  16137. this.getPixelRatio = function () {
  16138. return _pixelRatio;
  16139. };
  16140. this.setPixelRatio = function ( value ) {
  16141. if ( value === undefined ) return;
  16142. _pixelRatio = value;
  16143. this.setSize( _viewport.z, _viewport.w, false );
  16144. };
  16145. this.getSize = function () {
  16146. return {
  16147. width: _width,
  16148. height: _height
  16149. };
  16150. };
  16151. this.setSize = function ( width, height, updateStyle ) {
  16152. _width = width;
  16153. _height = height;
  16154. _canvas.width = width * _pixelRatio;
  16155. _canvas.height = height * _pixelRatio;
  16156. if ( updateStyle !== false ) {
  16157. _canvas.style.width = width + 'px';
  16158. _canvas.style.height = height + 'px';
  16159. }
  16160. this.setViewport( 0, 0, width, height );
  16161. };
  16162. this.setViewport = function ( x, y, width, height ) {
  16163. state.viewport( _viewport.set( x, y, width, height ) );
  16164. };
  16165. this.setScissor = function ( x, y, width, height ) {
  16166. state.scissor( _scissor.set( x, y, width, height ) );
  16167. };
  16168. this.setScissorTest = function ( boolean ) {
  16169. state.setScissorTest( _scissorTest = boolean );
  16170. };
  16171. // Clearing
  16172. this.getClearColor = function () {
  16173. return _clearColor;
  16174. };
  16175. this.setClearColor = function ( color, alpha ) {
  16176. _clearColor.set( color );
  16177. _clearAlpha = alpha !== undefined ? alpha : 1;
  16178. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16179. };
  16180. this.getClearAlpha = function () {
  16181. return _clearAlpha;
  16182. };
  16183. this.setClearAlpha = function ( alpha ) {
  16184. _clearAlpha = alpha;
  16185. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16186. };
  16187. this.clear = function ( color, depth, stencil ) {
  16188. var bits = 0;
  16189. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  16190. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  16191. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  16192. _gl.clear( bits );
  16193. };
  16194. this.clearColor = function () {
  16195. this.clear( true, false, false );
  16196. };
  16197. this.clearDepth = function () {
  16198. this.clear( false, true, false );
  16199. };
  16200. this.clearStencil = function () {
  16201. this.clear( false, false, true );
  16202. };
  16203. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  16204. this.setRenderTarget( renderTarget );
  16205. this.clear( color, depth, stencil );
  16206. };
  16207. // Reset
  16208. this.resetGLState = resetGLState;
  16209. this.dispose = function() {
  16210. transparentObjects = [];
  16211. transparentObjectsLastIndex = -1;
  16212. opaqueObjects = [];
  16213. opaqueObjectsLastIndex = -1;
  16214. _canvas.removeEventListener( 'webglcontextlost', onContextLost, false );
  16215. };
  16216. // Events
  16217. function onContextLost( event ) {
  16218. event.preventDefault();
  16219. resetGLState();
  16220. setDefaultGLState();
  16221. properties.clear();
  16222. }
  16223. function onMaterialDispose( event ) {
  16224. var material = event.target;
  16225. material.removeEventListener( 'dispose', onMaterialDispose );
  16226. deallocateMaterial( material );
  16227. }
  16228. // Buffer deallocation
  16229. function deallocateMaterial( material ) {
  16230. releaseMaterialProgramReference( material );
  16231. properties.delete( material );
  16232. }
  16233. function releaseMaterialProgramReference( material ) {
  16234. var programInfo = properties.get( material ).program;
  16235. material.program = undefined;
  16236. if ( programInfo !== undefined ) {
  16237. programCache.releaseProgram( programInfo );
  16238. }
  16239. }
  16240. // Buffer rendering
  16241. this.renderBufferImmediate = function ( object, program, material ) {
  16242. state.initAttributes();
  16243. var buffers = properties.get( object );
  16244. if ( object.hasPositions && ! buffers.position ) buffers.position = _gl.createBuffer();
  16245. if ( object.hasNormals && ! buffers.normal ) buffers.normal = _gl.createBuffer();
  16246. if ( object.hasUvs && ! buffers.uv ) buffers.uv = _gl.createBuffer();
  16247. if ( object.hasColors && ! buffers.color ) buffers.color = _gl.createBuffer();
  16248. var attributes = program.getAttributes();
  16249. if ( object.hasPositions ) {
  16250. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.position );
  16251. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  16252. state.enableAttribute( attributes.position );
  16253. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  16254. }
  16255. if ( object.hasNormals ) {
  16256. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.normal );
  16257. if ( ! material.isMeshPhongMaterial &&
  16258. ! material.isMeshStandardMaterial &&
  16259. ! material.isMeshNormalMaterial &&
  16260. material.shading === FlatShading ) {
  16261. for ( var i = 0, l = object.count * 3; i < l; i += 9 ) {
  16262. var array = object.normalArray;
  16263. var nx = ( array[ i + 0 ] + array[ i + 3 ] + array[ i + 6 ] ) / 3;
  16264. var ny = ( array[ i + 1 ] + array[ i + 4 ] + array[ i + 7 ] ) / 3;
  16265. var nz = ( array[ i + 2 ] + array[ i + 5 ] + array[ i + 8 ] ) / 3;
  16266. array[ i + 0 ] = nx;
  16267. array[ i + 1 ] = ny;
  16268. array[ i + 2 ] = nz;
  16269. array[ i + 3 ] = nx;
  16270. array[ i + 4 ] = ny;
  16271. array[ i + 5 ] = nz;
  16272. array[ i + 6 ] = nx;
  16273. array[ i + 7 ] = ny;
  16274. array[ i + 8 ] = nz;
  16275. }
  16276. }
  16277. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  16278. state.enableAttribute( attributes.normal );
  16279. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  16280. }
  16281. if ( object.hasUvs && material.map ) {
  16282. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.uv );
  16283. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  16284. state.enableAttribute( attributes.uv );
  16285. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  16286. }
  16287. if ( object.hasColors && material.vertexColors !== NoColors ) {
  16288. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffers.color );
  16289. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  16290. state.enableAttribute( attributes.color );
  16291. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  16292. }
  16293. state.disableUnusedAttributes();
  16294. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  16295. object.count = 0;
  16296. };
  16297. this.renderBufferDirect = function ( camera, fog, geometry, material, object, group ) {
  16298. setMaterial( material );
  16299. var program = setProgram( camera, fog, material, object );
  16300. var updateBuffers = false;
  16301. var geometryProgram = geometry.id + '_' + program.id + '_' + material.wireframe;
  16302. if ( geometryProgram !== _currentGeometryProgram ) {
  16303. _currentGeometryProgram = geometryProgram;
  16304. updateBuffers = true;
  16305. }
  16306. // morph targets
  16307. var morphTargetInfluences = object.morphTargetInfluences;
  16308. if ( morphTargetInfluences !== undefined ) {
  16309. var activeInfluences = [];
  16310. for ( var i = 0, l = morphTargetInfluences.length; i < l; i ++ ) {
  16311. var influence = morphTargetInfluences[ i ];
  16312. activeInfluences.push( [ influence, i ] );
  16313. }
  16314. activeInfluences.sort( absNumericalSort );
  16315. if ( activeInfluences.length > 8 ) {
  16316. activeInfluences.length = 8;
  16317. }
  16318. var morphAttributes = geometry.morphAttributes;
  16319. for ( var i = 0, l = activeInfluences.length; i < l; i ++ ) {
  16320. var influence = activeInfluences[ i ];
  16321. morphInfluences[ i ] = influence[ 0 ];
  16322. if ( influence[ 0 ] !== 0 ) {
  16323. var index = influence[ 1 ];
  16324. if ( material.morphTargets === true && morphAttributes.position ) geometry.addAttribute( 'morphTarget' + i, morphAttributes.position[ index ] );
  16325. if ( material.morphNormals === true && morphAttributes.normal ) geometry.addAttribute( 'morphNormal' + i, morphAttributes.normal[ index ] );
  16326. } else {
  16327. if ( material.morphTargets === true ) geometry.removeAttribute( 'morphTarget' + i );
  16328. if ( material.morphNormals === true ) geometry.removeAttribute( 'morphNormal' + i );
  16329. }
  16330. }
  16331. for ( var i = activeInfluences.length, il = morphInfluences.length; i < il; i ++ ) {
  16332. morphInfluences[ i ] = 0.0;
  16333. }
  16334. program.getUniforms().setValue(
  16335. _gl, 'morphTargetInfluences', morphInfluences );
  16336. updateBuffers = true;
  16337. }
  16338. //
  16339. var index = geometry.index;
  16340. var position = geometry.attributes.position;
  16341. var rangeFactor = 1;
  16342. if ( material.wireframe === true ) {
  16343. index = objects.getWireframeAttribute( geometry );
  16344. rangeFactor = 2;
  16345. }
  16346. var renderer;
  16347. if ( index !== null ) {
  16348. renderer = indexedBufferRenderer;
  16349. renderer.setIndex( index );
  16350. } else {
  16351. renderer = bufferRenderer;
  16352. }
  16353. if ( updateBuffers ) {
  16354. setupVertexAttributes( material, program, geometry );
  16355. if ( index !== null ) {
  16356. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, objects.getAttributeBuffer( index ) );
  16357. }
  16358. }
  16359. //
  16360. var dataCount = 0;
  16361. if ( index !== null ) {
  16362. dataCount = index.count;
  16363. } else if ( position !== undefined ) {
  16364. dataCount = position.count;
  16365. }
  16366. var rangeStart = geometry.drawRange.start * rangeFactor;
  16367. var rangeCount = geometry.drawRange.count * rangeFactor;
  16368. var groupStart = group !== null ? group.start * rangeFactor : 0;
  16369. var groupCount = group !== null ? group.count * rangeFactor : Infinity;
  16370. var drawStart = Math.max( rangeStart, groupStart );
  16371. var drawEnd = Math.min( dataCount, rangeStart + rangeCount, groupStart + groupCount ) - 1;
  16372. var drawCount = Math.max( 0, drawEnd - drawStart + 1 );
  16373. if ( drawCount === 0 ) return;
  16374. //
  16375. if ( object.isMesh ) {
  16376. if ( material.wireframe === true ) {
  16377. state.setLineWidth( material.wireframeLinewidth * getTargetPixelRatio() );
  16378. renderer.setMode( _gl.LINES );
  16379. } else {
  16380. switch ( object.drawMode ) {
  16381. case TrianglesDrawMode:
  16382. renderer.setMode( _gl.TRIANGLES );
  16383. break;
  16384. case TriangleStripDrawMode:
  16385. renderer.setMode( _gl.TRIANGLE_STRIP );
  16386. break;
  16387. case TriangleFanDrawMode:
  16388. renderer.setMode( _gl.TRIANGLE_FAN );
  16389. break;
  16390. }
  16391. }
  16392. } else if ( object.isLine ) {
  16393. var lineWidth = material.linewidth;
  16394. if ( lineWidth === undefined ) lineWidth = 1; // Not using Line*Material
  16395. state.setLineWidth( lineWidth * getTargetPixelRatio() );
  16396. if ( object.isLineSegments ) {
  16397. renderer.setMode( _gl.LINES );
  16398. } else {
  16399. renderer.setMode( _gl.LINE_STRIP );
  16400. }
  16401. } else if ( object.isPoints ) {
  16402. renderer.setMode( _gl.POINTS );
  16403. }
  16404. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16405. if ( geometry.maxInstancedCount > 0 ) {
  16406. renderer.renderInstances( geometry, drawStart, drawCount );
  16407. }
  16408. } else {
  16409. renderer.render( drawStart, drawCount );
  16410. }
  16411. };
  16412. function setupVertexAttributes( material, program, geometry, startIndex ) {
  16413. var extension;
  16414. if ( geometry && geometry.isInstancedBufferGeometry ) {
  16415. extension = extensions.get( 'ANGLE_instanced_arrays' );
  16416. if ( extension === null ) {
  16417. console.error( 'THREE.WebGLRenderer.setupVertexAttributes: using THREE.InstancedBufferGeometry but hardware does not support extension ANGLE_instanced_arrays.' );
  16418. return;
  16419. }
  16420. }
  16421. if ( startIndex === undefined ) startIndex = 0;
  16422. state.initAttributes();
  16423. var geometryAttributes = geometry.attributes;
  16424. var programAttributes = program.getAttributes();
  16425. var materialDefaultAttributeValues = material.defaultAttributeValues;
  16426. for ( var name in programAttributes ) {
  16427. var programAttribute = programAttributes[ name ];
  16428. if ( programAttribute >= 0 ) {
  16429. var geometryAttribute = geometryAttributes[ name ];
  16430. if ( geometryAttribute !== undefined ) {
  16431. var normalized = geometryAttribute.normalized;
  16432. var size = geometryAttribute.itemSize;
  16433. var attributeProperties = objects.getAttributeProperties( geometryAttribute );
  16434. var buffer = attributeProperties.__webglBuffer;
  16435. var type = attributeProperties.type;
  16436. var bytesPerElement = attributeProperties.bytesPerElement;
  16437. if ( geometryAttribute.isInterleavedBufferAttribute ) {
  16438. var data = geometryAttribute.data;
  16439. var stride = data.stride;
  16440. var offset = geometryAttribute.offset;
  16441. if ( data && data.isInstancedInterleavedBuffer ) {
  16442. state.enableAttributeAndDivisor( programAttribute, data.meshPerAttribute, extension );
  16443. if ( geometry.maxInstancedCount === undefined ) {
  16444. geometry.maxInstancedCount = data.meshPerAttribute * data.count;
  16445. }
  16446. } else {
  16447. state.enableAttribute( programAttribute );
  16448. }
  16449. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16450. _gl.vertexAttribPointer( programAttribute, size, type, normalized, stride * bytesPerElement, ( startIndex * stride + offset ) * bytesPerElement );
  16451. } else {
  16452. if ( geometryAttribute.isInstancedBufferAttribute ) {
  16453. state.enableAttributeAndDivisor( programAttribute, geometryAttribute.meshPerAttribute, extension );
  16454. if ( geometry.maxInstancedCount === undefined ) {
  16455. geometry.maxInstancedCount = geometryAttribute.meshPerAttribute * geometryAttribute.count;
  16456. }
  16457. } else {
  16458. state.enableAttribute( programAttribute );
  16459. }
  16460. _gl.bindBuffer( _gl.ARRAY_BUFFER, buffer );
  16461. _gl.vertexAttribPointer( programAttribute, size, type, normalized, 0, startIndex * size * bytesPerElement );
  16462. }
  16463. } else if ( materialDefaultAttributeValues !== undefined ) {
  16464. var value = materialDefaultAttributeValues[ name ];
  16465. if ( value !== undefined ) {
  16466. switch ( value.length ) {
  16467. case 2:
  16468. _gl.vertexAttrib2fv( programAttribute, value );
  16469. break;
  16470. case 3:
  16471. _gl.vertexAttrib3fv( programAttribute, value );
  16472. break;
  16473. case 4:
  16474. _gl.vertexAttrib4fv( programAttribute, value );
  16475. break;
  16476. default:
  16477. _gl.vertexAttrib1fv( programAttribute, value );
  16478. }
  16479. }
  16480. }
  16481. }
  16482. }
  16483. state.disableUnusedAttributes();
  16484. }
  16485. // Sorting
  16486. function absNumericalSort( a, b ) {
  16487. return Math.abs( b[ 0 ] ) - Math.abs( a[ 0 ] );
  16488. }
  16489. function painterSortStable( a, b ) {
  16490. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16491. return a.object.renderOrder - b.object.renderOrder;
  16492. } else if ( a.material.program && b.material.program && a.material.program !== b.material.program ) {
  16493. return a.material.program.id - b.material.program.id;
  16494. } else if ( a.material.id !== b.material.id ) {
  16495. return a.material.id - b.material.id;
  16496. } else if ( a.z !== b.z ) {
  16497. return a.z - b.z;
  16498. } else {
  16499. return a.id - b.id;
  16500. }
  16501. }
  16502. function reversePainterSortStable( a, b ) {
  16503. if ( a.object.renderOrder !== b.object.renderOrder ) {
  16504. return a.object.renderOrder - b.object.renderOrder;
  16505. } if ( a.z !== b.z ) {
  16506. return b.z - a.z;
  16507. } else {
  16508. return a.id - b.id;
  16509. }
  16510. }
  16511. // Rendering
  16512. this.render = function ( scene, camera, renderTarget, forceClear ) {
  16513. if ( camera !== undefined && camera.isCamera !== true ) {
  16514. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  16515. return;
  16516. }
  16517. // reset caching for this frame
  16518. _currentGeometryProgram = '';
  16519. _currentMaterialId = - 1;
  16520. _currentCamera = null;
  16521. // update scene graph
  16522. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  16523. // update camera matrices and frustum
  16524. if ( camera.parent === null ) camera.updateMatrixWorld();
  16525. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  16526. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  16527. _frustum.setFromMatrix( _projScreenMatrix );
  16528. lights.length = 0;
  16529. opaqueObjectsLastIndex = - 1;
  16530. transparentObjectsLastIndex = - 1;
  16531. sprites.length = 0;
  16532. lensFlares.length = 0;
  16533. _localClippingEnabled = this.localClippingEnabled;
  16534. _clippingEnabled = _clipping.init( this.clippingPlanes, _localClippingEnabled, camera );
  16535. projectObject( scene, camera );
  16536. opaqueObjects.length = opaqueObjectsLastIndex + 1;
  16537. transparentObjects.length = transparentObjectsLastIndex + 1;
  16538. if ( _this.sortObjects === true ) {
  16539. opaqueObjects.sort( painterSortStable );
  16540. transparentObjects.sort( reversePainterSortStable );
  16541. }
  16542. //
  16543. if ( _clippingEnabled ) _clipping.beginShadows();
  16544. setupShadows( lights );
  16545. shadowMap.render( scene, camera );
  16546. setupLights( lights, camera );
  16547. if ( _clippingEnabled ) _clipping.endShadows();
  16548. //
  16549. _infoRender.calls = 0;
  16550. _infoRender.vertices = 0;
  16551. _infoRender.faces = 0;
  16552. _infoRender.points = 0;
  16553. if ( renderTarget === undefined ) {
  16554. renderTarget = null;
  16555. }
  16556. this.setRenderTarget( renderTarget );
  16557. //
  16558. var background = scene.background;
  16559. if ( background === null ) {
  16560. state.buffers.color.setClear( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha, _premultipliedAlpha );
  16561. } else if ( background && background.isColor ) {
  16562. state.buffers.color.setClear( background.r, background.g, background.b, 1, _premultipliedAlpha );
  16563. forceClear = true;
  16564. }
  16565. if ( this.autoClear || forceClear ) {
  16566. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  16567. }
  16568. if ( background && background.isCubeTexture ) {
  16569. backgroundCamera2.projectionMatrix.copy( camera.projectionMatrix );
  16570. backgroundCamera2.matrixWorld.extractRotation( camera.matrixWorld );
  16571. backgroundCamera2.matrixWorldInverse.getInverse( backgroundCamera2.matrixWorld );
  16572. backgroundBoxMesh.material.uniforms[ "tCube" ].value = background;
  16573. backgroundBoxMesh.modelViewMatrix.multiplyMatrices( backgroundCamera2.matrixWorldInverse, backgroundBoxMesh.matrixWorld );
  16574. objects.update( backgroundBoxMesh );
  16575. _this.renderBufferDirect( backgroundCamera2, null, backgroundBoxMesh.geometry, backgroundBoxMesh.material, backgroundBoxMesh, null );
  16576. } else if ( background && background.isTexture ) {
  16577. backgroundPlaneMesh.material.map = background;
  16578. objects.update( backgroundPlaneMesh );
  16579. _this.renderBufferDirect( backgroundCamera, null, backgroundPlaneMesh.geometry, backgroundPlaneMesh.material, backgroundPlaneMesh, null );
  16580. }
  16581. //
  16582. if ( scene.overrideMaterial ) {
  16583. var overrideMaterial = scene.overrideMaterial;
  16584. renderObjects( opaqueObjects, scene, camera, overrideMaterial );
  16585. renderObjects( transparentObjects, scene, camera, overrideMaterial );
  16586. } else {
  16587. // opaque pass (front-to-back order)
  16588. state.setBlending( NoBlending );
  16589. renderObjects( opaqueObjects, scene, camera );
  16590. // transparent pass (back-to-front order)
  16591. renderObjects( transparentObjects, scene, camera );
  16592. }
  16593. // custom render plugins (post pass)
  16594. spritePlugin.render( scene, camera );
  16595. lensFlarePlugin.render( scene, camera, _currentViewport );
  16596. // Generate mipmap if we're using any kind of mipmap filtering
  16597. if ( renderTarget ) {
  16598. textures.updateRenderTargetMipmap( renderTarget );
  16599. }
  16600. // Ensure depth buffer writing is enabled so it can be cleared on next render
  16601. state.setDepthTest( true );
  16602. state.setDepthWrite( true );
  16603. state.setColorWrite( true );
  16604. // _gl.finish();
  16605. };
  16606. function pushRenderItem( object, geometry, material, z, group ) {
  16607. var array, index;
  16608. // allocate the next position in the appropriate array
  16609. if ( material.transparent ) {
  16610. array = transparentObjects;
  16611. index = ++ transparentObjectsLastIndex;
  16612. } else {
  16613. array = opaqueObjects;
  16614. index = ++ opaqueObjectsLastIndex;
  16615. }
  16616. // recycle existing render item or grow the array
  16617. var renderItem = array[ index ];
  16618. if ( renderItem !== undefined ) {
  16619. renderItem.id = object.id;
  16620. renderItem.object = object;
  16621. renderItem.geometry = geometry;
  16622. renderItem.material = material;
  16623. renderItem.z = _vector3.z;
  16624. renderItem.group = group;
  16625. } else {
  16626. renderItem = {
  16627. id: object.id,
  16628. object: object,
  16629. geometry: geometry,
  16630. material: material,
  16631. z: _vector3.z,
  16632. group: group
  16633. };
  16634. // assert( index === array.length );
  16635. array.push( renderItem );
  16636. }
  16637. }
  16638. // TODO Duplicated code (Frustum)
  16639. function isObjectViewable( object ) {
  16640. var geometry = object.geometry;
  16641. if ( geometry.boundingSphere === null )
  16642. geometry.computeBoundingSphere();
  16643. _sphere.copy( geometry.boundingSphere ).
  16644. applyMatrix4( object.matrixWorld );
  16645. return isSphereViewable( _sphere );
  16646. }
  16647. function isSpriteViewable( sprite ) {
  16648. _sphere.center.set( 0, 0, 0 );
  16649. _sphere.radius = 0.7071067811865476;
  16650. _sphere.applyMatrix4( sprite.matrixWorld );
  16651. return isSphereViewable( _sphere );
  16652. }
  16653. function isSphereViewable( sphere ) {
  16654. if ( ! _frustum.intersectsSphere( sphere ) ) return false;
  16655. var numPlanes = _clipping.numPlanes;
  16656. if ( numPlanes === 0 ) return true;
  16657. var planes = _this.clippingPlanes,
  16658. center = sphere.center,
  16659. negRad = - sphere.radius,
  16660. i = 0;
  16661. do {
  16662. // out when deeper than radius in the negative halfspace
  16663. if ( planes[ i ].distanceToPoint( center ) < negRad ) return false;
  16664. } while ( ++ i !== numPlanes );
  16665. return true;
  16666. }
  16667. function projectObject( object, camera ) {
  16668. if ( object.visible === false ) return;
  16669. var visible = ( object.layers.mask & camera.layers.mask ) !== 0;
  16670. if ( visible ) {
  16671. if ( object.isLight ) {
  16672. lights.push( object );
  16673. } else if ( object.isSprite ) {
  16674. if ( object.frustumCulled === false || isSpriteViewable( object ) === true ) {
  16675. sprites.push( object );
  16676. }
  16677. } else if ( object.isLensFlare ) {
  16678. lensFlares.push( object );
  16679. } else if ( object.isImmediateRenderObject ) {
  16680. if ( _this.sortObjects === true ) {
  16681. _vector3.setFromMatrixPosition( object.matrixWorld );
  16682. _vector3.applyProjection( _projScreenMatrix );
  16683. }
  16684. pushRenderItem( object, null, object.material, _vector3.z, null );
  16685. } else if ( object.isMesh || object.isLine || object.isPoints ) {
  16686. if ( object.isSkinnedMesh ) {
  16687. object.skeleton.update();
  16688. }
  16689. if ( object.frustumCulled === false || isObjectViewable( object ) === true ) {
  16690. var material = object.material;
  16691. if ( material.visible === true ) {
  16692. if ( _this.sortObjects === true ) {
  16693. _vector3.setFromMatrixPosition( object.matrixWorld );
  16694. _vector3.applyProjection( _projScreenMatrix );
  16695. }
  16696. var geometry = objects.update( object );
  16697. if ( material.isMultiMaterial ) {
  16698. var groups = geometry.groups;
  16699. var materials = material.materials;
  16700. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  16701. var group = groups[ i ];
  16702. var groupMaterial = materials[ group.materialIndex ];
  16703. if ( groupMaterial.visible === true ) {
  16704. pushRenderItem( object, geometry, groupMaterial, _vector3.z, group );
  16705. }
  16706. }
  16707. } else {
  16708. pushRenderItem( object, geometry, material, _vector3.z, null );
  16709. }
  16710. }
  16711. }
  16712. }
  16713. }
  16714. var children = object.children;
  16715. for ( var i = 0, l = children.length; i < l; i ++ ) {
  16716. projectObject( children[ i ], camera );
  16717. }
  16718. }
  16719. function renderObjects( renderList, scene, camera, overrideMaterial ) {
  16720. for ( var i = 0, l = renderList.length; i < l; i ++ ) {
  16721. var renderItem = renderList[ i ];
  16722. var object = renderItem.object;
  16723. var geometry = renderItem.geometry;
  16724. var material = overrideMaterial === undefined ? renderItem.material : overrideMaterial;
  16725. var group = renderItem.group;
  16726. object.modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  16727. object.normalMatrix.getNormalMatrix( object.modelViewMatrix );
  16728. object.onBeforeRender( _this, scene, camera, geometry, material, group );
  16729. if ( object.isImmediateRenderObject ) {
  16730. setMaterial( material );
  16731. var program = setProgram( camera, scene.fog, material, object );
  16732. _currentGeometryProgram = '';
  16733. object.render( function ( object ) {
  16734. _this.renderBufferImmediate( object, program, material );
  16735. } );
  16736. } else {
  16737. _this.renderBufferDirect( camera, scene.fog, geometry, material, object, group );
  16738. }
  16739. object.onAfterRender( _this, scene, camera, geometry, material, group );
  16740. }
  16741. }
  16742. function initMaterial( material, fog, object ) {
  16743. var materialProperties = properties.get( material );
  16744. var parameters = programCache.getParameters(
  16745. material, _lights, fog, _clipping.numPlanes, _clipping.numIntersection, object );
  16746. var code = programCache.getProgramCode( material, parameters );
  16747. var program = materialProperties.program;
  16748. var programChange = true;
  16749. if ( program === undefined ) {
  16750. // new material
  16751. material.addEventListener( 'dispose', onMaterialDispose );
  16752. } else if ( program.code !== code ) {
  16753. // changed glsl or parameters
  16754. releaseMaterialProgramReference( material );
  16755. } else if ( parameters.shaderID !== undefined ) {
  16756. // same glsl and uniform list
  16757. return;
  16758. } else {
  16759. // only rebuild uniform list
  16760. programChange = false;
  16761. }
  16762. if ( programChange ) {
  16763. if ( parameters.shaderID ) {
  16764. var shader = ShaderLib[ parameters.shaderID ];
  16765. materialProperties.__webglShader = {
  16766. name: material.type,
  16767. uniforms: UniformsUtils.clone( shader.uniforms ),
  16768. vertexShader: shader.vertexShader,
  16769. fragmentShader: shader.fragmentShader
  16770. };
  16771. } else {
  16772. materialProperties.__webglShader = {
  16773. name: material.type,
  16774. uniforms: material.uniforms,
  16775. vertexShader: material.vertexShader,
  16776. fragmentShader: material.fragmentShader
  16777. };
  16778. }
  16779. material.__webglShader = materialProperties.__webglShader;
  16780. program = programCache.acquireProgram( material, parameters, code );
  16781. materialProperties.program = program;
  16782. material.program = program;
  16783. }
  16784. var attributes = program.getAttributes();
  16785. if ( material.morphTargets ) {
  16786. material.numSupportedMorphTargets = 0;
  16787. for ( var i = 0; i < _this.maxMorphTargets; i ++ ) {
  16788. if ( attributes[ 'morphTarget' + i ] >= 0 ) {
  16789. material.numSupportedMorphTargets ++;
  16790. }
  16791. }
  16792. }
  16793. if ( material.morphNormals ) {
  16794. material.numSupportedMorphNormals = 0;
  16795. for ( var i = 0; i < _this.maxMorphNormals; i ++ ) {
  16796. if ( attributes[ 'morphNormal' + i ] >= 0 ) {
  16797. material.numSupportedMorphNormals ++;
  16798. }
  16799. }
  16800. }
  16801. var uniforms = materialProperties.__webglShader.uniforms;
  16802. if ( ! material.isShaderMaterial &&
  16803. ! material.isRawShaderMaterial ||
  16804. material.clipping === true ) {
  16805. materialProperties.numClippingPlanes = _clipping.numPlanes;
  16806. materialProperties.numIntersection = _clipping.numIntersection;
  16807. uniforms.clippingPlanes = _clipping.uniform;
  16808. }
  16809. materialProperties.fog = fog;
  16810. // store the light setup it was created for
  16811. materialProperties.lightsHash = _lights.hash;
  16812. if ( material.lights ) {
  16813. // wire up the material to this renderer's lighting state
  16814. uniforms.ambientLightColor.value = _lights.ambient;
  16815. uniforms.directionalLights.value = _lights.directional;
  16816. uniforms.spotLights.value = _lights.spot;
  16817. uniforms.rectAreaLights.value = _lights.rectArea;
  16818. uniforms.pointLights.value = _lights.point;
  16819. uniforms.hemisphereLights.value = _lights.hemi;
  16820. uniforms.directionalShadowMap.value = _lights.directionalShadowMap;
  16821. uniforms.directionalShadowMatrix.value = _lights.directionalShadowMatrix;
  16822. uniforms.spotShadowMap.value = _lights.spotShadowMap;
  16823. uniforms.spotShadowMatrix.value = _lights.spotShadowMatrix;
  16824. uniforms.pointShadowMap.value = _lights.pointShadowMap;
  16825. uniforms.pointShadowMatrix.value = _lights.pointShadowMatrix;
  16826. // TODO (abelnation): add area lights shadow info to uniforms
  16827. }
  16828. var progUniforms = materialProperties.program.getUniforms(),
  16829. uniformsList =
  16830. WebGLUniforms.seqWithValue( progUniforms.seq, uniforms );
  16831. materialProperties.uniformsList = uniformsList;
  16832. }
  16833. function setMaterial( material ) {
  16834. material.side === DoubleSide
  16835. ? state.disable( _gl.CULL_FACE )
  16836. : state.enable( _gl.CULL_FACE );
  16837. state.setFlipSided( material.side === BackSide );
  16838. material.transparent === true
  16839. ? state.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst, material.blendEquationAlpha, material.blendSrcAlpha, material.blendDstAlpha, material.premultipliedAlpha )
  16840. : state.setBlending( NoBlending );
  16841. state.setDepthFunc( material.depthFunc );
  16842. state.setDepthTest( material.depthTest );
  16843. state.setDepthWrite( material.depthWrite );
  16844. state.setColorWrite( material.colorWrite );
  16845. state.setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  16846. }
  16847. function setProgram( camera, fog, material, object ) {
  16848. _usedTextureUnits = 0;
  16849. var materialProperties = properties.get( material );
  16850. if ( _clippingEnabled ) {
  16851. if ( _localClippingEnabled || camera !== _currentCamera ) {
  16852. var useCache =
  16853. camera === _currentCamera &&
  16854. material.id === _currentMaterialId;
  16855. // we might want to call this function with some ClippingGroup
  16856. // object instead of the material, once it becomes feasible
  16857. // (#8465, #8379)
  16858. _clipping.setState(
  16859. material.clippingPlanes, material.clipIntersection, material.clipShadows,
  16860. camera, materialProperties, useCache );
  16861. }
  16862. }
  16863. if ( material.needsUpdate === false ) {
  16864. if ( materialProperties.program === undefined ) {
  16865. material.needsUpdate = true;
  16866. } else if ( material.fog && materialProperties.fog !== fog ) {
  16867. material.needsUpdate = true;
  16868. } else if ( material.lights && materialProperties.lightsHash !== _lights.hash ) {
  16869. material.needsUpdate = true;
  16870. } else if ( materialProperties.numClippingPlanes !== undefined &&
  16871. ( materialProperties.numClippingPlanes !== _clipping.numPlanes ||
  16872. materialProperties.numIntersection !== _clipping.numIntersection ) ) {
  16873. material.needsUpdate = true;
  16874. }
  16875. }
  16876. if ( material.needsUpdate ) {
  16877. initMaterial( material, fog, object );
  16878. material.needsUpdate = false;
  16879. }
  16880. var refreshProgram = false;
  16881. var refreshMaterial = false;
  16882. var refreshLights = false;
  16883. var program = materialProperties.program,
  16884. p_uniforms = program.getUniforms(),
  16885. m_uniforms = materialProperties.__webglShader.uniforms;
  16886. if ( program.id !== _currentProgram ) {
  16887. _gl.useProgram( program.program );
  16888. _currentProgram = program.id;
  16889. refreshProgram = true;
  16890. refreshMaterial = true;
  16891. refreshLights = true;
  16892. }
  16893. if ( material.id !== _currentMaterialId ) {
  16894. _currentMaterialId = material.id;
  16895. refreshMaterial = true;
  16896. }
  16897. if ( refreshProgram || camera !== _currentCamera ) {
  16898. p_uniforms.set( _gl, camera, 'projectionMatrix' );
  16899. if ( capabilities.logarithmicDepthBuffer ) {
  16900. p_uniforms.setValue( _gl, 'logDepthBufFC',
  16901. 2.0 / ( Math.log( camera.far + 1.0 ) / Math.LN2 ) );
  16902. }
  16903. if ( camera !== _currentCamera ) {
  16904. _currentCamera = camera;
  16905. // lighting uniforms depend on the camera so enforce an update
  16906. // now, in case this material supports lights - or later, when
  16907. // the next material that does gets activated:
  16908. refreshMaterial = true; // set to true on material change
  16909. refreshLights = true; // remains set until update done
  16910. }
  16911. // load material specific uniforms
  16912. // (shader material also gets them for the sake of genericity)
  16913. if ( material.isShaderMaterial ||
  16914. material.isMeshPhongMaterial ||
  16915. material.isMeshStandardMaterial ||
  16916. material.envMap ) {
  16917. var uCamPos = p_uniforms.map.cameraPosition;
  16918. if ( uCamPos !== undefined ) {
  16919. uCamPos.setValue( _gl,
  16920. _vector3.setFromMatrixPosition( camera.matrixWorld ) );
  16921. }
  16922. }
  16923. if ( material.isMeshPhongMaterial ||
  16924. material.isMeshLambertMaterial ||
  16925. material.isMeshBasicMaterial ||
  16926. material.isMeshStandardMaterial ||
  16927. material.isShaderMaterial ||
  16928. material.skinning ) {
  16929. p_uniforms.setValue( _gl, 'viewMatrix', camera.matrixWorldInverse );
  16930. }
  16931. p_uniforms.set( _gl, _this, 'toneMappingExposure' );
  16932. p_uniforms.set( _gl, _this, 'toneMappingWhitePoint' );
  16933. }
  16934. // skinning uniforms must be set even if material didn't change
  16935. // auto-setting of texture unit for bone texture must go before other textures
  16936. // not sure why, but otherwise weird things happen
  16937. if ( material.skinning ) {
  16938. p_uniforms.setOptional( _gl, object, 'bindMatrix' );
  16939. p_uniforms.setOptional( _gl, object, 'bindMatrixInverse' );
  16940. var skeleton = object.skeleton;
  16941. if ( skeleton ) {
  16942. if ( capabilities.floatVertexTextures && skeleton.useVertexTexture ) {
  16943. p_uniforms.set( _gl, skeleton, 'boneTexture' );
  16944. p_uniforms.set( _gl, skeleton, 'boneTextureWidth' );
  16945. p_uniforms.set( _gl, skeleton, 'boneTextureHeight' );
  16946. } else {
  16947. p_uniforms.setOptional( _gl, skeleton, 'boneMatrices' );
  16948. }
  16949. }
  16950. }
  16951. if ( refreshMaterial ) {
  16952. if ( material.lights ) {
  16953. // the current material requires lighting info
  16954. // note: all lighting uniforms are always set correctly
  16955. // they simply reference the renderer's state for their
  16956. // values
  16957. //
  16958. // use the current material's .needsUpdate flags to set
  16959. // the GL state when required
  16960. markUniformsLightsNeedsUpdate( m_uniforms, refreshLights );
  16961. }
  16962. // refresh uniforms common to several materials
  16963. if ( fog && material.fog ) {
  16964. refreshUniformsFog( m_uniforms, fog );
  16965. }
  16966. if ( material.isMeshBasicMaterial ||
  16967. material.isMeshLambertMaterial ||
  16968. material.isMeshPhongMaterial ||
  16969. material.isMeshStandardMaterial ||
  16970. material.isMeshNormalMaterial ||
  16971. material.isMeshDepthMaterial ) {
  16972. refreshUniformsCommon( m_uniforms, material );
  16973. }
  16974. // refresh single material specific uniforms
  16975. if ( material.isLineBasicMaterial ) {
  16976. refreshUniformsLine( m_uniforms, material );
  16977. } else if ( material.isLineDashedMaterial ) {
  16978. refreshUniformsLine( m_uniforms, material );
  16979. refreshUniformsDash( m_uniforms, material );
  16980. } else if ( material.isPointsMaterial ) {
  16981. refreshUniformsPoints( m_uniforms, material );
  16982. } else if ( material.isMeshLambertMaterial ) {
  16983. refreshUniformsLambert( m_uniforms, material );
  16984. } else if ( material.isMeshToonMaterial ) {
  16985. refreshUniformsToon( m_uniforms, material );
  16986. } else if ( material.isMeshPhongMaterial ) {
  16987. refreshUniformsPhong( m_uniforms, material );
  16988. } else if ( material.isMeshPhysicalMaterial ) {
  16989. refreshUniformsPhysical( m_uniforms, material );
  16990. } else if ( material.isMeshStandardMaterial ) {
  16991. refreshUniformsStandard( m_uniforms, material );
  16992. } else if ( material.isMeshDepthMaterial ) {
  16993. if ( material.displacementMap ) {
  16994. m_uniforms.displacementMap.value = material.displacementMap;
  16995. m_uniforms.displacementScale.value = material.displacementScale;
  16996. m_uniforms.displacementBias.value = material.displacementBias;
  16997. }
  16998. } else if ( material.isMeshNormalMaterial ) {
  16999. refreshUniformsNormal( m_uniforms, material );
  17000. }
  17001. // RectAreaLight Texture
  17002. // TODO (mrdoob): Find a nicer implementation
  17003. if ( m_uniforms.ltcMat !== undefined ) m_uniforms.ltcMat.value = THREE.UniformsLib.LTC_MAT_TEXTURE;
  17004. if ( m_uniforms.ltcMag !== undefined ) m_uniforms.ltcMag.value = THREE.UniformsLib.LTC_MAG_TEXTURE;
  17005. WebGLUniforms.upload(
  17006. _gl, materialProperties.uniformsList, m_uniforms, _this );
  17007. }
  17008. // common matrices
  17009. p_uniforms.set( _gl, object, 'modelViewMatrix' );
  17010. p_uniforms.set( _gl, object, 'normalMatrix' );
  17011. p_uniforms.setValue( _gl, 'modelMatrix', object.matrixWorld );
  17012. return program;
  17013. }
  17014. // Uniforms (refresh uniforms objects)
  17015. function refreshUniformsCommon( uniforms, material ) {
  17016. uniforms.opacity.value = material.opacity;
  17017. uniforms.diffuse.value = material.color;
  17018. if ( material.emissive ) {
  17019. uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity );
  17020. }
  17021. uniforms.map.value = material.map;
  17022. uniforms.specularMap.value = material.specularMap;
  17023. uniforms.alphaMap.value = material.alphaMap;
  17024. if ( material.lightMap ) {
  17025. uniforms.lightMap.value = material.lightMap;
  17026. uniforms.lightMapIntensity.value = material.lightMapIntensity;
  17027. }
  17028. if ( material.aoMap ) {
  17029. uniforms.aoMap.value = material.aoMap;
  17030. uniforms.aoMapIntensity.value = material.aoMapIntensity;
  17031. }
  17032. // uv repeat and offset setting priorities
  17033. // 1. color map
  17034. // 2. specular map
  17035. // 3. normal map
  17036. // 4. bump map
  17037. // 5. alpha map
  17038. // 6. emissive map
  17039. var uvScaleMap;
  17040. if ( material.map ) {
  17041. uvScaleMap = material.map;
  17042. } else if ( material.specularMap ) {
  17043. uvScaleMap = material.specularMap;
  17044. } else if ( material.displacementMap ) {
  17045. uvScaleMap = material.displacementMap;
  17046. } else if ( material.normalMap ) {
  17047. uvScaleMap = material.normalMap;
  17048. } else if ( material.bumpMap ) {
  17049. uvScaleMap = material.bumpMap;
  17050. } else if ( material.roughnessMap ) {
  17051. uvScaleMap = material.roughnessMap;
  17052. } else if ( material.metalnessMap ) {
  17053. uvScaleMap = material.metalnessMap;
  17054. } else if ( material.alphaMap ) {
  17055. uvScaleMap = material.alphaMap;
  17056. } else if ( material.emissiveMap ) {
  17057. uvScaleMap = material.emissiveMap;
  17058. }
  17059. if ( uvScaleMap !== undefined ) {
  17060. // backwards compatibility
  17061. if ( uvScaleMap.isWebGLRenderTarget ) {
  17062. uvScaleMap = uvScaleMap.texture;
  17063. }
  17064. var offset = uvScaleMap.offset;
  17065. var repeat = uvScaleMap.repeat;
  17066. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  17067. }
  17068. uniforms.envMap.value = material.envMap;
  17069. // don't flip CubeTexture envMaps, flip everything else:
  17070. // WebGLRenderTargetCube will be flipped for backwards compatibility
  17071. // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture
  17072. // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future
  17073. uniforms.flipEnvMap.value = ( ! ( material.envMap && material.envMap.isCubeTexture ) ) ? 1 : - 1;
  17074. uniforms.reflectivity.value = material.reflectivity;
  17075. uniforms.refractionRatio.value = material.refractionRatio;
  17076. }
  17077. function refreshUniformsLine( uniforms, material ) {
  17078. uniforms.diffuse.value = material.color;
  17079. uniforms.opacity.value = material.opacity;
  17080. }
  17081. function refreshUniformsDash( uniforms, material ) {
  17082. uniforms.dashSize.value = material.dashSize;
  17083. uniforms.totalSize.value = material.dashSize + material.gapSize;
  17084. uniforms.scale.value = material.scale;
  17085. }
  17086. function refreshUniformsPoints( uniforms, material ) {
  17087. uniforms.diffuse.value = material.color;
  17088. uniforms.opacity.value = material.opacity;
  17089. uniforms.size.value = material.size * _pixelRatio;
  17090. uniforms.scale.value = _height * 0.5;
  17091. uniforms.map.value = material.map;
  17092. if ( material.map !== null ) {
  17093. var offset = material.map.offset;
  17094. var repeat = material.map.repeat;
  17095. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  17096. }
  17097. }
  17098. function refreshUniformsFog( uniforms, fog ) {
  17099. uniforms.fogColor.value = fog.color;
  17100. if ( fog.isFog ) {
  17101. uniforms.fogNear.value = fog.near;
  17102. uniforms.fogFar.value = fog.far;
  17103. } else if ( fog.isFogExp2 ) {
  17104. uniforms.fogDensity.value = fog.density;
  17105. }
  17106. }
  17107. function refreshUniformsLambert( uniforms, material ) {
  17108. if ( material.emissiveMap ) {
  17109. uniforms.emissiveMap.value = material.emissiveMap;
  17110. }
  17111. }
  17112. function refreshUniformsPhong( uniforms, material ) {
  17113. uniforms.specular.value = material.specular;
  17114. uniforms.shininess.value = Math.max( material.shininess, 1e-4 ); // to prevent pow( 0.0, 0.0 )
  17115. if ( material.emissiveMap ) {
  17116. uniforms.emissiveMap.value = material.emissiveMap;
  17117. }
  17118. if ( material.bumpMap ) {
  17119. uniforms.bumpMap.value = material.bumpMap;
  17120. uniforms.bumpScale.value = material.bumpScale;
  17121. }
  17122. if ( material.normalMap ) {
  17123. uniforms.normalMap.value = material.normalMap;
  17124. uniforms.normalScale.value.copy( material.normalScale );
  17125. }
  17126. if ( material.displacementMap ) {
  17127. uniforms.displacementMap.value = material.displacementMap;
  17128. uniforms.displacementScale.value = material.displacementScale;
  17129. uniforms.displacementBias.value = material.displacementBias;
  17130. }
  17131. }
  17132. function refreshUniformsToon( uniforms, material ) {
  17133. refreshUniformsPhong( uniforms, material );
  17134. if ( material.gradientMap ) {
  17135. uniforms.gradientMap.value = material.gradientMap;
  17136. }
  17137. }
  17138. function refreshUniformsStandard( uniforms, material ) {
  17139. uniforms.roughness.value = material.roughness;
  17140. uniforms.metalness.value = material.metalness;
  17141. if ( material.roughnessMap ) {
  17142. uniforms.roughnessMap.value = material.roughnessMap;
  17143. }
  17144. if ( material.metalnessMap ) {
  17145. uniforms.metalnessMap.value = material.metalnessMap;
  17146. }
  17147. if ( material.emissiveMap ) {
  17148. uniforms.emissiveMap.value = material.emissiveMap;
  17149. }
  17150. if ( material.bumpMap ) {
  17151. uniforms.bumpMap.value = material.bumpMap;
  17152. uniforms.bumpScale.value = material.bumpScale;
  17153. }
  17154. if ( material.normalMap ) {
  17155. uniforms.normalMap.value = material.normalMap;
  17156. uniforms.normalScale.value.copy( material.normalScale );
  17157. }
  17158. if ( material.displacementMap ) {
  17159. uniforms.displacementMap.value = material.displacementMap;
  17160. uniforms.displacementScale.value = material.displacementScale;
  17161. uniforms.displacementBias.value = material.displacementBias;
  17162. }
  17163. if ( material.envMap ) {
  17164. //uniforms.envMap.value = material.envMap; // part of uniforms common
  17165. uniforms.envMapIntensity.value = material.envMapIntensity;
  17166. }
  17167. }
  17168. function refreshUniformsPhysical( uniforms, material ) {
  17169. uniforms.clearCoat.value = material.clearCoat;
  17170. uniforms.clearCoatRoughness.value = material.clearCoatRoughness;
  17171. refreshUniformsStandard( uniforms, material );
  17172. }
  17173. function refreshUniformsNormal( uniforms, material ) {
  17174. if ( material.bumpMap ) {
  17175. uniforms.bumpMap.value = material.bumpMap;
  17176. uniforms.bumpScale.value = material.bumpScale;
  17177. }
  17178. if ( material.normalMap ) {
  17179. uniforms.normalMap.value = material.normalMap;
  17180. uniforms.normalScale.value.copy( material.normalScale );
  17181. }
  17182. if ( material.displacementMap ) {
  17183. uniforms.displacementMap.value = material.displacementMap;
  17184. uniforms.displacementScale.value = material.displacementScale;
  17185. uniforms.displacementBias.value = material.displacementBias;
  17186. }
  17187. }
  17188. // If uniforms are marked as clean, they don't need to be loaded to the GPU.
  17189. function markUniformsLightsNeedsUpdate( uniforms, value ) {
  17190. uniforms.ambientLightColor.needsUpdate = value;
  17191. uniforms.directionalLights.needsUpdate = value;
  17192. uniforms.pointLights.needsUpdate = value;
  17193. uniforms.spotLights.needsUpdate = value;
  17194. uniforms.rectAreaLights.needsUpdate = value;
  17195. uniforms.hemisphereLights.needsUpdate = value;
  17196. }
  17197. // Lighting
  17198. function setupShadows( lights ) {
  17199. var lightShadowsLength = 0;
  17200. for ( var i = 0, l = lights.length; i < l; i ++ ) {
  17201. var light = lights[ i ];
  17202. if ( light.castShadow ) {
  17203. _lights.shadows[ lightShadowsLength ++ ] = light;
  17204. }
  17205. }
  17206. _lights.shadows.length = lightShadowsLength;
  17207. }
  17208. function setupLights( lights, camera ) {
  17209. var l, ll, light,
  17210. r = 0, g = 0, b = 0,
  17211. color,
  17212. intensity,
  17213. distance,
  17214. shadowMap,
  17215. viewMatrix = camera.matrixWorldInverse,
  17216. directionalLength = 0,
  17217. pointLength = 0,
  17218. spotLength = 0,
  17219. rectAreaLength = 0,
  17220. hemiLength = 0;
  17221. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  17222. light = lights[ l ];
  17223. color = light.color;
  17224. intensity = light.intensity;
  17225. distance = light.distance;
  17226. shadowMap = ( light.shadow && light.shadow.map ) ? light.shadow.map.texture : null;
  17227. if ( light.isAmbientLight ) {
  17228. r += color.r * intensity;
  17229. g += color.g * intensity;
  17230. b += color.b * intensity;
  17231. } else if ( light.isDirectionalLight ) {
  17232. var uniforms = lightCache.get( light );
  17233. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17234. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17235. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17236. uniforms.direction.sub( _vector3 );
  17237. uniforms.direction.transformDirection( viewMatrix );
  17238. uniforms.shadow = light.castShadow;
  17239. if ( light.castShadow ) {
  17240. uniforms.shadowBias = light.shadow.bias;
  17241. uniforms.shadowRadius = light.shadow.radius;
  17242. uniforms.shadowMapSize = light.shadow.mapSize;
  17243. }
  17244. _lights.directionalShadowMap[ directionalLength ] = shadowMap;
  17245. _lights.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;
  17246. _lights.directional[ directionalLength ++ ] = uniforms;
  17247. } else if ( light.isSpotLight ) {
  17248. var uniforms = lightCache.get( light );
  17249. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17250. uniforms.position.applyMatrix4( viewMatrix );
  17251. uniforms.color.copy( color ).multiplyScalar( intensity );
  17252. uniforms.distance = distance;
  17253. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17254. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  17255. uniforms.direction.sub( _vector3 );
  17256. uniforms.direction.transformDirection( viewMatrix );
  17257. uniforms.coneCos = Math.cos( light.angle );
  17258. uniforms.penumbraCos = Math.cos( light.angle * ( 1 - light.penumbra ) );
  17259. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17260. uniforms.shadow = light.castShadow;
  17261. if ( light.castShadow ) {
  17262. uniforms.shadowBias = light.shadow.bias;
  17263. uniforms.shadowRadius = light.shadow.radius;
  17264. uniforms.shadowMapSize = light.shadow.mapSize;
  17265. }
  17266. _lights.spotShadowMap[ spotLength ] = shadowMap;
  17267. _lights.spotShadowMatrix[ spotLength ] = light.shadow.matrix;
  17268. _lights.spot[ spotLength ++ ] = uniforms;
  17269. } else if ( light.isRectAreaLight ) {
  17270. var uniforms = lightCache.get( light );
  17271. // (a) intensity controls irradiance of entire light
  17272. uniforms.color
  17273. .copy( color )
  17274. .multiplyScalar( intensity / ( light.width * light.height ) );
  17275. // (b) intensity controls the radiance per light area
  17276. // uniforms.color.copy( color ).multiplyScalar( intensity );
  17277. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17278. uniforms.position.applyMatrix4( viewMatrix );
  17279. // extract local rotation of light to derive width/height half vectors
  17280. _matrix42.identity();
  17281. _matrix4.copy( light.matrixWorld );
  17282. _matrix4.premultiply( viewMatrix );
  17283. _matrix42.extractRotation( _matrix4 );
  17284. uniforms.halfWidth.set( light.width * 0.5, 0.0, 0.0 );
  17285. uniforms.halfHeight.set( 0.0, light.height * 0.5, 0.0 );
  17286. uniforms.halfWidth.applyMatrix4( _matrix42 );
  17287. uniforms.halfHeight.applyMatrix4( _matrix42 );
  17288. // TODO (abelnation): RectAreaLight distance?
  17289. // uniforms.distance = distance;
  17290. _lights.rectArea[ rectAreaLength ++ ] = uniforms;
  17291. } else if ( light.isPointLight ) {
  17292. var uniforms = lightCache.get( light );
  17293. uniforms.position.setFromMatrixPosition( light.matrixWorld );
  17294. uniforms.position.applyMatrix4( viewMatrix );
  17295. uniforms.color.copy( light.color ).multiplyScalar( light.intensity );
  17296. uniforms.distance = light.distance;
  17297. uniforms.decay = ( light.distance === 0 ) ? 0.0 : light.decay;
  17298. uniforms.shadow = light.castShadow;
  17299. if ( light.castShadow ) {
  17300. uniforms.shadowBias = light.shadow.bias;
  17301. uniforms.shadowRadius = light.shadow.radius;
  17302. uniforms.shadowMapSize = light.shadow.mapSize;
  17303. }
  17304. _lights.pointShadowMap[ pointLength ] = shadowMap;
  17305. if ( _lights.pointShadowMatrix[ pointLength ] === undefined ) {
  17306. _lights.pointShadowMatrix[ pointLength ] = new Matrix4();
  17307. }
  17308. // for point lights we set the shadow matrix to be a translation-only matrix
  17309. // equal to inverse of the light's position
  17310. _vector3.setFromMatrixPosition( light.matrixWorld ).negate();
  17311. _lights.pointShadowMatrix[ pointLength ].identity().setPosition( _vector3 );
  17312. _lights.point[ pointLength ++ ] = uniforms;
  17313. } else if ( light.isHemisphereLight ) {
  17314. var uniforms = lightCache.get( light );
  17315. uniforms.direction.setFromMatrixPosition( light.matrixWorld );
  17316. uniforms.direction.transformDirection( viewMatrix );
  17317. uniforms.direction.normalize();
  17318. uniforms.skyColor.copy( light.color ).multiplyScalar( intensity );
  17319. uniforms.groundColor.copy( light.groundColor ).multiplyScalar( intensity );
  17320. _lights.hemi[ hemiLength ++ ] = uniforms;
  17321. }
  17322. }
  17323. _lights.ambient[ 0 ] = r;
  17324. _lights.ambient[ 1 ] = g;
  17325. _lights.ambient[ 2 ] = b;
  17326. _lights.directional.length = directionalLength;
  17327. _lights.spot.length = spotLength;
  17328. _lights.rectArea.length = rectAreaLength;
  17329. _lights.point.length = pointLength;
  17330. _lights.hemi.length = hemiLength;
  17331. // TODO (sam-g-steel) why aren't we using join
  17332. _lights.hash = directionalLength + ',' + pointLength + ',' + spotLength + ',' + rectAreaLength + ',' + hemiLength + ',' + _lights.shadows.length;
  17333. }
  17334. // GL state setting
  17335. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  17336. state.setCullFace( cullFace );
  17337. state.setFlipSided( frontFaceDirection === FrontFaceDirectionCW );
  17338. };
  17339. // Textures
  17340. function allocTextureUnit() {
  17341. var textureUnit = _usedTextureUnits;
  17342. if ( textureUnit >= capabilities.maxTextures ) {
  17343. console.warn( 'WebGLRenderer: trying to use ' + textureUnit + ' texture units while this GPU supports only ' + capabilities.maxTextures );
  17344. }
  17345. _usedTextureUnits += 1;
  17346. return textureUnit;
  17347. }
  17348. this.allocTextureUnit = allocTextureUnit;
  17349. // this.setTexture2D = setTexture2D;
  17350. this.setTexture2D = ( function() {
  17351. var warned = false;
  17352. // backwards compatibility: peel texture.texture
  17353. return function setTexture2D( texture, slot ) {
  17354. if ( texture && texture.isWebGLRenderTarget ) {
  17355. if ( ! warned ) {
  17356. console.warn( "THREE.WebGLRenderer.setTexture2D: don't use render targets as textures. Use their .texture property instead." );
  17357. warned = true;
  17358. }
  17359. texture = texture.texture;
  17360. }
  17361. textures.setTexture2D( texture, slot );
  17362. };
  17363. }() );
  17364. this.setTexture = ( function() {
  17365. var warned = false;
  17366. return function setTexture( texture, slot ) {
  17367. if ( ! warned ) {
  17368. console.warn( "THREE.WebGLRenderer: .setTexture is deprecated, use setTexture2D instead." );
  17369. warned = true;
  17370. }
  17371. textures.setTexture2D( texture, slot );
  17372. };
  17373. }() );
  17374. this.setTextureCube = ( function() {
  17375. var warned = false;
  17376. return function setTextureCube( texture, slot ) {
  17377. // backwards compatibility: peel texture.texture
  17378. if ( texture && texture.isWebGLRenderTargetCube ) {
  17379. if ( ! warned ) {
  17380. console.warn( "THREE.WebGLRenderer.setTextureCube: don't use cube render targets as textures. Use their .texture property instead." );
  17381. warned = true;
  17382. }
  17383. texture = texture.texture;
  17384. }
  17385. // currently relying on the fact that WebGLRenderTargetCube.texture is a Texture and NOT a CubeTexture
  17386. // TODO: unify these code paths
  17387. if ( ( texture && texture.isCubeTexture ) ||
  17388. ( Array.isArray( texture.image ) && texture.image.length === 6 ) ) {
  17389. // CompressedTexture can have Array in image :/
  17390. // this function alone should take care of cube textures
  17391. textures.setTextureCube( texture, slot );
  17392. } else {
  17393. // assumed: texture property of THREE.WebGLRenderTargetCube
  17394. textures.setTextureCubeDynamic( texture, slot );
  17395. }
  17396. };
  17397. }() );
  17398. this.getCurrentRenderTarget = function() {
  17399. return _currentRenderTarget;
  17400. };
  17401. this.setRenderTarget = function ( renderTarget ) {
  17402. _currentRenderTarget = renderTarget;
  17403. if ( renderTarget && properties.get( renderTarget ).__webglFramebuffer === undefined ) {
  17404. textures.setupRenderTarget( renderTarget );
  17405. }
  17406. var isCube = ( renderTarget && renderTarget.isWebGLRenderTargetCube );
  17407. var framebuffer;
  17408. if ( renderTarget ) {
  17409. var renderTargetProperties = properties.get( renderTarget );
  17410. if ( isCube ) {
  17411. framebuffer = renderTargetProperties.__webglFramebuffer[ renderTarget.activeCubeFace ];
  17412. } else {
  17413. framebuffer = renderTargetProperties.__webglFramebuffer;
  17414. }
  17415. _currentScissor.copy( renderTarget.scissor );
  17416. _currentScissorTest = renderTarget.scissorTest;
  17417. _currentViewport.copy( renderTarget.viewport );
  17418. } else {
  17419. framebuffer = null;
  17420. _currentScissor.copy( _scissor ).multiplyScalar( _pixelRatio );
  17421. _currentScissorTest = _scissorTest;
  17422. _currentViewport.copy( _viewport ).multiplyScalar( _pixelRatio );
  17423. }
  17424. if ( _currentFramebuffer !== framebuffer ) {
  17425. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17426. _currentFramebuffer = framebuffer;
  17427. }
  17428. state.scissor( _currentScissor );
  17429. state.setScissorTest( _currentScissorTest );
  17430. state.viewport( _currentViewport );
  17431. if ( isCube ) {
  17432. var textureProperties = properties.get( renderTarget.texture );
  17433. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + renderTarget.activeCubeFace, textureProperties.__webglTexture, renderTarget.activeMipMapLevel );
  17434. }
  17435. };
  17436. this.readRenderTargetPixels = function ( renderTarget, x, y, width, height, buffer ) {
  17437. if ( ( renderTarget && renderTarget.isWebGLRenderTarget ) === false ) {
  17438. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.' );
  17439. return;
  17440. }
  17441. var framebuffer = properties.get( renderTarget ).__webglFramebuffer;
  17442. if ( framebuffer ) {
  17443. var restore = false;
  17444. if ( framebuffer !== _currentFramebuffer ) {
  17445. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  17446. restore = true;
  17447. }
  17448. try {
  17449. var texture = renderTarget.texture;
  17450. var textureFormat = texture.format;
  17451. var textureType = texture.type;
  17452. if ( textureFormat !== RGBAFormat && paramThreeToGL( textureFormat ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_FORMAT ) ) {
  17453. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.' );
  17454. return;
  17455. }
  17456. if ( textureType !== UnsignedByteType && paramThreeToGL( textureType ) !== _gl.getParameter( _gl.IMPLEMENTATION_COLOR_READ_TYPE ) && // IE11, Edge and Chrome Mac < 52 (#9513)
  17457. ! ( textureType === FloatType && ( extensions.get( 'OES_texture_float' ) || extensions.get( 'WEBGL_color_buffer_float' ) ) ) && // Chrome Mac >= 52 and Firefox
  17458. ! ( textureType === HalfFloatType && extensions.get( 'EXT_color_buffer_half_float' ) ) ) {
  17459. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.' );
  17460. return;
  17461. }
  17462. if ( _gl.checkFramebufferStatus( _gl.FRAMEBUFFER ) === _gl.FRAMEBUFFER_COMPLETE ) {
  17463. // the following if statement ensures valid read requests (no out-of-bounds pixels, see #8604)
  17464. if ( ( x >= 0 && x <= ( renderTarget.width - width ) ) && ( y >= 0 && y <= ( renderTarget.height - height ) ) ) {
  17465. _gl.readPixels( x, y, width, height, paramThreeToGL( textureFormat ), paramThreeToGL( textureType ), buffer );
  17466. }
  17467. } else {
  17468. console.error( 'THREE.WebGLRenderer.readRenderTargetPixels: readPixels from renderTarget failed. Framebuffer not complete.' );
  17469. }
  17470. } finally {
  17471. if ( restore ) {
  17472. _gl.bindFramebuffer( _gl.FRAMEBUFFER, _currentFramebuffer );
  17473. }
  17474. }
  17475. }
  17476. };
  17477. // Map three.js constants to WebGL constants
  17478. function paramThreeToGL( p ) {
  17479. var extension;
  17480. if ( p === RepeatWrapping ) return _gl.REPEAT;
  17481. if ( p === ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  17482. if ( p === MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  17483. if ( p === NearestFilter ) return _gl.NEAREST;
  17484. if ( p === NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  17485. if ( p === NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  17486. if ( p === LinearFilter ) return _gl.LINEAR;
  17487. if ( p === LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  17488. if ( p === LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  17489. if ( p === UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  17490. if ( p === UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  17491. if ( p === UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  17492. if ( p === UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  17493. if ( p === ByteType ) return _gl.BYTE;
  17494. if ( p === ShortType ) return _gl.SHORT;
  17495. if ( p === UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  17496. if ( p === IntType ) return _gl.INT;
  17497. if ( p === UnsignedIntType ) return _gl.UNSIGNED_INT;
  17498. if ( p === FloatType ) return _gl.FLOAT;
  17499. if ( p === HalfFloatType ) {
  17500. extension = extensions.get( 'OES_texture_half_float' );
  17501. if ( extension !== null ) return extension.HALF_FLOAT_OES;
  17502. }
  17503. if ( p === AlphaFormat ) return _gl.ALPHA;
  17504. if ( p === RGBFormat ) return _gl.RGB;
  17505. if ( p === RGBAFormat ) return _gl.RGBA;
  17506. if ( p === LuminanceFormat ) return _gl.LUMINANCE;
  17507. if ( p === LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  17508. if ( p === DepthFormat ) return _gl.DEPTH_COMPONENT;
  17509. if ( p === DepthStencilFormat ) return _gl.DEPTH_STENCIL;
  17510. if ( p === AddEquation ) return _gl.FUNC_ADD;
  17511. if ( p === SubtractEquation ) return _gl.FUNC_SUBTRACT;
  17512. if ( p === ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  17513. if ( p === ZeroFactor ) return _gl.ZERO;
  17514. if ( p === OneFactor ) return _gl.ONE;
  17515. if ( p === SrcColorFactor ) return _gl.SRC_COLOR;
  17516. if ( p === OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  17517. if ( p === SrcAlphaFactor ) return _gl.SRC_ALPHA;
  17518. if ( p === OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  17519. if ( p === DstAlphaFactor ) return _gl.DST_ALPHA;
  17520. if ( p === OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  17521. if ( p === DstColorFactor ) return _gl.DST_COLOR;
  17522. if ( p === OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  17523. if ( p === SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  17524. if ( p === RGB_S3TC_DXT1_Format || p === RGBA_S3TC_DXT1_Format ||
  17525. p === RGBA_S3TC_DXT3_Format || p === RGBA_S3TC_DXT5_Format ) {
  17526. extension = extensions.get( 'WEBGL_compressed_texture_s3tc' );
  17527. if ( extension !== null ) {
  17528. if ( p === RGB_S3TC_DXT1_Format ) return extension.COMPRESSED_RGB_S3TC_DXT1_EXT;
  17529. if ( p === RGBA_S3TC_DXT1_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  17530. if ( p === RGBA_S3TC_DXT3_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  17531. if ( p === RGBA_S3TC_DXT5_Format ) return extension.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  17532. }
  17533. }
  17534. if ( p === RGB_PVRTC_4BPPV1_Format || p === RGB_PVRTC_2BPPV1_Format ||
  17535. p === RGBA_PVRTC_4BPPV1_Format || p === RGBA_PVRTC_2BPPV1_Format ) {
  17536. extension = extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  17537. if ( extension !== null ) {
  17538. if ( p === RGB_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;
  17539. if ( p === RGB_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
  17540. if ( p === RGBA_PVRTC_4BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;
  17541. if ( p === RGBA_PVRTC_2BPPV1_Format ) return extension.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
  17542. }
  17543. }
  17544. if ( p === RGB_ETC1_Format ) {
  17545. extension = extensions.get( 'WEBGL_compressed_texture_etc1' );
  17546. if ( extension !== null ) return extension.COMPRESSED_RGB_ETC1_WEBGL;
  17547. }
  17548. if ( p === MinEquation || p === MaxEquation ) {
  17549. extension = extensions.get( 'EXT_blend_minmax' );
  17550. if ( extension !== null ) {
  17551. if ( p === MinEquation ) return extension.MIN_EXT;
  17552. if ( p === MaxEquation ) return extension.MAX_EXT;
  17553. }
  17554. }
  17555. if ( p === UnsignedInt248Type ) {
  17556. extension = extensions.get( 'WEBGL_depth_texture' );
  17557. if ( extension !== null ) return extension.UNSIGNED_INT_24_8_WEBGL;
  17558. }
  17559. return 0;
  17560. }
  17561. }
  17562. /**
  17563. * @author mrdoob / http://mrdoob.com/
  17564. * @author alteredq / http://alteredqualia.com/
  17565. */
  17566. function FogExp2 ( color, density ) {
  17567. this.name = '';
  17568. this.color = new Color( color );
  17569. this.density = ( density !== undefined ) ? density : 0.00025;
  17570. }
  17571. FogExp2.prototype.isFogExp2 = true;
  17572. FogExp2.prototype.clone = function () {
  17573. return new FogExp2( this.color.getHex(), this.density );
  17574. };
  17575. FogExp2.prototype.toJSON = function ( meta ) {
  17576. return {
  17577. type: 'FogExp2',
  17578. color: this.color.getHex(),
  17579. density: this.density
  17580. };
  17581. };
  17582. /**
  17583. * @author mrdoob / http://mrdoob.com/
  17584. * @author alteredq / http://alteredqualia.com/
  17585. */
  17586. function Fog ( color, near, far ) {
  17587. this.name = '';
  17588. this.color = new Color( color );
  17589. this.near = ( near !== undefined ) ? near : 1;
  17590. this.far = ( far !== undefined ) ? far : 1000;
  17591. }
  17592. Fog.prototype.isFog = true;
  17593. Fog.prototype.clone = function () {
  17594. return new Fog( this.color.getHex(), this.near, this.far );
  17595. };
  17596. Fog.prototype.toJSON = function ( meta ) {
  17597. return {
  17598. type: 'Fog',
  17599. color: this.color.getHex(),
  17600. near: this.near,
  17601. far: this.far
  17602. };
  17603. };
  17604. /**
  17605. * @author mrdoob / http://mrdoob.com/
  17606. */
  17607. function Scene () {
  17608. Object3D.call( this );
  17609. this.type = 'Scene';
  17610. this.background = null;
  17611. this.fog = null;
  17612. this.overrideMaterial = null;
  17613. this.autoUpdate = true; // checked by the renderer
  17614. }
  17615. Scene.prototype = Object.create( Object3D.prototype );
  17616. Scene.prototype.constructor = Scene;
  17617. Scene.prototype.copy = function ( source, recursive ) {
  17618. Object3D.prototype.copy.call( this, source, recursive );
  17619. if ( source.background !== null ) this.background = source.background.clone();
  17620. if ( source.fog !== null ) this.fog = source.fog.clone();
  17621. if ( source.overrideMaterial !== null ) this.overrideMaterial = source.overrideMaterial.clone();
  17622. this.autoUpdate = source.autoUpdate;
  17623. this.matrixAutoUpdate = source.matrixAutoUpdate;
  17624. return this;
  17625. };
  17626. Scene.prototype.toJSON = function ( meta ) {
  17627. var data = Object3D.prototype.toJSON.call( this, meta );
  17628. if ( this.background !== null ) data.object.background = this.background.toJSON( meta );
  17629. if ( this.fog !== null ) data.object.fog = this.fog.toJSON();
  17630. return data;
  17631. };
  17632. /**
  17633. * @author mikael emtinger / http://gomo.se/
  17634. * @author alteredq / http://alteredqualia.com/
  17635. */
  17636. function LensFlare( texture, size, distance, blending, color ) {
  17637. Object3D.call( this );
  17638. this.lensFlares = [];
  17639. this.positionScreen = new Vector3();
  17640. this.customUpdateCallback = undefined;
  17641. if ( texture !== undefined ) {
  17642. this.add( texture, size, distance, blending, color );
  17643. }
  17644. }
  17645. LensFlare.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17646. constructor: LensFlare,
  17647. isLensFlare: true,
  17648. copy: function ( source ) {
  17649. Object3D.prototype.copy.call( this, source );
  17650. this.positionScreen.copy( source.positionScreen );
  17651. this.customUpdateCallback = source.customUpdateCallback;
  17652. for ( var i = 0, l = source.lensFlares.length; i < l; i ++ ) {
  17653. this.lensFlares.push( source.lensFlares[ i ] );
  17654. }
  17655. return this;
  17656. },
  17657. add: function ( texture, size, distance, blending, color, opacity ) {
  17658. if ( size === undefined ) size = - 1;
  17659. if ( distance === undefined ) distance = 0;
  17660. if ( opacity === undefined ) opacity = 1;
  17661. if ( color === undefined ) color = new Color( 0xffffff );
  17662. if ( blending === undefined ) blending = NormalBlending;
  17663. distance = Math.min( distance, Math.max( 0, distance ) );
  17664. this.lensFlares.push( {
  17665. texture: texture, // THREE.Texture
  17666. size: size, // size in pixels (-1 = use texture.width)
  17667. distance: distance, // distance (0-1) from light source (0=at light source)
  17668. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is in front z = 1 is back
  17669. scale: 1, // scale
  17670. rotation: 0, // rotation
  17671. opacity: opacity, // opacity
  17672. color: color, // color
  17673. blending: blending // blending
  17674. } );
  17675. },
  17676. /*
  17677. * Update lens flares update positions on all flares based on the screen position
  17678. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  17679. */
  17680. updateLensFlares: function () {
  17681. var f, fl = this.lensFlares.length;
  17682. var flare;
  17683. var vecX = - this.positionScreen.x * 2;
  17684. var vecY = - this.positionScreen.y * 2;
  17685. for ( f = 0; f < fl; f ++ ) {
  17686. flare = this.lensFlares[ f ];
  17687. flare.x = this.positionScreen.x + vecX * flare.distance;
  17688. flare.y = this.positionScreen.y + vecY * flare.distance;
  17689. flare.wantedRotation = flare.x * Math.PI * 0.25;
  17690. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  17691. }
  17692. }
  17693. } );
  17694. /**
  17695. * @author alteredq / http://alteredqualia.com/
  17696. *
  17697. * parameters = {
  17698. * color: <hex>,
  17699. * opacity: <float>,
  17700. * map: new THREE.Texture( <Image> ),
  17701. *
  17702. * uvOffset: new THREE.Vector2(),
  17703. * uvScale: new THREE.Vector2()
  17704. * }
  17705. */
  17706. function SpriteMaterial( parameters ) {
  17707. Material.call( this );
  17708. this.type = 'SpriteMaterial';
  17709. this.color = new Color( 0xffffff );
  17710. this.map = null;
  17711. this.rotation = 0;
  17712. this.fog = false;
  17713. this.lights = false;
  17714. this.setValues( parameters );
  17715. }
  17716. SpriteMaterial.prototype = Object.create( Material.prototype );
  17717. SpriteMaterial.prototype.constructor = SpriteMaterial;
  17718. SpriteMaterial.prototype.copy = function ( source ) {
  17719. Material.prototype.copy.call( this, source );
  17720. this.color.copy( source.color );
  17721. this.map = source.map;
  17722. this.rotation = source.rotation;
  17723. return this;
  17724. };
  17725. /**
  17726. * @author mikael emtinger / http://gomo.se/
  17727. * @author alteredq / http://alteredqualia.com/
  17728. */
  17729. function Sprite( material ) {
  17730. Object3D.call( this );
  17731. this.type = 'Sprite';
  17732. this.material = ( material !== undefined ) ? material : new SpriteMaterial();
  17733. }
  17734. Sprite.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17735. constructor: Sprite,
  17736. isSprite: true,
  17737. raycast: ( function () {
  17738. var matrixPosition = new Vector3();
  17739. return function raycast( raycaster, intersects ) {
  17740. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  17741. var distanceSq = raycaster.ray.distanceSqToPoint( matrixPosition );
  17742. var guessSizeSq = this.scale.x * this.scale.y / 4;
  17743. if ( distanceSq > guessSizeSq ) {
  17744. return;
  17745. }
  17746. intersects.push( {
  17747. distance: Math.sqrt( distanceSq ),
  17748. point: this.position,
  17749. face: null,
  17750. object: this
  17751. } );
  17752. };
  17753. }() ),
  17754. clone: function () {
  17755. return new this.constructor( this.material ).copy( this );
  17756. }
  17757. } );
  17758. /**
  17759. * @author mikael emtinger / http://gomo.se/
  17760. * @author alteredq / http://alteredqualia.com/
  17761. * @author mrdoob / http://mrdoob.com/
  17762. */
  17763. function LOD() {
  17764. Object3D.call( this );
  17765. this.type = 'LOD';
  17766. Object.defineProperties( this, {
  17767. levels: {
  17768. enumerable: true,
  17769. value: []
  17770. }
  17771. } );
  17772. }
  17773. LOD.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17774. constructor: LOD,
  17775. copy: function ( source ) {
  17776. Object3D.prototype.copy.call( this, source, false );
  17777. var levels = source.levels;
  17778. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  17779. var level = levels[ i ];
  17780. this.addLevel( level.object.clone(), level.distance );
  17781. }
  17782. return this;
  17783. },
  17784. addLevel: function ( object, distance ) {
  17785. if ( distance === undefined ) distance = 0;
  17786. distance = Math.abs( distance );
  17787. var levels = this.levels;
  17788. for ( var l = 0; l < levels.length; l ++ ) {
  17789. if ( distance < levels[ l ].distance ) {
  17790. break;
  17791. }
  17792. }
  17793. levels.splice( l, 0, { distance: distance, object: object } );
  17794. this.add( object );
  17795. },
  17796. getObjectForDistance: function ( distance ) {
  17797. var levels = this.levels;
  17798. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  17799. if ( distance < levels[ i ].distance ) {
  17800. break;
  17801. }
  17802. }
  17803. return levels[ i - 1 ].object;
  17804. },
  17805. raycast: ( function () {
  17806. var matrixPosition = new Vector3();
  17807. return function raycast( raycaster, intersects ) {
  17808. matrixPosition.setFromMatrixPosition( this.matrixWorld );
  17809. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  17810. this.getObjectForDistance( distance ).raycast( raycaster, intersects );
  17811. };
  17812. }() ),
  17813. update: function () {
  17814. var v1 = new Vector3();
  17815. var v2 = new Vector3();
  17816. return function update( camera ) {
  17817. var levels = this.levels;
  17818. if ( levels.length > 1 ) {
  17819. v1.setFromMatrixPosition( camera.matrixWorld );
  17820. v2.setFromMatrixPosition( this.matrixWorld );
  17821. var distance = v1.distanceTo( v2 );
  17822. levels[ 0 ].object.visible = true;
  17823. for ( var i = 1, l = levels.length; i < l; i ++ ) {
  17824. if ( distance >= levels[ i ].distance ) {
  17825. levels[ i - 1 ].object.visible = false;
  17826. levels[ i ].object.visible = true;
  17827. } else {
  17828. break;
  17829. }
  17830. }
  17831. for ( ; i < l; i ++ ) {
  17832. levels[ i ].object.visible = false;
  17833. }
  17834. }
  17835. };
  17836. }(),
  17837. toJSON: function ( meta ) {
  17838. var data = Object3D.prototype.toJSON.call( this, meta );
  17839. data.object.levels = [];
  17840. var levels = this.levels;
  17841. for ( var i = 0, l = levels.length; i < l; i ++ ) {
  17842. var level = levels[ i ];
  17843. data.object.levels.push( {
  17844. object: level.object.uuid,
  17845. distance: level.distance
  17846. } );
  17847. }
  17848. return data;
  17849. }
  17850. } );
  17851. /**
  17852. * @author mikael emtinger / http://gomo.se/
  17853. * @author alteredq / http://alteredqualia.com/
  17854. * @author michael guerrero / http://realitymeltdown.com
  17855. * @author ikerr / http://verold.com
  17856. */
  17857. function Skeleton( bones, boneInverses, useVertexTexture ) {
  17858. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  17859. this.identityMatrix = new Matrix4();
  17860. // copy the bone array
  17861. bones = bones || [];
  17862. this.bones = bones.slice( 0 );
  17863. // create a bone texture or an array of floats
  17864. if ( this.useVertexTexture ) {
  17865. // layout (1 matrix = 4 pixels)
  17866. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  17867. // with 8x8 pixel texture max 16 bones * 4 pixels = (8 * 8)
  17868. // 16x16 pixel texture max 64 bones * 4 pixels = (16 * 16)
  17869. // 32x32 pixel texture max 256 bones * 4 pixels = (32 * 32)
  17870. // 64x64 pixel texture max 1024 bones * 4 pixels = (64 * 64)
  17871. var size = Math.sqrt( this.bones.length * 4 ); // 4 pixels needed for 1 matrix
  17872. size = _Math.nextPowerOfTwo( Math.ceil( size ) );
  17873. size = Math.max( size, 4 );
  17874. this.boneTextureWidth = size;
  17875. this.boneTextureHeight = size;
  17876. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  17877. this.boneTexture = new DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, RGBAFormat, FloatType );
  17878. } else {
  17879. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  17880. }
  17881. // use the supplied bone inverses or calculate the inverses
  17882. if ( boneInverses === undefined ) {
  17883. this.calculateInverses();
  17884. } else {
  17885. if ( this.bones.length === boneInverses.length ) {
  17886. this.boneInverses = boneInverses.slice( 0 );
  17887. } else {
  17888. console.warn( 'THREE.Skeleton bonInverses is the wrong length.' );
  17889. this.boneInverses = [];
  17890. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17891. this.boneInverses.push( new Matrix4() );
  17892. }
  17893. }
  17894. }
  17895. }
  17896. Object.assign( Skeleton.prototype, {
  17897. calculateInverses: function () {
  17898. this.boneInverses = [];
  17899. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17900. var inverse = new Matrix4();
  17901. if ( this.bones[ b ] ) {
  17902. inverse.getInverse( this.bones[ b ].matrixWorld );
  17903. }
  17904. this.boneInverses.push( inverse );
  17905. }
  17906. },
  17907. pose: function () {
  17908. var bone;
  17909. // recover the bind-time world matrices
  17910. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17911. bone = this.bones[ b ];
  17912. if ( bone ) {
  17913. bone.matrixWorld.getInverse( this.boneInverses[ b ] );
  17914. }
  17915. }
  17916. // compute the local matrices, positions, rotations and scales
  17917. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17918. bone = this.bones[ b ];
  17919. if ( bone ) {
  17920. if ( bone.parent && bone.parent.isBone ) {
  17921. bone.matrix.getInverse( bone.parent.matrixWorld );
  17922. bone.matrix.multiply( bone.matrixWorld );
  17923. } else {
  17924. bone.matrix.copy( bone.matrixWorld );
  17925. }
  17926. bone.matrix.decompose( bone.position, bone.quaternion, bone.scale );
  17927. }
  17928. }
  17929. },
  17930. update: ( function () {
  17931. var offsetMatrix = new Matrix4();
  17932. return function update() {
  17933. // flatten bone matrices to array
  17934. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  17935. // compute the offset between the current and the original transform
  17936. var matrix = this.bones[ b ] ? this.bones[ b ].matrixWorld : this.identityMatrix;
  17937. offsetMatrix.multiplyMatrices( matrix, this.boneInverses[ b ] );
  17938. offsetMatrix.toArray( this.boneMatrices, b * 16 );
  17939. }
  17940. if ( this.useVertexTexture ) {
  17941. this.boneTexture.needsUpdate = true;
  17942. }
  17943. };
  17944. } )(),
  17945. clone: function () {
  17946. return new Skeleton( this.bones, this.boneInverses, this.useVertexTexture );
  17947. }
  17948. } );
  17949. /**
  17950. * @author mikael emtinger / http://gomo.se/
  17951. * @author alteredq / http://alteredqualia.com/
  17952. * @author ikerr / http://verold.com
  17953. */
  17954. function Bone() {
  17955. Object3D.call( this );
  17956. this.type = 'Bone';
  17957. }
  17958. Bone.prototype = Object.assign( Object.create( Object3D.prototype ), {
  17959. constructor: Bone,
  17960. isBone: true
  17961. } );
  17962. /**
  17963. * @author mikael emtinger / http://gomo.se/
  17964. * @author alteredq / http://alteredqualia.com/
  17965. * @author ikerr / http://verold.com
  17966. */
  17967. function SkinnedMesh( geometry, material, useVertexTexture ) {
  17968. Mesh.call( this, geometry, material );
  17969. this.type = 'SkinnedMesh';
  17970. this.bindMode = "attached";
  17971. this.bindMatrix = new Matrix4();
  17972. this.bindMatrixInverse = new Matrix4();
  17973. // init bones
  17974. // TODO: remove bone creation as there is no reason (other than
  17975. // convenience) for THREE.SkinnedMesh to do this.
  17976. var bones = [];
  17977. if ( this.geometry && this.geometry.bones !== undefined ) {
  17978. var bone, gbone;
  17979. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  17980. gbone = this.geometry.bones[ b ];
  17981. bone = new Bone();
  17982. bones.push( bone );
  17983. bone.name = gbone.name;
  17984. bone.position.fromArray( gbone.pos );
  17985. bone.quaternion.fromArray( gbone.rotq );
  17986. if ( gbone.scl !== undefined ) bone.scale.fromArray( gbone.scl );
  17987. }
  17988. for ( var b = 0, bl = this.geometry.bones.length; b < bl; ++ b ) {
  17989. gbone = this.geometry.bones[ b ];
  17990. if ( gbone.parent !== - 1 && gbone.parent !== null &&
  17991. bones[ gbone.parent ] !== undefined ) {
  17992. bones[ gbone.parent ].add( bones[ b ] );
  17993. } else {
  17994. this.add( bones[ b ] );
  17995. }
  17996. }
  17997. }
  17998. this.normalizeSkinWeights();
  17999. this.updateMatrixWorld( true );
  18000. this.bind( new Skeleton( bones, undefined, useVertexTexture ), this.matrixWorld );
  18001. }
  18002. SkinnedMesh.prototype = Object.assign( Object.create( Mesh.prototype ), {
  18003. constructor: SkinnedMesh,
  18004. isSkinnedMesh: true,
  18005. bind: function( skeleton, bindMatrix ) {
  18006. this.skeleton = skeleton;
  18007. if ( bindMatrix === undefined ) {
  18008. this.updateMatrixWorld( true );
  18009. this.skeleton.calculateInverses();
  18010. bindMatrix = this.matrixWorld;
  18011. }
  18012. this.bindMatrix.copy( bindMatrix );
  18013. this.bindMatrixInverse.getInverse( bindMatrix );
  18014. },
  18015. pose: function () {
  18016. this.skeleton.pose();
  18017. },
  18018. normalizeSkinWeights: function () {
  18019. if ( this.geometry && this.geometry.isGeometry ) {
  18020. for ( var i = 0; i < this.geometry.skinWeights.length; i ++ ) {
  18021. var sw = this.geometry.skinWeights[ i ];
  18022. var scale = 1.0 / sw.lengthManhattan();
  18023. if ( scale !== Infinity ) {
  18024. sw.multiplyScalar( scale );
  18025. } else {
  18026. sw.set( 1, 0, 0, 0 ); // do something reasonable
  18027. }
  18028. }
  18029. } else if ( this.geometry && this.geometry.isBufferGeometry ) {
  18030. var vec = new Vector4();
  18031. var skinWeight = this.geometry.attributes.skinWeight;
  18032. for ( var i = 0; i < skinWeight.count; i ++ ) {
  18033. vec.x = skinWeight.getX( i );
  18034. vec.y = skinWeight.getY( i );
  18035. vec.z = skinWeight.getZ( i );
  18036. vec.w = skinWeight.getW( i );
  18037. var scale = 1.0 / vec.lengthManhattan();
  18038. if ( scale !== Infinity ) {
  18039. vec.multiplyScalar( scale );
  18040. } else {
  18041. vec.set( 1, 0, 0, 0 ); // do something reasonable
  18042. }
  18043. skinWeight.setXYZW( i, vec.x, vec.y, vec.z, vec.w );
  18044. }
  18045. }
  18046. },
  18047. updateMatrixWorld: function( force ) {
  18048. Mesh.prototype.updateMatrixWorld.call( this, true );
  18049. if ( this.bindMode === "attached" ) {
  18050. this.bindMatrixInverse.getInverse( this.matrixWorld );
  18051. } else if ( this.bindMode === "detached" ) {
  18052. this.bindMatrixInverse.getInverse( this.bindMatrix );
  18053. } else {
  18054. console.warn( 'THREE.SkinnedMesh unrecognized bindMode: ' + this.bindMode );
  18055. }
  18056. },
  18057. clone: function() {
  18058. return new this.constructor( this.geometry, this.material, this.skeleton.useVertexTexture ).copy( this );
  18059. }
  18060. } );
  18061. /**
  18062. * @author mrdoob / http://mrdoob.com/
  18063. * @author alteredq / http://alteredqualia.com/
  18064. *
  18065. * parameters = {
  18066. * color: <hex>,
  18067. * opacity: <float>,
  18068. *
  18069. * linewidth: <float>,
  18070. * linecap: "round",
  18071. * linejoin: "round"
  18072. * }
  18073. */
  18074. function LineBasicMaterial( parameters ) {
  18075. Material.call( this );
  18076. this.type = 'LineBasicMaterial';
  18077. this.color = new Color( 0xffffff );
  18078. this.linewidth = 1;
  18079. this.linecap = 'round';
  18080. this.linejoin = 'round';
  18081. this.lights = false;
  18082. this.setValues( parameters );
  18083. }
  18084. LineBasicMaterial.prototype = Object.create( Material.prototype );
  18085. LineBasicMaterial.prototype.constructor = LineBasicMaterial;
  18086. LineBasicMaterial.prototype.isLineBasicMaterial = true;
  18087. LineBasicMaterial.prototype.copy = function ( source ) {
  18088. Material.prototype.copy.call( this, source );
  18089. this.color.copy( source.color );
  18090. this.linewidth = source.linewidth;
  18091. this.linecap = source.linecap;
  18092. this.linejoin = source.linejoin;
  18093. return this;
  18094. };
  18095. /**
  18096. * @author mrdoob / http://mrdoob.com/
  18097. */
  18098. function Line( geometry, material, mode ) {
  18099. if ( mode === 1 ) {
  18100. console.warn( 'THREE.Line: parameter THREE.LinePieces no longer supported. Created THREE.LineSegments instead.' );
  18101. return new LineSegments( geometry, material );
  18102. }
  18103. Object3D.call( this );
  18104. this.type = 'Line';
  18105. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18106. this.material = material !== undefined ? material : new LineBasicMaterial( { color: Math.random() * 0xffffff } );
  18107. }
  18108. Line.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18109. constructor: Line,
  18110. isLine: true,
  18111. raycast: ( function () {
  18112. var inverseMatrix = new Matrix4();
  18113. var ray = new Ray();
  18114. var sphere = new Sphere();
  18115. return function raycast( raycaster, intersects ) {
  18116. var precision = raycaster.linePrecision;
  18117. var precisionSq = precision * precision;
  18118. var geometry = this.geometry;
  18119. var matrixWorld = this.matrixWorld;
  18120. // Checking boundingSphere distance to ray
  18121. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18122. sphere.copy( geometry.boundingSphere );
  18123. sphere.applyMatrix4( matrixWorld );
  18124. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18125. //
  18126. inverseMatrix.getInverse( matrixWorld );
  18127. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18128. var vStart = new Vector3();
  18129. var vEnd = new Vector3();
  18130. var interSegment = new Vector3();
  18131. var interRay = new Vector3();
  18132. var step = (this && this.isLineSegments) ? 2 : 1;
  18133. if ( geometry.isBufferGeometry ) {
  18134. var index = geometry.index;
  18135. var attributes = geometry.attributes;
  18136. var positions = attributes.position.array;
  18137. if ( index !== null ) {
  18138. var indices = index.array;
  18139. for ( var i = 0, l = indices.length - 1; i < l; i += step ) {
  18140. var a = indices[ i ];
  18141. var b = indices[ i + 1 ];
  18142. vStart.fromArray( positions, a * 3 );
  18143. vEnd.fromArray( positions, b * 3 );
  18144. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18145. if ( distSq > precisionSq ) continue;
  18146. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18147. var distance = raycaster.ray.origin.distanceTo( interRay );
  18148. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18149. intersects.push( {
  18150. distance: distance,
  18151. // What do we want? intersection point on the ray or on the segment??
  18152. // point: raycaster.ray.at( distance ),
  18153. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18154. index: i,
  18155. face: null,
  18156. faceIndex: null,
  18157. object: this
  18158. } );
  18159. }
  18160. } else {
  18161. for ( var i = 0, l = positions.length / 3 - 1; i < l; i += step ) {
  18162. vStart.fromArray( positions, 3 * i );
  18163. vEnd.fromArray( positions, 3 * i + 3 );
  18164. var distSq = ray.distanceSqToSegment( vStart, vEnd, interRay, interSegment );
  18165. if ( distSq > precisionSq ) continue;
  18166. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18167. var distance = raycaster.ray.origin.distanceTo( interRay );
  18168. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18169. intersects.push( {
  18170. distance: distance,
  18171. // What do we want? intersection point on the ray or on the segment??
  18172. // point: raycaster.ray.at( distance ),
  18173. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18174. index: i,
  18175. face: null,
  18176. faceIndex: null,
  18177. object: this
  18178. } );
  18179. }
  18180. }
  18181. } else if ( geometry.isGeometry ) {
  18182. var vertices = geometry.vertices;
  18183. var nbVertices = vertices.length;
  18184. for ( var i = 0; i < nbVertices - 1; i += step ) {
  18185. var distSq = ray.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  18186. if ( distSq > precisionSq ) continue;
  18187. interRay.applyMatrix4( this.matrixWorld ); //Move back to world space for distance calculation
  18188. var distance = raycaster.ray.origin.distanceTo( interRay );
  18189. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  18190. intersects.push( {
  18191. distance: distance,
  18192. // What do we want? intersection point on the ray or on the segment??
  18193. // point: raycaster.ray.at( distance ),
  18194. point: interSegment.clone().applyMatrix4( this.matrixWorld ),
  18195. index: i,
  18196. face: null,
  18197. faceIndex: null,
  18198. object: this
  18199. } );
  18200. }
  18201. }
  18202. };
  18203. }() ),
  18204. clone: function () {
  18205. return new this.constructor( this.geometry, this.material ).copy( this );
  18206. }
  18207. } );
  18208. /**
  18209. * @author mrdoob / http://mrdoob.com/
  18210. */
  18211. function LineSegments( geometry, material ) {
  18212. Line.call( this, geometry, material );
  18213. this.type = 'LineSegments';
  18214. }
  18215. LineSegments.prototype = Object.assign( Object.create( Line.prototype ), {
  18216. constructor: LineSegments,
  18217. isLineSegments: true
  18218. } );
  18219. /**
  18220. * @author mrdoob / http://mrdoob.com/
  18221. * @author alteredq / http://alteredqualia.com/
  18222. *
  18223. * parameters = {
  18224. * color: <hex>,
  18225. * opacity: <float>,
  18226. * map: new THREE.Texture( <Image> ),
  18227. *
  18228. * size: <float>,
  18229. * sizeAttenuation: <bool>
  18230. * }
  18231. */
  18232. function PointsMaterial( parameters ) {
  18233. Material.call( this );
  18234. this.type = 'PointsMaterial';
  18235. this.color = new Color( 0xffffff );
  18236. this.map = null;
  18237. this.size = 1;
  18238. this.sizeAttenuation = true;
  18239. this.lights = false;
  18240. this.setValues( parameters );
  18241. }
  18242. PointsMaterial.prototype = Object.create( Material.prototype );
  18243. PointsMaterial.prototype.constructor = PointsMaterial;
  18244. PointsMaterial.prototype.isPointsMaterial = true;
  18245. PointsMaterial.prototype.copy = function ( source ) {
  18246. Material.prototype.copy.call( this, source );
  18247. this.color.copy( source.color );
  18248. this.map = source.map;
  18249. this.size = source.size;
  18250. this.sizeAttenuation = source.sizeAttenuation;
  18251. return this;
  18252. };
  18253. /**
  18254. * @author alteredq / http://alteredqualia.com/
  18255. */
  18256. function Points( geometry, material ) {
  18257. Object3D.call( this );
  18258. this.type = 'Points';
  18259. this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
  18260. this.material = material !== undefined ? material : new PointsMaterial( { color: Math.random() * 0xffffff } );
  18261. }
  18262. Points.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18263. constructor: Points,
  18264. isPoints: true,
  18265. raycast: ( function () {
  18266. var inverseMatrix = new Matrix4();
  18267. var ray = new Ray();
  18268. var sphere = new Sphere();
  18269. return function raycast( raycaster, intersects ) {
  18270. var object = this;
  18271. var geometry = this.geometry;
  18272. var matrixWorld = this.matrixWorld;
  18273. var threshold = raycaster.params.Points.threshold;
  18274. // Checking boundingSphere distance to ray
  18275. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  18276. sphere.copy( geometry.boundingSphere );
  18277. sphere.applyMatrix4( matrixWorld );
  18278. if ( raycaster.ray.intersectsSphere( sphere ) === false ) return;
  18279. //
  18280. inverseMatrix.getInverse( matrixWorld );
  18281. ray.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  18282. var localThreshold = threshold / ( ( this.scale.x + this.scale.y + this.scale.z ) / 3 );
  18283. var localThresholdSq = localThreshold * localThreshold;
  18284. var position = new Vector3();
  18285. function testPoint( point, index ) {
  18286. var rayPointDistanceSq = ray.distanceSqToPoint( point );
  18287. if ( rayPointDistanceSq < localThresholdSq ) {
  18288. var intersectPoint = ray.closestPointToPoint( point );
  18289. intersectPoint.applyMatrix4( matrixWorld );
  18290. var distance = raycaster.ray.origin.distanceTo( intersectPoint );
  18291. if ( distance < raycaster.near || distance > raycaster.far ) return;
  18292. intersects.push( {
  18293. distance: distance,
  18294. distanceToRay: Math.sqrt( rayPointDistanceSq ),
  18295. point: intersectPoint.clone(),
  18296. index: index,
  18297. face: null,
  18298. object: object
  18299. } );
  18300. }
  18301. }
  18302. if ( geometry.isBufferGeometry ) {
  18303. var index = geometry.index;
  18304. var attributes = geometry.attributes;
  18305. var positions = attributes.position.array;
  18306. if ( index !== null ) {
  18307. var indices = index.array;
  18308. for ( var i = 0, il = indices.length; i < il; i ++ ) {
  18309. var a = indices[ i ];
  18310. position.fromArray( positions, a * 3 );
  18311. testPoint( position, a );
  18312. }
  18313. } else {
  18314. for ( var i = 0, l = positions.length / 3; i < l; i ++ ) {
  18315. position.fromArray( positions, i * 3 );
  18316. testPoint( position, i );
  18317. }
  18318. }
  18319. } else {
  18320. var vertices = geometry.vertices;
  18321. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18322. testPoint( vertices[ i ], i );
  18323. }
  18324. }
  18325. };
  18326. }() ),
  18327. clone: function () {
  18328. return new this.constructor( this.geometry, this.material ).copy( this );
  18329. }
  18330. } );
  18331. /**
  18332. * @author mrdoob / http://mrdoob.com/
  18333. */
  18334. function Group() {
  18335. Object3D.call( this );
  18336. this.type = 'Group';
  18337. }
  18338. Group.prototype = Object.assign( Object.create( Object3D.prototype ), {
  18339. constructor: Group
  18340. } );
  18341. /**
  18342. * @author mrdoob / http://mrdoob.com/
  18343. */
  18344. function VideoTexture( video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18345. Texture.call( this, video, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18346. this.generateMipmaps = false;
  18347. var scope = this;
  18348. function update() {
  18349. requestAnimationFrame( update );
  18350. if ( video.readyState >= video.HAVE_CURRENT_DATA ) {
  18351. scope.needsUpdate = true;
  18352. }
  18353. }
  18354. update();
  18355. }
  18356. VideoTexture.prototype = Object.create( Texture.prototype );
  18357. VideoTexture.prototype.constructor = VideoTexture;
  18358. /**
  18359. * @author alteredq / http://alteredqualia.com/
  18360. */
  18361. function CompressedTexture( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, encoding ) {
  18362. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding );
  18363. this.image = { width: width, height: height };
  18364. this.mipmaps = mipmaps;
  18365. // no flipping for cube textures
  18366. // (also flipping doesn't work for compressed textures )
  18367. this.flipY = false;
  18368. // can't generate mipmaps for compressed textures
  18369. // mips must be embedded in DDS files
  18370. this.generateMipmaps = false;
  18371. }
  18372. CompressedTexture.prototype = Object.create( Texture.prototype );
  18373. CompressedTexture.prototype.constructor = CompressedTexture;
  18374. CompressedTexture.prototype.isCompressedTexture = true;
  18375. /**
  18376. * @author mrdoob / http://mrdoob.com/
  18377. */
  18378. function CanvasTexture( canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  18379. Texture.call( this, canvas, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18380. this.needsUpdate = true;
  18381. }
  18382. CanvasTexture.prototype = Object.create( Texture.prototype );
  18383. CanvasTexture.prototype.constructor = CanvasTexture;
  18384. /**
  18385. * @author Matt DesLauriers / @mattdesl
  18386. * @author atix / arthursilber.de
  18387. */
  18388. function DepthTexture( width, height, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy, format ) {
  18389. format = format !== undefined ? format : DepthFormat;
  18390. if ( format !== DepthFormat && format !== DepthStencilFormat ) {
  18391. throw new Error( 'DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat' )
  18392. }
  18393. if ( type === undefined && format === DepthFormat ) type = UnsignedShortType;
  18394. if ( type === undefined && format === DepthStencilFormat ) type = UnsignedInt248Type;
  18395. Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  18396. this.image = { width: width, height: height };
  18397. this.magFilter = magFilter !== undefined ? magFilter : NearestFilter;
  18398. this.minFilter = minFilter !== undefined ? minFilter : NearestFilter;
  18399. this.flipY = false;
  18400. this.generateMipmaps = false;
  18401. }
  18402. DepthTexture.prototype = Object.create( Texture.prototype );
  18403. DepthTexture.prototype.constructor = DepthTexture;
  18404. DepthTexture.prototype.isDepthTexture = true;
  18405. /**
  18406. * @author mrdoob / http://mrdoob.com/
  18407. */
  18408. function WireframeGeometry( geometry ) {
  18409. BufferGeometry.call( this );
  18410. var edge = [ 0, 0 ], hash = {};
  18411. function sortFunction( a, b ) {
  18412. return a - b;
  18413. }
  18414. var keys = [ 'a', 'b', 'c' ];
  18415. if ( geometry && geometry.isGeometry ) {
  18416. var vertices = geometry.vertices;
  18417. var faces = geometry.faces;
  18418. var numEdges = 0;
  18419. // allocate maximal size
  18420. var edges = new Uint32Array( 6 * faces.length );
  18421. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18422. var face = faces[ i ];
  18423. for ( var j = 0; j < 3; j ++ ) {
  18424. edge[ 0 ] = face[ keys[ j ] ];
  18425. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  18426. edge.sort( sortFunction );
  18427. var key = edge.toString();
  18428. if ( hash[ key ] === undefined ) {
  18429. edges[ 2 * numEdges ] = edge[ 0 ];
  18430. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  18431. hash[ key ] = true;
  18432. numEdges ++;
  18433. }
  18434. }
  18435. }
  18436. var coords = new Float32Array( numEdges * 2 * 3 );
  18437. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  18438. for ( var j = 0; j < 2; j ++ ) {
  18439. var vertex = vertices[ edges [ 2 * i + j ] ];
  18440. var index = 6 * i + 3 * j;
  18441. coords[ index + 0 ] = vertex.x;
  18442. coords[ index + 1 ] = vertex.y;
  18443. coords[ index + 2 ] = vertex.z;
  18444. }
  18445. }
  18446. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  18447. } else if ( geometry && geometry.isBufferGeometry ) {
  18448. if ( geometry.index !== null ) {
  18449. // Indexed BufferGeometry
  18450. var indices = geometry.index.array;
  18451. var vertices = geometry.attributes.position;
  18452. var groups = geometry.groups;
  18453. var numEdges = 0;
  18454. if ( groups.length === 0 ) {
  18455. geometry.addGroup( 0, indices.length );
  18456. }
  18457. // allocate maximal size
  18458. var edges = new Uint32Array( 2 * indices.length );
  18459. for ( var o = 0, ol = groups.length; o < ol; ++ o ) {
  18460. var group = groups[ o ];
  18461. var start = group.start;
  18462. var count = group.count;
  18463. for ( var i = start, il = start + count; i < il; i += 3 ) {
  18464. for ( var j = 0; j < 3; j ++ ) {
  18465. edge[ 0 ] = indices[ i + j ];
  18466. edge[ 1 ] = indices[ i + ( j + 1 ) % 3 ];
  18467. edge.sort( sortFunction );
  18468. var key = edge.toString();
  18469. if ( hash[ key ] === undefined ) {
  18470. edges[ 2 * numEdges ] = edge[ 0 ];
  18471. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  18472. hash[ key ] = true;
  18473. numEdges ++;
  18474. }
  18475. }
  18476. }
  18477. }
  18478. var coords = new Float32Array( numEdges * 2 * 3 );
  18479. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  18480. for ( var j = 0; j < 2; j ++ ) {
  18481. var index = 6 * i + 3 * j;
  18482. var index2 = edges[ 2 * i + j ];
  18483. coords[ index + 0 ] = vertices.getX( index2 );
  18484. coords[ index + 1 ] = vertices.getY( index2 );
  18485. coords[ index + 2 ] = vertices.getZ( index2 );
  18486. }
  18487. }
  18488. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  18489. } else {
  18490. // non-indexed BufferGeometry
  18491. var vertices = geometry.attributes.position.array;
  18492. var numEdges = vertices.length / 3;
  18493. var numTris = numEdges / 3;
  18494. var coords = new Float32Array( numEdges * 2 * 3 );
  18495. for ( var i = 0, l = numTris; i < l; i ++ ) {
  18496. for ( var j = 0; j < 3; j ++ ) {
  18497. var index = 18 * i + 6 * j;
  18498. var index1 = 9 * i + 3 * j;
  18499. coords[ index + 0 ] = vertices[ index1 ];
  18500. coords[ index + 1 ] = vertices[ index1 + 1 ];
  18501. coords[ index + 2 ] = vertices[ index1 + 2 ];
  18502. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  18503. coords[ index + 3 ] = vertices[ index2 ];
  18504. coords[ index + 4 ] = vertices[ index2 + 1 ];
  18505. coords[ index + 5 ] = vertices[ index2 + 2 ];
  18506. }
  18507. }
  18508. this.addAttribute( 'position', new BufferAttribute( coords, 3 ) );
  18509. }
  18510. }
  18511. }
  18512. WireframeGeometry.prototype = Object.create( BufferGeometry.prototype );
  18513. WireframeGeometry.prototype.constructor = WireframeGeometry;
  18514. /**
  18515. * @author Mugen87 / https://github.com/Mugen87
  18516. *
  18517. * Parametric Surfaces Geometry
  18518. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18519. */
  18520. function ParametricBufferGeometry( func, slices, stacks ) {
  18521. BufferGeometry.call( this );
  18522. this.type = 'ParametricBufferGeometry';
  18523. this.parameters = {
  18524. func: func,
  18525. slices: slices,
  18526. stacks: stacks
  18527. };
  18528. // generate vertices and uvs
  18529. var vertices = [];
  18530. var uvs = [];
  18531. var i, j, p;
  18532. var u, v;
  18533. var sliceCount = slices + 1;
  18534. for ( i = 0; i <= stacks; i ++ ) {
  18535. v = i / stacks;
  18536. for ( j = 0; j <= slices; j ++ ) {
  18537. u = j / slices;
  18538. p = func( u, v );
  18539. vertices.push( p.x, p.y, p.z );
  18540. uvs.push( u, v );
  18541. }
  18542. }
  18543. // generate indices
  18544. var indices = [];
  18545. var a, b, c, d;
  18546. for ( i = 0; i < stacks; i ++ ) {
  18547. for ( j = 0; j < slices; j ++ ) {
  18548. a = i * sliceCount + j;
  18549. b = i * sliceCount + j + 1;
  18550. c = ( i + 1 ) * sliceCount + j + 1;
  18551. d = ( i + 1 ) * sliceCount + j;
  18552. // faces one and two
  18553. indices.push( a, b, d );
  18554. indices.push( b, c, d );
  18555. }
  18556. }
  18557. // build geometry
  18558. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  18559. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18560. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18561. // generate normals
  18562. this.computeVertexNormals();
  18563. }
  18564. ParametricBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18565. ParametricBufferGeometry.prototype.constructor = ParametricBufferGeometry;
  18566. /**
  18567. * @author zz85 / https://github.com/zz85
  18568. *
  18569. * Parametric Surfaces Geometry
  18570. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18571. */
  18572. function ParametricGeometry( func, slices, stacks ) {
  18573. Geometry.call( this );
  18574. this.type = 'ParametricGeometry';
  18575. this.parameters = {
  18576. func: func,
  18577. slices: slices,
  18578. stacks: stacks
  18579. };
  18580. this.fromBufferGeometry( new ParametricBufferGeometry( func, slices, stacks ) );
  18581. this.mergeVertices();
  18582. }
  18583. ParametricGeometry.prototype = Object.create( Geometry.prototype );
  18584. ParametricGeometry.prototype.constructor = ParametricGeometry;
  18585. /**
  18586. * @author Mugen87 / https://github.com/Mugen87
  18587. */
  18588. function PolyhedronBufferGeometry( vertices, indices, radius, detail ) {
  18589. BufferGeometry.call( this );
  18590. this.type = 'PolyhedronBufferGeometry';
  18591. this.parameters = {
  18592. vertices: vertices,
  18593. indices: indices,
  18594. radius: radius,
  18595. detail: detail
  18596. };
  18597. radius = radius || 1;
  18598. detail = detail || 0;
  18599. // default buffer data
  18600. var vertexBuffer = [];
  18601. var uvBuffer = [];
  18602. // the subdivision creates the vertex buffer data
  18603. subdivide( detail );
  18604. // all vertices should lie on a conceptual sphere with a given radius
  18605. appplyRadius( radius );
  18606. // finally, create the uv data
  18607. generateUVs();
  18608. // build non-indexed geometry
  18609. this.addAttribute( 'position', new Float32BufferAttribute( vertexBuffer, 3 ) );
  18610. this.addAttribute( 'normal', new Float32BufferAttribute( vertexBuffer.slice(), 3 ) );
  18611. this.addAttribute( 'uv', new Float32BufferAttribute( uvBuffer, 2 ) );
  18612. this.normalizeNormals();
  18613. this.boundingSphere = new Sphere( new Vector3(), radius );
  18614. // helper functions
  18615. function subdivide( detail ) {
  18616. var a = new Vector3();
  18617. var b = new Vector3();
  18618. var c = new Vector3();
  18619. // iterate over all faces and apply a subdivison with the given detail value
  18620. for ( var i = 0; i < indices.length; i += 3 ) {
  18621. // get the vertices of the face
  18622. getVertexByIndex( indices[ i + 0 ], a );
  18623. getVertexByIndex( indices[ i + 1 ], b );
  18624. getVertexByIndex( indices[ i + 2 ], c );
  18625. // perform subdivision
  18626. subdivideFace( a, b, c, detail );
  18627. }
  18628. }
  18629. function subdivideFace( a, b, c, detail ) {
  18630. var cols = Math.pow( 2, detail );
  18631. // we use this multidimensional array as a data structure for creating the subdivision
  18632. var v = [];
  18633. var i, j;
  18634. // construct all of the vertices for this subdivision
  18635. for ( i = 0 ; i <= cols; i ++ ) {
  18636. v[ i ] = [];
  18637. var aj = a.clone().lerp( c, i / cols );
  18638. var bj = b.clone().lerp( c, i / cols );
  18639. var rows = cols - i;
  18640. for ( j = 0; j <= rows; j ++ ) {
  18641. if ( j === 0 && i === cols ) {
  18642. v[ i ][ j ] = aj;
  18643. } else {
  18644. v[ i ][ j ] = aj.clone().lerp( bj, j / rows );
  18645. }
  18646. }
  18647. }
  18648. // construct all of the faces
  18649. for ( i = 0; i < cols ; i ++ ) {
  18650. for ( j = 0; j < 2 * ( cols - i ) - 1; j ++ ) {
  18651. var k = Math.floor( j / 2 );
  18652. if ( j % 2 === 0 ) {
  18653. pushVertex( v[ i ][ k + 1 ] );
  18654. pushVertex( v[ i + 1 ][ k ] );
  18655. pushVertex( v[ i ][ k ] );
  18656. } else {
  18657. pushVertex( v[ i ][ k + 1 ] );
  18658. pushVertex( v[ i + 1 ][ k + 1 ] );
  18659. pushVertex( v[ i + 1 ][ k ] );
  18660. }
  18661. }
  18662. }
  18663. }
  18664. function appplyRadius( radius ) {
  18665. var vertex = new Vector3();
  18666. // iterate over the entire buffer and apply the radius to each vertex
  18667. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  18668. vertex.x = vertexBuffer[ i + 0 ];
  18669. vertex.y = vertexBuffer[ i + 1 ];
  18670. vertex.z = vertexBuffer[ i + 2 ];
  18671. vertex.normalize().multiplyScalar( radius );
  18672. vertexBuffer[ i + 0 ] = vertex.x;
  18673. vertexBuffer[ i + 1 ] = vertex.y;
  18674. vertexBuffer[ i + 2 ] = vertex.z;
  18675. }
  18676. }
  18677. function generateUVs() {
  18678. var vertex = new Vector3();
  18679. for ( var i = 0; i < vertexBuffer.length; i += 3 ) {
  18680. vertex.x = vertexBuffer[ i + 0 ];
  18681. vertex.y = vertexBuffer[ i + 1 ];
  18682. vertex.z = vertexBuffer[ i + 2 ];
  18683. var u = azimuth( vertex ) / 2 / Math.PI + 0.5;
  18684. var v = inclination( vertex ) / Math.PI + 0.5;
  18685. uvBuffer.push( u, 1 - v );
  18686. }
  18687. correctUVs();
  18688. correctSeam();
  18689. }
  18690. function correctSeam() {
  18691. // handle case when face straddles the seam, see #3269
  18692. for ( var i = 0; i < uvBuffer.length; i += 6 ) {
  18693. // uv data of a single face
  18694. var x0 = uvBuffer[ i + 0 ];
  18695. var x1 = uvBuffer[ i + 2 ];
  18696. var x2 = uvBuffer[ i + 4 ];
  18697. var max = Math.max( x0, x1, x2 );
  18698. var min = Math.min( x0, x1, x2 );
  18699. // 0.9 is somewhat arbitrary
  18700. if ( max > 0.9 && min < 0.1 ) {
  18701. if ( x0 < 0.2 ) uvBuffer[ i + 0 ] += 1;
  18702. if ( x1 < 0.2 ) uvBuffer[ i + 2 ] += 1;
  18703. if ( x2 < 0.2 ) uvBuffer[ i + 4 ] += 1;
  18704. }
  18705. }
  18706. }
  18707. function pushVertex( vertex ) {
  18708. vertexBuffer.push( vertex.x, vertex.y, vertex.z );
  18709. }
  18710. function getVertexByIndex( index, vertex ) {
  18711. var stride = index * 3;
  18712. vertex.x = vertices[ stride + 0 ];
  18713. vertex.y = vertices[ stride + 1 ];
  18714. vertex.z = vertices[ stride + 2 ];
  18715. }
  18716. function correctUVs() {
  18717. var a = new Vector3();
  18718. var b = new Vector3();
  18719. var c = new Vector3();
  18720. var centroid = new Vector3();
  18721. var uvA = new Vector2();
  18722. var uvB = new Vector2();
  18723. var uvC = new Vector2();
  18724. for ( var i = 0, j = 0; i < vertexBuffer.length; i += 9, j += 6 ) {
  18725. a.set( vertexBuffer[ i + 0 ], vertexBuffer[ i + 1 ], vertexBuffer[ i + 2 ] );
  18726. b.set( vertexBuffer[ i + 3 ], vertexBuffer[ i + 4 ], vertexBuffer[ i + 5 ] );
  18727. c.set( vertexBuffer[ i + 6 ], vertexBuffer[ i + 7 ], vertexBuffer[ i + 8 ] );
  18728. uvA.set( uvBuffer[ j + 0 ], uvBuffer[ j + 1 ] );
  18729. uvB.set( uvBuffer[ j + 2 ], uvBuffer[ j + 3 ] );
  18730. uvC.set( uvBuffer[ j + 4 ], uvBuffer[ j + 5 ] );
  18731. centroid.copy( a ).add( b ).add( c ).divideScalar( 3 );
  18732. var azi = azimuth( centroid );
  18733. correctUV( uvA, j + 0, a, azi );
  18734. correctUV( uvB, j + 2, b, azi );
  18735. correctUV( uvC, j + 4, c, azi );
  18736. }
  18737. }
  18738. function correctUV( uv, stride, vector, azimuth ) {
  18739. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) {
  18740. uvBuffer[ stride ] = uv.x - 1;
  18741. }
  18742. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) {
  18743. uvBuffer[ stride ] = azimuth / 2 / Math.PI + 0.5;
  18744. }
  18745. }
  18746. // Angle around the Y axis, counter-clockwise when looking from above.
  18747. function azimuth( vector ) {
  18748. return Math.atan2( vector.z, - vector.x );
  18749. }
  18750. // Angle above the XZ plane.
  18751. function inclination( vector ) {
  18752. return Math.atan2( - vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18753. }
  18754. }
  18755. PolyhedronBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  18756. PolyhedronBufferGeometry.prototype.constructor = PolyhedronBufferGeometry;
  18757. /**
  18758. * @author Mugen87 / https://github.com/Mugen87
  18759. */
  18760. function TetrahedronBufferGeometry( radius, detail ) {
  18761. var vertices = [
  18762. 1, 1, 1, - 1, - 1, 1, - 1, 1, - 1, 1, - 1, - 1
  18763. ];
  18764. var indices = [
  18765. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  18766. ];
  18767. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18768. this.type = 'TetrahedronBufferGeometry';
  18769. this.parameters = {
  18770. radius: radius,
  18771. detail: detail
  18772. };
  18773. }
  18774. TetrahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18775. TetrahedronBufferGeometry.prototype.constructor = TetrahedronBufferGeometry;
  18776. /**
  18777. * @author timothypratley / https://github.com/timothypratley
  18778. */
  18779. function TetrahedronGeometry( radius, detail ) {
  18780. Geometry.call( this );
  18781. this.type = 'TetrahedronGeometry';
  18782. this.parameters = {
  18783. radius: radius,
  18784. detail: detail
  18785. };
  18786. this.fromBufferGeometry( new TetrahedronBufferGeometry( radius, detail ) );
  18787. this.mergeVertices();
  18788. }
  18789. TetrahedronGeometry.prototype = Object.create( Geometry.prototype );
  18790. TetrahedronGeometry.prototype.constructor = TetrahedronGeometry;
  18791. /**
  18792. * @author Mugen87 / https://github.com/Mugen87
  18793. */
  18794. function OctahedronBufferGeometry( radius,detail ) {
  18795. var vertices = [
  18796. 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1, 0, 0, 0, 1, 0, 0, - 1
  18797. ];
  18798. var indices = [
  18799. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  18800. ];
  18801. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18802. this.type = 'OctahedronBufferGeometry';
  18803. this.parameters = {
  18804. radius: radius,
  18805. detail: detail
  18806. };
  18807. }
  18808. OctahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18809. OctahedronBufferGeometry.prototype.constructor = OctahedronBufferGeometry;
  18810. /**
  18811. * @author timothypratley / https://github.com/timothypratley
  18812. */
  18813. function OctahedronGeometry( radius, detail ) {
  18814. Geometry.call( this );
  18815. this.type = 'OctahedronGeometry';
  18816. this.parameters = {
  18817. radius: radius,
  18818. detail: detail
  18819. };
  18820. this.fromBufferGeometry( new OctahedronBufferGeometry( radius, detail ) );
  18821. this.mergeVertices();
  18822. }
  18823. OctahedronGeometry.prototype = Object.create( Geometry.prototype );
  18824. OctahedronGeometry.prototype.constructor = OctahedronGeometry;
  18825. /**
  18826. * @author Mugen87 / https://github.com/Mugen87
  18827. */
  18828. function IcosahedronBufferGeometry( radius, detail ) {
  18829. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18830. var vertices = [
  18831. - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t, 0,
  18832. 0, - 1, t, 0, 1, t, 0, - 1, - t, 0, 1, - t,
  18833. t, 0, - 1, t, 0, 1, - t, 0, - 1, - t, 0, 1
  18834. ];
  18835. var indices = [
  18836. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  18837. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  18838. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  18839. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  18840. ];
  18841. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18842. this.type = 'IcosahedronBufferGeometry';
  18843. this.parameters = {
  18844. radius: radius,
  18845. detail: detail
  18846. };
  18847. }
  18848. IcosahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18849. IcosahedronBufferGeometry.prototype.constructor = IcosahedronBufferGeometry;
  18850. /**
  18851. * @author timothypratley / https://github.com/timothypratley
  18852. */
  18853. function IcosahedronGeometry( radius, detail ) {
  18854. Geometry.call( this );
  18855. this.type = 'IcosahedronGeometry';
  18856. this.parameters = {
  18857. radius: radius,
  18858. detail: detail
  18859. };
  18860. this.fromBufferGeometry( new IcosahedronBufferGeometry( radius, detail ) );
  18861. this.mergeVertices();
  18862. }
  18863. IcosahedronGeometry.prototype = Object.create( Geometry.prototype );
  18864. IcosahedronGeometry.prototype.constructor = IcosahedronGeometry;
  18865. /**
  18866. * @author Mugen87 / https://github.com/Mugen87
  18867. */
  18868. function DodecahedronBufferGeometry( radius, detail ) {
  18869. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18870. var r = 1 / t;
  18871. var vertices = [
  18872. // (±1, ±1, ±1)
  18873. - 1, - 1, - 1, - 1, - 1, 1,
  18874. - 1, 1, - 1, - 1, 1, 1,
  18875. 1, - 1, - 1, 1, - 1, 1,
  18876. 1, 1, - 1, 1, 1, 1,
  18877. // (0, ±1/φ, ±φ)
  18878. 0, - r, - t, 0, - r, t,
  18879. 0, r, - t, 0, r, t,
  18880. // (±1/φ, ±φ, 0)
  18881. - r, - t, 0, - r, t, 0,
  18882. r, - t, 0, r, t, 0,
  18883. // (±φ, 0, ±1/φ)
  18884. - t, 0, - r, t, 0, - r,
  18885. - t, 0, r, t, 0, r
  18886. ];
  18887. var indices = [
  18888. 3, 11, 7, 3, 7, 15, 3, 15, 13,
  18889. 7, 19, 17, 7, 17, 6, 7, 6, 15,
  18890. 17, 4, 8, 17, 8, 10, 17, 10, 6,
  18891. 8, 0, 16, 8, 16, 2, 8, 2, 10,
  18892. 0, 12, 1, 0, 1, 18, 0, 18, 16,
  18893. 6, 10, 2, 6, 2, 13, 6, 13, 15,
  18894. 2, 16, 18, 2, 18, 3, 2, 3, 13,
  18895. 18, 1, 9, 18, 9, 11, 18, 11, 3,
  18896. 4, 14, 12, 4, 12, 0, 4, 0, 8,
  18897. 11, 9, 5, 11, 5, 19, 11, 19, 7,
  18898. 19, 5, 14, 19, 14, 4, 19, 4, 17,
  18899. 1, 12, 14, 1, 14, 5, 1, 5, 9
  18900. ];
  18901. PolyhedronBufferGeometry.call( this, vertices, indices, radius, detail );
  18902. this.type = 'DodecahedronBufferGeometry';
  18903. this.parameters = {
  18904. radius: radius,
  18905. detail: detail
  18906. };
  18907. }
  18908. DodecahedronBufferGeometry.prototype = Object.create( PolyhedronBufferGeometry.prototype );
  18909. DodecahedronBufferGeometry.prototype.constructor = DodecahedronBufferGeometry;
  18910. /**
  18911. * @author Abe Pazos / https://hamoid.com
  18912. */
  18913. function DodecahedronGeometry( radius, detail ) {
  18914. Geometry.call( this );
  18915. this.type = 'DodecahedronGeometry';
  18916. this.parameters = {
  18917. radius: radius,
  18918. detail: detail
  18919. };
  18920. this.fromBufferGeometry( new DodecahedronBufferGeometry( radius, detail ) );
  18921. this.mergeVertices();
  18922. }
  18923. DodecahedronGeometry.prototype = Object.create( Geometry.prototype );
  18924. DodecahedronGeometry.prototype.constructor = DodecahedronGeometry;
  18925. /**
  18926. * @author clockworkgeek / https://github.com/clockworkgeek
  18927. * @author timothypratley / https://github.com/timothypratley
  18928. * @author WestLangley / http://github.com/WestLangley
  18929. */
  18930. function PolyhedronGeometry( vertices, indices, radius, detail ) {
  18931. Geometry.call( this );
  18932. this.type = 'PolyhedronGeometry';
  18933. this.parameters = {
  18934. vertices: vertices,
  18935. indices: indices,
  18936. radius: radius,
  18937. detail: detail
  18938. };
  18939. this.fromBufferGeometry( new PolyhedronBufferGeometry( vertices, indices, radius, detail ) );
  18940. this.mergeVertices();
  18941. }
  18942. PolyhedronGeometry.prototype = Object.create( Geometry.prototype );
  18943. PolyhedronGeometry.prototype.constructor = PolyhedronGeometry;
  18944. /**
  18945. * @author Mugen87 / https://github.com/Mugen87
  18946. *
  18947. * Creates a tube which extrudes along a 3d spline.
  18948. *
  18949. */
  18950. function TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed ) {
  18951. BufferGeometry.call( this );
  18952. this.type = 'TubeBufferGeometry';
  18953. this.parameters = {
  18954. path: path,
  18955. tubularSegments: tubularSegments,
  18956. radius: radius,
  18957. radialSegments: radialSegments,
  18958. closed: closed
  18959. };
  18960. tubularSegments = tubularSegments || 64;
  18961. radius = radius || 1;
  18962. radialSegments = radialSegments || 8;
  18963. closed = closed || false;
  18964. var frames = path.computeFrenetFrames( tubularSegments, closed );
  18965. // expose internals
  18966. this.tangents = frames.tangents;
  18967. this.normals = frames.normals;
  18968. this.binormals = frames.binormals;
  18969. // helper variables
  18970. var vertex = new Vector3();
  18971. var normal = new Vector3();
  18972. var uv = new Vector2();
  18973. var i, j;
  18974. // buffer
  18975. var vertices = [];
  18976. var normals = [];
  18977. var uvs = [];
  18978. var indices = [];
  18979. // create buffer data
  18980. generateBufferData();
  18981. // build geometry
  18982. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  18983. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  18984. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  18985. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  18986. // functions
  18987. function generateBufferData() {
  18988. for ( i = 0; i < tubularSegments; i ++ ) {
  18989. generateSegment( i );
  18990. }
  18991. // if the geometry is not closed, generate the last row of vertices and normals
  18992. // at the regular position on the given path
  18993. //
  18994. // if the geometry is closed, duplicate the first row of vertices and normals (uvs will differ)
  18995. generateSegment( ( closed === false ) ? tubularSegments : 0 );
  18996. // uvs are generated in a separate function.
  18997. // this makes it easy compute correct values for closed geometries
  18998. generateUVs();
  18999. // finally create faces
  19000. generateIndices();
  19001. }
  19002. function generateSegment( i ) {
  19003. // we use getPointAt to sample evenly distributed points from the given path
  19004. var P = path.getPointAt( i / tubularSegments );
  19005. // retrieve corresponding normal and binormal
  19006. var N = frames.normals[ i ];
  19007. var B = frames.binormals[ i ];
  19008. // generate normals and vertices for the current segment
  19009. for ( j = 0; j <= radialSegments; j ++ ) {
  19010. var v = j / radialSegments * Math.PI * 2;
  19011. var sin = Math.sin( v );
  19012. var cos = - Math.cos( v );
  19013. // normal
  19014. normal.x = ( cos * N.x + sin * B.x );
  19015. normal.y = ( cos * N.y + sin * B.y );
  19016. normal.z = ( cos * N.z + sin * B.z );
  19017. normal.normalize();
  19018. normals.push( normal.x, normal.y, normal.z );
  19019. // vertex
  19020. vertex.x = P.x + radius * normal.x;
  19021. vertex.y = P.y + radius * normal.y;
  19022. vertex.z = P.z + radius * normal.z;
  19023. vertices.push( vertex.x, vertex.y, vertex.z );
  19024. }
  19025. }
  19026. function generateIndices() {
  19027. for ( j = 1; j <= tubularSegments; j ++ ) {
  19028. for ( i = 1; i <= radialSegments; i ++ ) {
  19029. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19030. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19031. var c = ( radialSegments + 1 ) * j + i;
  19032. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19033. // faces
  19034. indices.push( a, b, d );
  19035. indices.push( b, c, d );
  19036. }
  19037. }
  19038. }
  19039. function generateUVs() {
  19040. for ( i = 0; i <= tubularSegments; i ++ ) {
  19041. for ( j = 0; j <= radialSegments; j ++ ) {
  19042. uv.x = i / tubularSegments;
  19043. uv.y = j / radialSegments;
  19044. uvs.push( uv.x, uv.y );
  19045. }
  19046. }
  19047. }
  19048. }
  19049. TubeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19050. TubeBufferGeometry.prototype.constructor = TubeBufferGeometry;
  19051. /**
  19052. * @author oosmoxiecode / https://github.com/oosmoxiecode
  19053. * @author WestLangley / https://github.com/WestLangley
  19054. * @author zz85 / https://github.com/zz85
  19055. * @author miningold / https://github.com/miningold
  19056. * @author jonobr1 / https://github.com/jonobr1
  19057. *
  19058. * Creates a tube which extrudes along a 3d spline.
  19059. */
  19060. function TubeGeometry( path, tubularSegments, radius, radialSegments, closed, taper ) {
  19061. Geometry.call( this );
  19062. this.type = 'TubeGeometry';
  19063. this.parameters = {
  19064. path: path,
  19065. tubularSegments: tubularSegments,
  19066. radius: radius,
  19067. radialSegments: radialSegments,
  19068. closed: closed
  19069. };
  19070. if ( taper !== undefined ) console.warn( 'THREE.TubeGeometry: taper has been removed.' );
  19071. var bufferGeometry = new TubeBufferGeometry( path, tubularSegments, radius, radialSegments, closed );
  19072. // expose internals
  19073. this.tangents = bufferGeometry.tangents;
  19074. this.normals = bufferGeometry.normals;
  19075. this.binormals = bufferGeometry.binormals;
  19076. // create geometry
  19077. this.fromBufferGeometry( bufferGeometry );
  19078. this.mergeVertices();
  19079. }
  19080. TubeGeometry.prototype = Object.create( Geometry.prototype );
  19081. TubeGeometry.prototype.constructor = TubeGeometry;
  19082. /**
  19083. * @author Mugen87 / https://github.com/Mugen87
  19084. *
  19085. * see: http://www.blackpawn.com/texts/pqtorus/
  19086. */
  19087. function TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) {
  19088. BufferGeometry.call( this );
  19089. this.type = 'TorusKnotBufferGeometry';
  19090. this.parameters = {
  19091. radius: radius,
  19092. tube: tube,
  19093. tubularSegments: tubularSegments,
  19094. radialSegments: radialSegments,
  19095. p: p,
  19096. q: q
  19097. };
  19098. radius = radius || 100;
  19099. tube = tube || 40;
  19100. tubularSegments = Math.floor( tubularSegments ) || 64;
  19101. radialSegments = Math.floor( radialSegments ) || 8;
  19102. p = p || 2;
  19103. q = q || 3;
  19104. // used to calculate buffer length
  19105. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  19106. var indexCount = radialSegments * tubularSegments * 2 * 3;
  19107. // buffers
  19108. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  19109. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19110. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  19111. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  19112. // helper variables
  19113. var i, j, index = 0, indexOffset = 0;
  19114. var vertex = new Vector3();
  19115. var normal = new Vector3();
  19116. var uv = new Vector2();
  19117. var P1 = new Vector3();
  19118. var P2 = new Vector3();
  19119. var B = new Vector3();
  19120. var T = new Vector3();
  19121. var N = new Vector3();
  19122. // generate vertices, normals and uvs
  19123. for ( i = 0; i <= tubularSegments; ++ i ) {
  19124. // the radian "u" is used to calculate the position on the torus curve of the current tubular segement
  19125. var u = i / tubularSegments * p * Math.PI * 2;
  19126. // now we calculate two points. P1 is our current position on the curve, P2 is a little farther ahead.
  19127. // these points are used to create a special "coordinate space", which is necessary to calculate the correct vertex positions
  19128. calculatePositionOnCurve( u, p, q, radius, P1 );
  19129. calculatePositionOnCurve( u + 0.01, p, q, radius, P2 );
  19130. // calculate orthonormal basis
  19131. T.subVectors( P2, P1 );
  19132. N.addVectors( P2, P1 );
  19133. B.crossVectors( T, N );
  19134. N.crossVectors( B, T );
  19135. // normalize B, N. T can be ignored, we don't use it
  19136. B.normalize();
  19137. N.normalize();
  19138. for ( j = 0; j <= radialSegments; ++ j ) {
  19139. // now calculate the vertices. they are nothing more than an extrusion of the torus curve.
  19140. // because we extrude a shape in the xy-plane, there is no need to calculate a z-value.
  19141. var v = j / radialSegments * Math.PI * 2;
  19142. var cx = - tube * Math.cos( v );
  19143. var cy = tube * Math.sin( v );
  19144. // now calculate the final vertex position.
  19145. // first we orient the extrusion with our basis vectos, then we add it to the current position on the curve
  19146. vertex.x = P1.x + ( cx * N.x + cy * B.x );
  19147. vertex.y = P1.y + ( cx * N.y + cy * B.y );
  19148. vertex.z = P1.z + ( cx * N.z + cy * B.z );
  19149. // vertex
  19150. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  19151. // normal (P1 is always the center/origin of the extrusion, thus we can use it to calculate the normal)
  19152. normal.subVectors( vertex, P1 ).normalize();
  19153. normals.setXYZ( index, normal.x, normal.y, normal.z );
  19154. // uv
  19155. uv.x = i / tubularSegments;
  19156. uv.y = j / radialSegments;
  19157. uvs.setXY( index, uv.x, uv.y );
  19158. // increase index
  19159. index ++;
  19160. }
  19161. }
  19162. // generate indices
  19163. for ( j = 1; j <= tubularSegments; j ++ ) {
  19164. for ( i = 1; i <= radialSegments; i ++ ) {
  19165. // indices
  19166. var a = ( radialSegments + 1 ) * ( j - 1 ) + ( i - 1 );
  19167. var b = ( radialSegments + 1 ) * j + ( i - 1 );
  19168. var c = ( radialSegments + 1 ) * j + i;
  19169. var d = ( radialSegments + 1 ) * ( j - 1 ) + i;
  19170. // face one
  19171. indices.setX( indexOffset, a ); indexOffset++;
  19172. indices.setX( indexOffset, b ); indexOffset++;
  19173. indices.setX( indexOffset, d ); indexOffset++;
  19174. // face two
  19175. indices.setX( indexOffset, b ); indexOffset++;
  19176. indices.setX( indexOffset, c ); indexOffset++;
  19177. indices.setX( indexOffset, d ); indexOffset++;
  19178. }
  19179. }
  19180. // build geometry
  19181. this.setIndex( indices );
  19182. this.addAttribute( 'position', vertices );
  19183. this.addAttribute( 'normal', normals );
  19184. this.addAttribute( 'uv', uvs );
  19185. // this function calculates the current position on the torus curve
  19186. function calculatePositionOnCurve( u, p, q, radius, position ) {
  19187. var cu = Math.cos( u );
  19188. var su = Math.sin( u );
  19189. var quOverP = q / p * u;
  19190. var cs = Math.cos( quOverP );
  19191. position.x = radius * ( 2 + cs ) * 0.5 * cu;
  19192. position.y = radius * ( 2 + cs ) * su * 0.5;
  19193. position.z = radius * Math.sin( quOverP ) * 0.5;
  19194. }
  19195. }
  19196. TorusKnotBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19197. TorusKnotBufferGeometry.prototype.constructor = TorusKnotBufferGeometry;
  19198. /**
  19199. * @author oosmoxiecode
  19200. */
  19201. function TorusKnotGeometry( radius, tube, tubularSegments, radialSegments, p, q, heightScale ) {
  19202. Geometry.call( this );
  19203. this.type = 'TorusKnotGeometry';
  19204. this.parameters = {
  19205. radius: radius,
  19206. tube: tube,
  19207. tubularSegments: tubularSegments,
  19208. radialSegments: radialSegments,
  19209. p: p,
  19210. q: q
  19211. };
  19212. if( heightScale !== undefined ) console.warn( 'THREE.TorusKnotGeometry: heightScale has been deprecated. Use .scale( x, y, z ) instead.' );
  19213. this.fromBufferGeometry( new TorusKnotBufferGeometry( radius, tube, tubularSegments, radialSegments, p, q ) );
  19214. this.mergeVertices();
  19215. }
  19216. TorusKnotGeometry.prototype = Object.create( Geometry.prototype );
  19217. TorusKnotGeometry.prototype.constructor = TorusKnotGeometry;
  19218. /**
  19219. * @author Mugen87 / https://github.com/Mugen87
  19220. */
  19221. function TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19222. BufferGeometry.call( this );
  19223. this.type = 'TorusBufferGeometry';
  19224. this.parameters = {
  19225. radius: radius,
  19226. tube: tube,
  19227. radialSegments: radialSegments,
  19228. tubularSegments: tubularSegments,
  19229. arc: arc
  19230. };
  19231. radius = radius || 100;
  19232. tube = tube || 40;
  19233. radialSegments = Math.floor( radialSegments ) || 8;
  19234. tubularSegments = Math.floor( tubularSegments ) || 6;
  19235. arc = arc || Math.PI * 2;
  19236. // used to calculate buffer length
  19237. var vertexCount = ( ( radialSegments + 1 ) * ( tubularSegments + 1 ) );
  19238. var indexCount = radialSegments * tubularSegments * 2 * 3;
  19239. // buffers
  19240. var indices = new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount );
  19241. var vertices = new Float32Array( vertexCount * 3 );
  19242. var normals = new Float32Array( vertexCount * 3 );
  19243. var uvs = new Float32Array( vertexCount * 2 );
  19244. // offset variables
  19245. var vertexBufferOffset = 0;
  19246. var uvBufferOffset = 0;
  19247. var indexBufferOffset = 0;
  19248. // helper variables
  19249. var center = new Vector3();
  19250. var vertex = new Vector3();
  19251. var normal = new Vector3();
  19252. var j, i;
  19253. // generate vertices, normals and uvs
  19254. for ( j = 0; j <= radialSegments; j ++ ) {
  19255. for ( i = 0; i <= tubularSegments; i ++ ) {
  19256. var u = i / tubularSegments * arc;
  19257. var v = j / radialSegments * Math.PI * 2;
  19258. // vertex
  19259. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  19260. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  19261. vertex.z = tube * Math.sin( v );
  19262. vertices[ vertexBufferOffset ] = vertex.x;
  19263. vertices[ vertexBufferOffset + 1 ] = vertex.y;
  19264. vertices[ vertexBufferOffset + 2 ] = vertex.z;
  19265. // this vector is used to calculate the normal
  19266. center.x = radius * Math.cos( u );
  19267. center.y = radius * Math.sin( u );
  19268. // normal
  19269. normal.subVectors( vertex, center ).normalize();
  19270. normals[ vertexBufferOffset ] = normal.x;
  19271. normals[ vertexBufferOffset + 1 ] = normal.y;
  19272. normals[ vertexBufferOffset + 2 ] = normal.z;
  19273. // uv
  19274. uvs[ uvBufferOffset ] = i / tubularSegments;
  19275. uvs[ uvBufferOffset + 1 ] = j / radialSegments;
  19276. // update offsets
  19277. vertexBufferOffset += 3;
  19278. uvBufferOffset += 2;
  19279. }
  19280. }
  19281. // generate indices
  19282. for ( j = 1; j <= radialSegments; j ++ ) {
  19283. for ( i = 1; i <= tubularSegments; i ++ ) {
  19284. // indices
  19285. var a = ( tubularSegments + 1 ) * j + i - 1;
  19286. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19287. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  19288. var d = ( tubularSegments + 1 ) * j + i;
  19289. // face one
  19290. indices[ indexBufferOffset ] = a;
  19291. indices[ indexBufferOffset + 1 ] = b;
  19292. indices[ indexBufferOffset + 2 ] = d;
  19293. // face two
  19294. indices[ indexBufferOffset + 3 ] = b;
  19295. indices[ indexBufferOffset + 4 ] = c;
  19296. indices[ indexBufferOffset + 5 ] = d;
  19297. // update offset
  19298. indexBufferOffset += 6;
  19299. }
  19300. }
  19301. // build geometry
  19302. this.setIndex( new BufferAttribute( indices, 1 ) );
  19303. this.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
  19304. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  19305. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  19306. }
  19307. TorusBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  19308. TorusBufferGeometry.prototype.constructor = TorusBufferGeometry;
  19309. /**
  19310. * @author oosmoxiecode
  19311. * @author mrdoob / http://mrdoob.com/
  19312. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19313. */
  19314. function TorusGeometry( radius, tube, radialSegments, tubularSegments, arc ) {
  19315. Geometry.call( this );
  19316. this.type = 'TorusGeometry';
  19317. this.parameters = {
  19318. radius: radius,
  19319. tube: tube,
  19320. radialSegments: radialSegments,
  19321. tubularSegments: tubularSegments,
  19322. arc: arc
  19323. };
  19324. this.fromBufferGeometry( new TorusBufferGeometry( radius, tube, radialSegments, tubularSegments, arc ) );
  19325. }
  19326. TorusGeometry.prototype = Object.create( Geometry.prototype );
  19327. TorusGeometry.prototype.constructor = TorusGeometry;
  19328. /**
  19329. * @author zz85 / http://www.lab4games.net/zz85/blog
  19330. */
  19331. var ShapeUtils = {
  19332. // calculate area of the contour polygon
  19333. area: function ( contour ) {
  19334. var n = contour.length;
  19335. var a = 0.0;
  19336. for ( var p = n - 1, q = 0; q < n; p = q ++ ) {
  19337. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  19338. }
  19339. return a * 0.5;
  19340. },
  19341. triangulate: ( function () {
  19342. /**
  19343. * This code is a quick port of code written in C++ which was submitted to
  19344. * flipcode.com by John W. Ratcliff // July 22, 2000
  19345. * See original code and more information here:
  19346. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  19347. *
  19348. * ported to actionscript by Zevan Rosser
  19349. * www.actionsnippet.com
  19350. *
  19351. * ported to javascript by Joshua Koo
  19352. * http://www.lab4games.net/zz85/blog
  19353. *
  19354. */
  19355. function snip( contour, u, v, w, n, verts ) {
  19356. var p;
  19357. var ax, ay, bx, by;
  19358. var cx, cy, px, py;
  19359. ax = contour[ verts[ u ] ].x;
  19360. ay = contour[ verts[ u ] ].y;
  19361. bx = contour[ verts[ v ] ].x;
  19362. by = contour[ verts[ v ] ].y;
  19363. cx = contour[ verts[ w ] ].x;
  19364. cy = contour[ verts[ w ] ].y;
  19365. if ( ( bx - ax ) * ( cy - ay ) - ( by - ay ) * ( cx - ax ) <= 0 ) return false;
  19366. var aX, aY, bX, bY, cX, cY;
  19367. var apx, apy, bpx, bpy, cpx, cpy;
  19368. var cCROSSap, bCROSScp, aCROSSbp;
  19369. aX = cx - bx; aY = cy - by;
  19370. bX = ax - cx; bY = ay - cy;
  19371. cX = bx - ax; cY = by - ay;
  19372. for ( p = 0; p < n; p ++ ) {
  19373. px = contour[ verts[ p ] ].x;
  19374. py = contour[ verts[ p ] ].y;
  19375. if ( ( ( px === ax ) && ( py === ay ) ) ||
  19376. ( ( px === bx ) && ( py === by ) ) ||
  19377. ( ( px === cx ) && ( py === cy ) ) ) continue;
  19378. apx = px - ax; apy = py - ay;
  19379. bpx = px - bx; bpy = py - by;
  19380. cpx = px - cx; cpy = py - cy;
  19381. // see if p is inside triangle abc
  19382. aCROSSbp = aX * bpy - aY * bpx;
  19383. cCROSSap = cX * apy - cY * apx;
  19384. bCROSScp = bX * cpy - bY * cpx;
  19385. if ( ( aCROSSbp >= - Number.EPSILON ) && ( bCROSScp >= - Number.EPSILON ) && ( cCROSSap >= - Number.EPSILON ) ) return false;
  19386. }
  19387. return true;
  19388. }
  19389. // takes in an contour array and returns
  19390. return function triangulate( contour, indices ) {
  19391. var n = contour.length;
  19392. if ( n < 3 ) return null;
  19393. var result = [],
  19394. verts = [],
  19395. vertIndices = [];
  19396. /* we want a counter-clockwise polygon in verts */
  19397. var u, v, w;
  19398. if ( ShapeUtils.area( contour ) > 0.0 ) {
  19399. for ( v = 0; v < n; v ++ ) verts[ v ] = v;
  19400. } else {
  19401. for ( v = 0; v < n; v ++ ) verts[ v ] = ( n - 1 ) - v;
  19402. }
  19403. var nv = n;
  19404. /* remove nv - 2 vertices, creating 1 triangle every time */
  19405. var count = 2 * nv; /* error detection */
  19406. for ( v = nv - 1; nv > 2; ) {
  19407. /* if we loop, it is probably a non-simple polygon */
  19408. if ( ( count -- ) <= 0 ) {
  19409. //** Triangulate: ERROR - probable bad polygon!
  19410. //throw ( "Warning, unable to triangulate polygon!" );
  19411. //return null;
  19412. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  19413. console.warn( 'THREE.ShapeUtils: Unable to triangulate polygon! in triangulate()' );
  19414. if ( indices ) return vertIndices;
  19415. return result;
  19416. }
  19417. /* three consecutive vertices in current polygon, <u,v,w> */
  19418. u = v; if ( nv <= u ) u = 0; /* previous */
  19419. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  19420. w = v + 1; if ( nv <= w ) w = 0; /* next */
  19421. if ( snip( contour, u, v, w, nv, verts ) ) {
  19422. var a, b, c, s, t;
  19423. /* true names of the vertices */
  19424. a = verts[ u ];
  19425. b = verts[ v ];
  19426. c = verts[ w ];
  19427. /* output Triangle */
  19428. result.push( [ contour[ a ],
  19429. contour[ b ],
  19430. contour[ c ] ] );
  19431. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  19432. /* remove v from the remaining polygon */
  19433. for ( s = v, t = v + 1; t < nv; s ++, t ++ ) {
  19434. verts[ s ] = verts[ t ];
  19435. }
  19436. nv --;
  19437. /* reset error detection counter */
  19438. count = 2 * nv;
  19439. }
  19440. }
  19441. if ( indices ) return vertIndices;
  19442. return result;
  19443. }
  19444. } )(),
  19445. triangulateShape: function ( contour, holes ) {
  19446. function removeDupEndPts(points) {
  19447. var l = points.length;
  19448. if ( l > 2 && points[ l - 1 ].equals( points[ 0 ] ) ) {
  19449. points.pop();
  19450. }
  19451. }
  19452. removeDupEndPts( contour );
  19453. holes.forEach( removeDupEndPts );
  19454. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  19455. // inOtherPt needs to be collinear to the inSegment
  19456. if ( inSegPt1.x !== inSegPt2.x ) {
  19457. if ( inSegPt1.x < inSegPt2.x ) {
  19458. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  19459. } else {
  19460. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  19461. }
  19462. } else {
  19463. if ( inSegPt1.y < inSegPt2.y ) {
  19464. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  19465. } else {
  19466. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  19467. }
  19468. }
  19469. }
  19470. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  19471. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  19472. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  19473. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  19474. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  19475. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  19476. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  19477. if ( Math.abs( limit ) > Number.EPSILON ) {
  19478. // not parallel
  19479. var perpSeg2;
  19480. if ( limit > 0 ) {
  19481. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  19482. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19483. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  19484. } else {
  19485. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  19486. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  19487. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  19488. }
  19489. // i.e. to reduce rounding errors
  19490. // intersection at endpoint of segment#1?
  19491. if ( perpSeg2 === 0 ) {
  19492. if ( ( inExcludeAdjacentSegs ) &&
  19493. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19494. return [ inSeg1Pt1 ];
  19495. }
  19496. if ( perpSeg2 === limit ) {
  19497. if ( ( inExcludeAdjacentSegs ) &&
  19498. ( ( perpSeg1 === 0 ) || ( perpSeg1 === limit ) ) ) return [];
  19499. return [ inSeg1Pt2 ];
  19500. }
  19501. // intersection at endpoint of segment#2?
  19502. if ( perpSeg1 === 0 ) return [ inSeg2Pt1 ];
  19503. if ( perpSeg1 === limit ) return [ inSeg2Pt2 ];
  19504. // return real intersection point
  19505. var factorSeg1 = perpSeg2 / limit;
  19506. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  19507. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  19508. } else {
  19509. // parallel or collinear
  19510. if ( ( perpSeg1 !== 0 ) ||
  19511. ( seg2dy * seg1seg2dx !== seg2dx * seg1seg2dy ) ) return [];
  19512. // they are collinear or degenerate
  19513. var seg1Pt = ( ( seg1dx === 0 ) && ( seg1dy === 0 ) ); // segment1 is just a point?
  19514. var seg2Pt = ( ( seg2dx === 0 ) && ( seg2dy === 0 ) ); // segment2 is just a point?
  19515. // both segments are points
  19516. if ( seg1Pt && seg2Pt ) {
  19517. if ( ( inSeg1Pt1.x !== inSeg2Pt1.x ) ||
  19518. ( inSeg1Pt1.y !== inSeg2Pt1.y ) ) return []; // they are distinct points
  19519. return [ inSeg1Pt1 ]; // they are the same point
  19520. }
  19521. // segment#1 is a single point
  19522. if ( seg1Pt ) {
  19523. if ( ! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  19524. return [ inSeg1Pt1 ];
  19525. }
  19526. // segment#2 is a single point
  19527. if ( seg2Pt ) {
  19528. if ( ! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  19529. return [ inSeg2Pt1 ];
  19530. }
  19531. // they are collinear segments, which might overlap
  19532. var seg1min, seg1max, seg1minVal, seg1maxVal;
  19533. var seg2min, seg2max, seg2minVal, seg2maxVal;
  19534. if ( seg1dx !== 0 ) {
  19535. // the segments are NOT on a vertical line
  19536. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  19537. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  19538. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  19539. } else {
  19540. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  19541. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  19542. }
  19543. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  19544. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  19545. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  19546. } else {
  19547. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  19548. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  19549. }
  19550. } else {
  19551. // the segments are on a vertical line
  19552. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  19553. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  19554. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  19555. } else {
  19556. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  19557. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  19558. }
  19559. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  19560. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  19561. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  19562. } else {
  19563. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  19564. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  19565. }
  19566. }
  19567. if ( seg1minVal <= seg2minVal ) {
  19568. if ( seg1maxVal < seg2minVal ) return [];
  19569. if ( seg1maxVal === seg2minVal ) {
  19570. if ( inExcludeAdjacentSegs ) return [];
  19571. return [ seg2min ];
  19572. }
  19573. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  19574. return [ seg2min, seg2max ];
  19575. } else {
  19576. if ( seg1minVal > seg2maxVal ) return [];
  19577. if ( seg1minVal === seg2maxVal ) {
  19578. if ( inExcludeAdjacentSegs ) return [];
  19579. return [ seg1min ];
  19580. }
  19581. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  19582. return [ seg1min, seg2max ];
  19583. }
  19584. }
  19585. }
  19586. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  19587. // The order of legs is important
  19588. // translation of all points, so that Vertex is at (0,0)
  19589. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  19590. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  19591. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  19592. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  19593. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  19594. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  19595. if ( Math.abs( from2toAngle ) > Number.EPSILON ) {
  19596. // angle != 180 deg.
  19597. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  19598. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  19599. if ( from2toAngle > 0 ) {
  19600. // main angle < 180 deg.
  19601. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  19602. } else {
  19603. // main angle > 180 deg.
  19604. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  19605. }
  19606. } else {
  19607. // angle == 180 deg.
  19608. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  19609. return ( from2otherAngle > 0 );
  19610. }
  19611. }
  19612. function removeHoles( contour, holes ) {
  19613. var shape = contour.concat(); // work on this shape
  19614. var hole;
  19615. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  19616. // Check if hole point lies within angle around shape point
  19617. var lastShapeIdx = shape.length - 1;
  19618. var prevShapeIdx = inShapeIdx - 1;
  19619. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  19620. var nextShapeIdx = inShapeIdx + 1;
  19621. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  19622. var insideAngle = isPointInsideAngle( shape[ inShapeIdx ], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[ inHoleIdx ] );
  19623. if ( ! insideAngle ) {
  19624. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  19625. return false;
  19626. }
  19627. // Check if shape point lies within angle around hole point
  19628. var lastHoleIdx = hole.length - 1;
  19629. var prevHoleIdx = inHoleIdx - 1;
  19630. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  19631. var nextHoleIdx = inHoleIdx + 1;
  19632. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  19633. insideAngle = isPointInsideAngle( hole[ inHoleIdx ], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[ inShapeIdx ] );
  19634. if ( ! insideAngle ) {
  19635. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  19636. return false;
  19637. }
  19638. return true;
  19639. }
  19640. function intersectsShapeEdge( inShapePt, inHolePt ) {
  19641. // checks for intersections with shape edges
  19642. var sIdx, nextIdx, intersection;
  19643. for ( sIdx = 0; sIdx < shape.length; sIdx ++ ) {
  19644. nextIdx = sIdx + 1; nextIdx %= shape.length;
  19645. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[ sIdx ], shape[ nextIdx ], true );
  19646. if ( intersection.length > 0 ) return true;
  19647. }
  19648. return false;
  19649. }
  19650. var indepHoles = [];
  19651. function intersectsHoleEdge( inShapePt, inHolePt ) {
  19652. // checks for intersections with hole edges
  19653. var ihIdx, chkHole,
  19654. hIdx, nextIdx, intersection;
  19655. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx ++ ) {
  19656. chkHole = holes[ indepHoles[ ihIdx ]];
  19657. for ( hIdx = 0; hIdx < chkHole.length; hIdx ++ ) {
  19658. nextIdx = hIdx + 1; nextIdx %= chkHole.length;
  19659. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[ hIdx ], chkHole[ nextIdx ], true );
  19660. if ( intersection.length > 0 ) return true;
  19661. }
  19662. }
  19663. return false;
  19664. }
  19665. var holeIndex, shapeIndex,
  19666. shapePt, holePt,
  19667. holeIdx, cutKey, failedCuts = [],
  19668. tmpShape1, tmpShape2,
  19669. tmpHole1, tmpHole2;
  19670. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19671. indepHoles.push( h );
  19672. }
  19673. var minShapeIndex = 0;
  19674. var counter = indepHoles.length * 2;
  19675. while ( indepHoles.length > 0 ) {
  19676. counter --;
  19677. if ( counter < 0 ) {
  19678. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  19679. break;
  19680. }
  19681. // search for shape-vertex and hole-vertex,
  19682. // which can be connected without intersections
  19683. for ( shapeIndex = minShapeIndex; shapeIndex < shape.length; shapeIndex ++ ) {
  19684. shapePt = shape[ shapeIndex ];
  19685. holeIndex = - 1;
  19686. // search for hole which can be reached without intersections
  19687. for ( var h = 0; h < indepHoles.length; h ++ ) {
  19688. holeIdx = indepHoles[ h ];
  19689. // prevent multiple checks
  19690. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  19691. if ( failedCuts[ cutKey ] !== undefined ) continue;
  19692. hole = holes[ holeIdx ];
  19693. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  19694. holePt = hole[ h2 ];
  19695. if ( ! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  19696. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  19697. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  19698. holeIndex = h2;
  19699. indepHoles.splice( h, 1 );
  19700. tmpShape1 = shape.slice( 0, shapeIndex + 1 );
  19701. tmpShape2 = shape.slice( shapeIndex );
  19702. tmpHole1 = hole.slice( holeIndex );
  19703. tmpHole2 = hole.slice( 0, holeIndex + 1 );
  19704. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  19705. minShapeIndex = shapeIndex;
  19706. // Debug only, to show the selected cuts
  19707. // glob_CutLines.push( [ shapePt, holePt ] );
  19708. break;
  19709. }
  19710. if ( holeIndex >= 0 ) break; // hole-vertex found
  19711. failedCuts[ cutKey ] = true; // remember failure
  19712. }
  19713. if ( holeIndex >= 0 ) break; // hole-vertex found
  19714. }
  19715. }
  19716. return shape; /* shape with no holes */
  19717. }
  19718. var i, il, f, face,
  19719. key, index,
  19720. allPointsMap = {};
  19721. // To maintain reference to old shape, one must match coordinates, or offset the indices from original arrays. It's probably easier to do the first.
  19722. var allpoints = contour.concat();
  19723. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  19724. Array.prototype.push.apply( allpoints, holes[ h ] );
  19725. }
  19726. //console.log( "allpoints",allpoints, allpoints.length );
  19727. // prepare all points map
  19728. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  19729. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  19730. if ( allPointsMap[ key ] !== undefined ) {
  19731. console.warn( "THREE.ShapeUtils: Duplicate point", key, i );
  19732. }
  19733. allPointsMap[ key ] = i;
  19734. }
  19735. // remove holes by cutting paths to holes and adding them to the shape
  19736. var shapeWithoutHoles = removeHoles( contour, holes );
  19737. var triangles = ShapeUtils.triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  19738. //console.log( "triangles",triangles, triangles.length );
  19739. // check all face vertices against all points map
  19740. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  19741. face = triangles[ i ];
  19742. for ( f = 0; f < 3; f ++ ) {
  19743. key = face[ f ].x + ":" + face[ f ].y;
  19744. index = allPointsMap[ key ];
  19745. if ( index !== undefined ) {
  19746. face[ f ] = index;
  19747. }
  19748. }
  19749. }
  19750. return triangles.concat();
  19751. },
  19752. isClockWise: function ( pts ) {
  19753. return ShapeUtils.area( pts ) < 0;
  19754. },
  19755. // Bezier Curves formulas obtained from
  19756. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  19757. // Quad Bezier Functions
  19758. b2: ( function () {
  19759. function b2p0( t, p ) {
  19760. var k = 1 - t;
  19761. return k * k * p;
  19762. }
  19763. function b2p1( t, p ) {
  19764. return 2 * ( 1 - t ) * t * p;
  19765. }
  19766. function b2p2( t, p ) {
  19767. return t * t * p;
  19768. }
  19769. return function b2( t, p0, p1, p2 ) {
  19770. return b2p0( t, p0 ) + b2p1( t, p1 ) + b2p2( t, p2 );
  19771. };
  19772. } )(),
  19773. // Cubic Bezier Functions
  19774. b3: ( function () {
  19775. function b3p0( t, p ) {
  19776. var k = 1 - t;
  19777. return k * k * k * p;
  19778. }
  19779. function b3p1( t, p ) {
  19780. var k = 1 - t;
  19781. return 3 * k * k * t * p;
  19782. }
  19783. function b3p2( t, p ) {
  19784. var k = 1 - t;
  19785. return 3 * k * t * t * p;
  19786. }
  19787. function b3p3( t, p ) {
  19788. return t * t * t * p;
  19789. }
  19790. return function b3( t, p0, p1, p2, p3 ) {
  19791. return b3p0( t, p0 ) + b3p1( t, p1 ) + b3p2( t, p2 ) + b3p3( t, p3 );
  19792. };
  19793. } )()
  19794. };
  19795. /**
  19796. * @author zz85 / http://www.lab4games.net/zz85/blog
  19797. *
  19798. * Creates extruded geometry from a path shape.
  19799. *
  19800. * parameters = {
  19801. *
  19802. * curveSegments: <int>, // number of points on the curves
  19803. * steps: <int>, // number of points for z-side extrusions / used for subdividing segments of extrude spline too
  19804. * amount: <int>, // Depth to extrude the shape
  19805. *
  19806. * bevelEnabled: <bool>, // turn on bevel
  19807. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19808. * bevelSize: <float>, // how far from shape outline is bevel
  19809. * bevelSegments: <int>, // number of bevel layers
  19810. *
  19811. * extrudePath: <THREE.Curve> // curve to extrude shape along
  19812. * frames: <Object> // containing arrays of tangents, normals, binormals
  19813. *
  19814. * uvGenerator: <Object> // object that provides UV generator functions
  19815. *
  19816. * }
  19817. **/
  19818. function ExtrudeGeometry( shapes, options ) {
  19819. if ( typeof( shapes ) === "undefined" ) {
  19820. shapes = [];
  19821. return;
  19822. }
  19823. Geometry.call( this );
  19824. this.type = 'ExtrudeGeometry';
  19825. shapes = Array.isArray( shapes ) ? shapes : [ shapes ];
  19826. this.addShapeList( shapes, options );
  19827. this.computeFaceNormals();
  19828. // can't really use automatic vertex normals
  19829. // as then front and back sides get smoothed too
  19830. // should do separate smoothing just for sides
  19831. //this.computeVertexNormals();
  19832. //console.log( "took", ( Date.now() - startTime ) );
  19833. }
  19834. ExtrudeGeometry.prototype = Object.create( Geometry.prototype );
  19835. ExtrudeGeometry.prototype.constructor = ExtrudeGeometry;
  19836. ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19837. var sl = shapes.length;
  19838. for ( var s = 0; s < sl; s ++ ) {
  19839. var shape = shapes[ s ];
  19840. this.addShape( shape, options );
  19841. }
  19842. };
  19843. ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19844. var amount = options.amount !== undefined ? options.amount : 100;
  19845. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19846. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19847. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19848. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19849. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19850. var steps = options.steps !== undefined ? options.steps : 1;
  19851. var extrudePath = options.extrudePath;
  19852. var extrudePts, extrudeByPath = false;
  19853. // Use default WorldUVGenerator if no UV generators are specified.
  19854. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : ExtrudeGeometry.WorldUVGenerator;
  19855. var splineTube, binormal, normal, position2;
  19856. if ( extrudePath ) {
  19857. extrudePts = extrudePath.getSpacedPoints( steps );
  19858. extrudeByPath = true;
  19859. bevelEnabled = false; // bevels not supported for path extrusion
  19860. // SETUP TNB variables
  19861. // TODO1 - have a .isClosed in spline?
  19862. splineTube = options.frames !== undefined ? options.frames : extrudePath.computeFrenetFrames( steps, false );
  19863. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19864. binormal = new Vector3();
  19865. normal = new Vector3();
  19866. position2 = new Vector3();
  19867. }
  19868. // Safeguards if bevels are not enabled
  19869. if ( ! bevelEnabled ) {
  19870. bevelSegments = 0;
  19871. bevelThickness = 0;
  19872. bevelSize = 0;
  19873. }
  19874. // Variables initialization
  19875. var ahole, h, hl; // looping of holes
  19876. var scope = this;
  19877. var shapesOffset = this.vertices.length;
  19878. var shapePoints = shape.extractPoints( curveSegments );
  19879. var vertices = shapePoints.shape;
  19880. var holes = shapePoints.holes;
  19881. var reverse = ! ShapeUtils.isClockWise( vertices );
  19882. if ( reverse ) {
  19883. vertices = vertices.reverse();
  19884. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19885. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19886. ahole = holes[ h ];
  19887. if ( ShapeUtils.isClockWise( ahole ) ) {
  19888. holes[ h ] = ahole.reverse();
  19889. }
  19890. }
  19891. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19892. }
  19893. var faces = ShapeUtils.triangulateShape( vertices, holes );
  19894. /* Vertices */
  19895. var contour = vertices; // vertices has all points but contour has only points of circumference
  19896. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19897. ahole = holes[ h ];
  19898. vertices = vertices.concat( ahole );
  19899. }
  19900. function scalePt2( pt, vec, size ) {
  19901. if ( ! vec ) console.error( "THREE.ExtrudeGeometry: vec does not exist" );
  19902. return vec.clone().multiplyScalar( size ).add( pt );
  19903. }
  19904. var b, bs, t, z,
  19905. vert, vlen = vertices.length,
  19906. face, flen = faces.length;
  19907. // Find directions for point movement
  19908. function getBevelVec( inPt, inPrev, inNext ) {
  19909. // computes for inPt the corresponding point inPt' on a new contour
  19910. // shifted by 1 unit (length of normalized vector) to the left
  19911. // if we walk along contour clockwise, this new contour is outside the old one
  19912. //
  19913. // inPt' is the intersection of the two lines parallel to the two
  19914. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19915. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19916. // good reading for geometry algorithms (here: line-line intersection)
  19917. // http://geomalgorithms.com/a05-_intersect-1.html
  19918. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19919. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19920. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19921. // check for collinear edges
  19922. var collinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19923. if ( Math.abs( collinear0 ) > Number.EPSILON ) {
  19924. // not collinear
  19925. // length of vectors for normalizing
  19926. var v_prev_len = Math.sqrt( v_prev_lensq );
  19927. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19928. // shift adjacent points by unit vectors to the left
  19929. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19930. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19931. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19932. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19933. // scaling factor for v_prev to intersection point
  19934. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19935. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19936. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19937. // vector from inPt to intersection point
  19938. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19939. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19940. // Don't normalize!, otherwise sharp corners become ugly
  19941. // but prevent crazy spikes
  19942. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y );
  19943. if ( v_trans_lensq <= 2 ) {
  19944. return new Vector2( v_trans_x, v_trans_y );
  19945. } else {
  19946. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19947. }
  19948. } else {
  19949. // handle special case of collinear edges
  19950. var direction_eq = false; // assumes: opposite
  19951. if ( v_prev_x > Number.EPSILON ) {
  19952. if ( v_next_x > Number.EPSILON ) {
  19953. direction_eq = true;
  19954. }
  19955. } else {
  19956. if ( v_prev_x < - Number.EPSILON ) {
  19957. if ( v_next_x < - Number.EPSILON ) {
  19958. direction_eq = true;
  19959. }
  19960. } else {
  19961. if ( Math.sign( v_prev_y ) === Math.sign( v_next_y ) ) {
  19962. direction_eq = true;
  19963. }
  19964. }
  19965. }
  19966. if ( direction_eq ) {
  19967. // console.log("Warning: lines are a straight sequence");
  19968. v_trans_x = - v_prev_y;
  19969. v_trans_y = v_prev_x;
  19970. shrink_by = Math.sqrt( v_prev_lensq );
  19971. } else {
  19972. // console.log("Warning: lines are a straight spike");
  19973. v_trans_x = v_prev_x;
  19974. v_trans_y = v_prev_y;
  19975. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19976. }
  19977. }
  19978. return new Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19979. }
  19980. var contourMovements = [];
  19981. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19982. if ( j === il ) j = 0;
  19983. if ( k === il ) k = 0;
  19984. // (j)---(i)---(k)
  19985. // console.log('i,j,k', i, j , k)
  19986. contourMovements[ i ] = getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19987. }
  19988. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19989. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19990. ahole = holes[ h ];
  19991. oneHoleMovements = [];
  19992. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19993. if ( j === il ) j = 0;
  19994. if ( k === il ) k = 0;
  19995. // (j)---(i)---(k)
  19996. oneHoleMovements[ i ] = getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19997. }
  19998. holesMovements.push( oneHoleMovements );
  19999. verticesMovements = verticesMovements.concat( oneHoleMovements );
  20000. }
  20001. // Loop bevelSegments, 1 for the front, 1 for the back
  20002. for ( b = 0; b < bevelSegments; b ++ ) {
  20003. //for ( b = bevelSegments; b > 0; b -- ) {
  20004. t = b / bevelSegments;
  20005. z = bevelThickness * Math.cos( t * Math.PI / 2 );
  20006. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20007. // contract shape
  20008. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20009. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20010. v( vert.x, vert.y, - z );
  20011. }
  20012. // expand holes
  20013. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20014. ahole = holes[ h ];
  20015. oneHoleMovements = holesMovements[ h ];
  20016. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20017. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20018. v( vert.x, vert.y, - z );
  20019. }
  20020. }
  20021. }
  20022. bs = bevelSize;
  20023. // Back facing vertices
  20024. for ( i = 0; i < vlen; i ++ ) {
  20025. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20026. if ( ! extrudeByPath ) {
  20027. v( vert.x, vert.y, 0 );
  20028. } else {
  20029. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20030. normal.copy( splineTube.normals[ 0 ] ).multiplyScalar( vert.x );
  20031. binormal.copy( splineTube.binormals[ 0 ] ).multiplyScalar( vert.y );
  20032. position2.copy( extrudePts[ 0 ] ).add( normal ).add( binormal );
  20033. v( position2.x, position2.y, position2.z );
  20034. }
  20035. }
  20036. // Add stepped vertices...
  20037. // Including front facing vertices
  20038. var s;
  20039. for ( s = 1; s <= steps; s ++ ) {
  20040. for ( i = 0; i < vlen; i ++ ) {
  20041. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20042. if ( ! extrudeByPath ) {
  20043. v( vert.x, vert.y, amount / steps * s );
  20044. } else {
  20045. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20046. normal.copy( splineTube.normals[ s ] ).multiplyScalar( vert.x );
  20047. binormal.copy( splineTube.binormals[ s ] ).multiplyScalar( vert.y );
  20048. position2.copy( extrudePts[ s ] ).add( normal ).add( binormal );
  20049. v( position2.x, position2.y, position2.z );
  20050. }
  20051. }
  20052. }
  20053. // Add bevel segments planes
  20054. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20055. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20056. t = b / bevelSegments;
  20057. z = bevelThickness * Math.cos ( t * Math.PI / 2 );
  20058. bs = bevelSize * Math.sin( t * Math.PI / 2 );
  20059. // contract shape
  20060. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20061. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20062. v( vert.x, vert.y, amount + z );
  20063. }
  20064. // expand holes
  20065. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20066. ahole = holes[ h ];
  20067. oneHoleMovements = holesMovements[ h ];
  20068. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20069. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20070. if ( ! extrudeByPath ) {
  20071. v( vert.x, vert.y, amount + z );
  20072. } else {
  20073. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20074. }
  20075. }
  20076. }
  20077. }
  20078. /* Faces */
  20079. // Top and bottom faces
  20080. buildLidFaces();
  20081. // Sides faces
  20082. buildSideFaces();
  20083. ///// Internal functions
  20084. function buildLidFaces() {
  20085. if ( bevelEnabled ) {
  20086. var layer = 0; // steps + 1
  20087. var offset = vlen * layer;
  20088. // Bottom faces
  20089. for ( i = 0; i < flen; i ++ ) {
  20090. face = faces[ i ];
  20091. f3( face[ 2 ] + offset, face[ 1 ] + offset, face[ 0 ] + offset );
  20092. }
  20093. layer = steps + bevelSegments * 2;
  20094. offset = vlen * layer;
  20095. // Top faces
  20096. for ( i = 0; i < flen; i ++ ) {
  20097. face = faces[ i ];
  20098. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset );
  20099. }
  20100. } else {
  20101. // Bottom faces
  20102. for ( i = 0; i < flen; i ++ ) {
  20103. face = faces[ i ];
  20104. f3( face[ 2 ], face[ 1 ], face[ 0 ] );
  20105. }
  20106. // Top faces
  20107. for ( i = 0; i < flen; i ++ ) {
  20108. face = faces[ i ];
  20109. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps );
  20110. }
  20111. }
  20112. }
  20113. // Create faces for the z-sides of the shape
  20114. function buildSideFaces() {
  20115. var layeroffset = 0;
  20116. sidewalls( contour, layeroffset );
  20117. layeroffset += contour.length;
  20118. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20119. ahole = holes[ h ];
  20120. sidewalls( ahole, layeroffset );
  20121. //, true
  20122. layeroffset += ahole.length;
  20123. }
  20124. }
  20125. function sidewalls( contour, layeroffset ) {
  20126. var j, k;
  20127. i = contour.length;
  20128. while ( -- i >= 0 ) {
  20129. j = i;
  20130. k = i - 1;
  20131. if ( k < 0 ) k = contour.length - 1;
  20132. //console.log('b', i,j, i-1, k,vertices.length);
  20133. var s = 0, sl = steps + bevelSegments * 2;
  20134. for ( s = 0; s < sl; s ++ ) {
  20135. var slen1 = vlen * s;
  20136. var slen2 = vlen * ( s + 1 );
  20137. var a = layeroffset + j + slen1,
  20138. b = layeroffset + k + slen1,
  20139. c = layeroffset + k + slen2,
  20140. d = layeroffset + j + slen2;
  20141. f4( a, b, c, d, contour, s, sl, j, k );
  20142. }
  20143. }
  20144. }
  20145. function v( x, y, z ) {
  20146. scope.vertices.push( new Vector3( x, y, z ) );
  20147. }
  20148. function f3( a, b, c ) {
  20149. a += shapesOffset;
  20150. b += shapesOffset;
  20151. c += shapesOffset;
  20152. scope.faces.push( new Face3( a, b, c, null, null, 0 ) );
  20153. var uvs = uvgen.generateTopUV( scope, a, b, c );
  20154. scope.faceVertexUvs[ 0 ].push( uvs );
  20155. }
  20156. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20157. a += shapesOffset;
  20158. b += shapesOffset;
  20159. c += shapesOffset;
  20160. d += shapesOffset;
  20161. scope.faces.push( new Face3( a, b, d, null, null, 1 ) );
  20162. scope.faces.push( new Face3( b, c, d, null, null, 1 ) );
  20163. var uvs = uvgen.generateSideWallUV( scope, a, b, c, d );
  20164. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20165. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20166. }
  20167. };
  20168. ExtrudeGeometry.WorldUVGenerator = {
  20169. generateTopUV: function ( geometry, indexA, indexB, indexC ) {
  20170. var vertices = geometry.vertices;
  20171. var a = vertices[ indexA ];
  20172. var b = vertices[ indexB ];
  20173. var c = vertices[ indexC ];
  20174. return [
  20175. new Vector2( a.x, a.y ),
  20176. new Vector2( b.x, b.y ),
  20177. new Vector2( c.x, c.y )
  20178. ];
  20179. },
  20180. generateSideWallUV: function ( geometry, indexA, indexB, indexC, indexD ) {
  20181. var vertices = geometry.vertices;
  20182. var a = vertices[ indexA ];
  20183. var b = vertices[ indexB ];
  20184. var c = vertices[ indexC ];
  20185. var d = vertices[ indexD ];
  20186. if ( Math.abs( a.y - b.y ) < 0.01 ) {
  20187. return [
  20188. new Vector2( a.x, 1 - a.z ),
  20189. new Vector2( b.x, 1 - b.z ),
  20190. new Vector2( c.x, 1 - c.z ),
  20191. new Vector2( d.x, 1 - d.z )
  20192. ];
  20193. } else {
  20194. return [
  20195. new Vector2( a.y, 1 - a.z ),
  20196. new Vector2( b.y, 1 - b.z ),
  20197. new Vector2( c.y, 1 - c.z ),
  20198. new Vector2( d.y, 1 - d.z )
  20199. ];
  20200. }
  20201. }
  20202. };
  20203. /**
  20204. * @author zz85 / http://www.lab4games.net/zz85/blog
  20205. * @author alteredq / http://alteredqualia.com/
  20206. *
  20207. * Text = 3D Text
  20208. *
  20209. * parameters = {
  20210. * font: <THREE.Font>, // font
  20211. *
  20212. * size: <float>, // size of the text
  20213. * height: <float>, // thickness to extrude text
  20214. * curveSegments: <int>, // number of points on the curves
  20215. *
  20216. * bevelEnabled: <bool>, // turn on bevel
  20217. * bevelThickness: <float>, // how deep into text bevel goes
  20218. * bevelSize: <float> // how far from text outline is bevel
  20219. * }
  20220. */
  20221. function TextGeometry( text, parameters ) {
  20222. parameters = parameters || {};
  20223. var font = parameters.font;
  20224. if ( (font && font.isFont) === false ) {
  20225. console.error( 'THREE.TextGeometry: font parameter is not an instance of THREE.Font.' );
  20226. return new Geometry();
  20227. }
  20228. var shapes = font.generateShapes( text, parameters.size, parameters.curveSegments );
  20229. // translate parameters to ExtrudeGeometry API
  20230. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20231. // defaults
  20232. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20233. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20234. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20235. ExtrudeGeometry.call( this, shapes, parameters );
  20236. this.type = 'TextGeometry';
  20237. }
  20238. TextGeometry.prototype = Object.create( ExtrudeGeometry.prototype );
  20239. TextGeometry.prototype.constructor = TextGeometry;
  20240. /**
  20241. * @author benaadams / https://twitter.com/ben_a_adams
  20242. * based on THREE.SphereGeometry
  20243. */
  20244. function SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20245. BufferGeometry.call( this );
  20246. this.type = 'SphereBufferGeometry';
  20247. this.parameters = {
  20248. radius: radius,
  20249. widthSegments: widthSegments,
  20250. heightSegments: heightSegments,
  20251. phiStart: phiStart,
  20252. phiLength: phiLength,
  20253. thetaStart: thetaStart,
  20254. thetaLength: thetaLength
  20255. };
  20256. radius = radius || 50;
  20257. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20258. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20259. phiStart = phiStart !== undefined ? phiStart : 0;
  20260. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20261. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20262. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20263. var thetaEnd = thetaStart + thetaLength;
  20264. var vertexCount = ( ( widthSegments + 1 ) * ( heightSegments + 1 ) );
  20265. var positions = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20266. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20267. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  20268. var index = 0, vertices = [], normal = new Vector3();
  20269. for ( var y = 0; y <= heightSegments; y ++ ) {
  20270. var verticesRow = [];
  20271. var v = y / heightSegments;
  20272. for ( var x = 0; x <= widthSegments; x ++ ) {
  20273. var u = x / widthSegments;
  20274. var px = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20275. var py = radius * Math.cos( thetaStart + v * thetaLength );
  20276. var pz = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20277. normal.set( px, py, pz ).normalize();
  20278. positions.setXYZ( index, px, py, pz );
  20279. normals.setXYZ( index, normal.x, normal.y, normal.z );
  20280. uvs.setXY( index, u, 1 - v );
  20281. verticesRow.push( index );
  20282. index ++;
  20283. }
  20284. vertices.push( verticesRow );
  20285. }
  20286. var indices = [];
  20287. for ( var y = 0; y < heightSegments; y ++ ) {
  20288. for ( var x = 0; x < widthSegments; x ++ ) {
  20289. var v1 = vertices[ y ][ x + 1 ];
  20290. var v2 = vertices[ y ][ x ];
  20291. var v3 = vertices[ y + 1 ][ x ];
  20292. var v4 = vertices[ y + 1 ][ x + 1 ];
  20293. if ( y !== 0 || thetaStart > 0 ) indices.push( v1, v2, v4 );
  20294. if ( y !== heightSegments - 1 || thetaEnd < Math.PI ) indices.push( v2, v3, v4 );
  20295. }
  20296. }
  20297. this.setIndex( new ( positions.count > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  20298. this.addAttribute( 'position', positions );
  20299. this.addAttribute( 'normal', normals );
  20300. this.addAttribute( 'uv', uvs );
  20301. this.boundingSphere = new Sphere( new Vector3(), radius );
  20302. }
  20303. SphereBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20304. SphereBufferGeometry.prototype.constructor = SphereBufferGeometry;
  20305. /**
  20306. * @author mrdoob / http://mrdoob.com/
  20307. */
  20308. function SphereGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20309. Geometry.call( this );
  20310. this.type = 'SphereGeometry';
  20311. this.parameters = {
  20312. radius: radius,
  20313. widthSegments: widthSegments,
  20314. heightSegments: heightSegments,
  20315. phiStart: phiStart,
  20316. phiLength: phiLength,
  20317. thetaStart: thetaStart,
  20318. thetaLength: thetaLength
  20319. };
  20320. this.fromBufferGeometry( new SphereBufferGeometry( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) );
  20321. }
  20322. SphereGeometry.prototype = Object.create( Geometry.prototype );
  20323. SphereGeometry.prototype.constructor = SphereGeometry;
  20324. /**
  20325. * @author Mugen87 / https://github.com/Mugen87
  20326. */
  20327. function RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20328. BufferGeometry.call( this );
  20329. this.type = 'RingBufferGeometry';
  20330. this.parameters = {
  20331. innerRadius: innerRadius,
  20332. outerRadius: outerRadius,
  20333. thetaSegments: thetaSegments,
  20334. phiSegments: phiSegments,
  20335. thetaStart: thetaStart,
  20336. thetaLength: thetaLength
  20337. };
  20338. innerRadius = innerRadius || 20;
  20339. outerRadius = outerRadius || 50;
  20340. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20341. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20342. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20343. phiSegments = phiSegments !== undefined ? Math.max( 1, phiSegments ) : 1;
  20344. // these are used to calculate buffer length
  20345. var vertexCount = ( thetaSegments + 1 ) * ( phiSegments + 1 );
  20346. var indexCount = thetaSegments * phiSegments * 2 * 3;
  20347. // buffers
  20348. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  20349. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20350. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20351. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  20352. // some helper variables
  20353. var index = 0, indexOffset = 0, segment;
  20354. var radius = innerRadius;
  20355. var radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20356. var vertex = new Vector3();
  20357. var uv = new Vector2();
  20358. var j, i;
  20359. // generate vertices, normals and uvs
  20360. // values are generate from the inside of the ring to the outside
  20361. for ( j = 0; j <= phiSegments; j ++ ) {
  20362. for ( i = 0; i <= thetaSegments; i ++ ) {
  20363. segment = thetaStart + i / thetaSegments * thetaLength;
  20364. // vertex
  20365. vertex.x = radius * Math.cos( segment );
  20366. vertex.y = radius * Math.sin( segment );
  20367. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  20368. // normal
  20369. normals.setXYZ( index, 0, 0, 1 );
  20370. // uv
  20371. uv.x = ( vertex.x / outerRadius + 1 ) / 2;
  20372. uv.y = ( vertex.y / outerRadius + 1 ) / 2;
  20373. uvs.setXY( index, uv.x, uv.y );
  20374. // increase index
  20375. index++;
  20376. }
  20377. // increase the radius for next row of vertices
  20378. radius += radiusStep;
  20379. }
  20380. // generate indices
  20381. for ( j = 0; j < phiSegments; j ++ ) {
  20382. var thetaSegmentLevel = j * ( thetaSegments + 1 );
  20383. for ( i = 0; i < thetaSegments; i ++ ) {
  20384. segment = i + thetaSegmentLevel;
  20385. // indices
  20386. var a = segment;
  20387. var b = segment + thetaSegments + 1;
  20388. var c = segment + thetaSegments + 2;
  20389. var d = segment + 1;
  20390. // face one
  20391. indices.setX( indexOffset, a ); indexOffset++;
  20392. indices.setX( indexOffset, b ); indexOffset++;
  20393. indices.setX( indexOffset, c ); indexOffset++;
  20394. // face two
  20395. indices.setX( indexOffset, a ); indexOffset++;
  20396. indices.setX( indexOffset, c ); indexOffset++;
  20397. indices.setX( indexOffset, d ); indexOffset++;
  20398. }
  20399. }
  20400. // build geometry
  20401. this.setIndex( indices );
  20402. this.addAttribute( 'position', vertices );
  20403. this.addAttribute( 'normal', normals );
  20404. this.addAttribute( 'uv', uvs );
  20405. }
  20406. RingBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20407. RingBufferGeometry.prototype.constructor = RingBufferGeometry;
  20408. /**
  20409. * @author Kaleb Murphy
  20410. */
  20411. function RingGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20412. Geometry.call( this );
  20413. this.type = 'RingGeometry';
  20414. this.parameters = {
  20415. innerRadius: innerRadius,
  20416. outerRadius: outerRadius,
  20417. thetaSegments: thetaSegments,
  20418. phiSegments: phiSegments,
  20419. thetaStart: thetaStart,
  20420. thetaLength: thetaLength
  20421. };
  20422. this.fromBufferGeometry( new RingBufferGeometry( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) );
  20423. }
  20424. RingGeometry.prototype = Object.create( Geometry.prototype );
  20425. RingGeometry.prototype.constructor = RingGeometry;
  20426. /**
  20427. * @author mrdoob / http://mrdoob.com/
  20428. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20429. */
  20430. function PlaneGeometry( width, height, widthSegments, heightSegments ) {
  20431. Geometry.call( this );
  20432. this.type = 'PlaneGeometry';
  20433. this.parameters = {
  20434. width: width,
  20435. height: height,
  20436. widthSegments: widthSegments,
  20437. heightSegments: heightSegments
  20438. };
  20439. this.fromBufferGeometry( new PlaneBufferGeometry( width, height, widthSegments, heightSegments ) );
  20440. }
  20441. PlaneGeometry.prototype = Object.create( Geometry.prototype );
  20442. PlaneGeometry.prototype.constructor = PlaneGeometry;
  20443. /**
  20444. * @author Mugen87 / https://github.com/Mugen87
  20445. */
  20446. // points - to create a closed torus, one must use a set of points
  20447. // like so: [ a, b, c, d, a ], see first is the same as last.
  20448. // segments - the number of circumference segments to create
  20449. // phiStart - the starting radian
  20450. // phiLength - the radian (0 to 2PI) range of the lathed section
  20451. // 2PI is a closed lathe, less than 2PI is a portion.
  20452. function LatheBufferGeometry( points, segments, phiStart, phiLength ) {
  20453. BufferGeometry.call( this );
  20454. this.type = 'LatheBufferGeometry';
  20455. this.parameters = {
  20456. points: points,
  20457. segments: segments,
  20458. phiStart: phiStart,
  20459. phiLength: phiLength
  20460. };
  20461. segments = Math.floor( segments ) || 12;
  20462. phiStart = phiStart || 0;
  20463. phiLength = phiLength || Math.PI * 2;
  20464. // clamp phiLength so it's in range of [ 0, 2PI ]
  20465. phiLength = _Math.clamp( phiLength, 0, Math.PI * 2 );
  20466. // these are used to calculate buffer length
  20467. var vertexCount = ( segments + 1 ) * points.length;
  20468. var indexCount = segments * points.length * 2 * 3;
  20469. // buffers
  20470. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ) , 1 );
  20471. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20472. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  20473. // helper variables
  20474. var index = 0, indexOffset = 0, base;
  20475. var inverseSegments = 1.0 / segments;
  20476. var vertex = new Vector3();
  20477. var uv = new Vector2();
  20478. var i, j;
  20479. // generate vertices and uvs
  20480. for ( i = 0; i <= segments; i ++ ) {
  20481. var phi = phiStart + i * inverseSegments * phiLength;
  20482. var sin = Math.sin( phi );
  20483. var cos = Math.cos( phi );
  20484. for ( j = 0; j <= ( points.length - 1 ); j ++ ) {
  20485. // vertex
  20486. vertex.x = points[ j ].x * sin;
  20487. vertex.y = points[ j ].y;
  20488. vertex.z = points[ j ].x * cos;
  20489. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  20490. // uv
  20491. uv.x = i / segments;
  20492. uv.y = j / ( points.length - 1 );
  20493. uvs.setXY( index, uv.x, uv.y );
  20494. // increase index
  20495. index ++;
  20496. }
  20497. }
  20498. // generate indices
  20499. for ( i = 0; i < segments; i ++ ) {
  20500. for ( j = 0; j < ( points.length - 1 ); j ++ ) {
  20501. base = j + i * points.length;
  20502. // indices
  20503. var a = base;
  20504. var b = base + points.length;
  20505. var c = base + points.length + 1;
  20506. var d = base + 1;
  20507. // face one
  20508. indices.setX( indexOffset, a ); indexOffset++;
  20509. indices.setX( indexOffset, b ); indexOffset++;
  20510. indices.setX( indexOffset, d ); indexOffset++;
  20511. // face two
  20512. indices.setX( indexOffset, b ); indexOffset++;
  20513. indices.setX( indexOffset, c ); indexOffset++;
  20514. indices.setX( indexOffset, d ); indexOffset++;
  20515. }
  20516. }
  20517. // build geometry
  20518. this.setIndex( indices );
  20519. this.addAttribute( 'position', vertices );
  20520. this.addAttribute( 'uv', uvs );
  20521. // generate normals
  20522. this.computeVertexNormals();
  20523. // if the geometry is closed, we need to average the normals along the seam.
  20524. // because the corresponding vertices are identical (but still have different UVs).
  20525. if( phiLength === Math.PI * 2 ) {
  20526. var normals = this.attributes.normal.array;
  20527. var n1 = new Vector3();
  20528. var n2 = new Vector3();
  20529. var n = new Vector3();
  20530. // this is the buffer offset for the last line of vertices
  20531. base = segments * points.length * 3;
  20532. for( i = 0, j = 0; i < points.length; i ++, j += 3 ) {
  20533. // select the normal of the vertex in the first line
  20534. n1.x = normals[ j + 0 ];
  20535. n1.y = normals[ j + 1 ];
  20536. n1.z = normals[ j + 2 ];
  20537. // select the normal of the vertex in the last line
  20538. n2.x = normals[ base + j + 0 ];
  20539. n2.y = normals[ base + j + 1 ];
  20540. n2.z = normals[ base + j + 2 ];
  20541. // average normals
  20542. n.addVectors( n1, n2 ).normalize();
  20543. // assign the new values to both normals
  20544. normals[ j + 0 ] = normals[ base + j + 0 ] = n.x;
  20545. normals[ j + 1 ] = normals[ base + j + 1 ] = n.y;
  20546. normals[ j + 2 ] = normals[ base + j + 2 ] = n.z;
  20547. } // next row
  20548. }
  20549. }
  20550. LatheBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20551. LatheBufferGeometry.prototype.constructor = LatheBufferGeometry;
  20552. /**
  20553. * @author astrodud / http://astrodud.isgreat.org/
  20554. * @author zz85 / https://github.com/zz85
  20555. * @author bhouston / http://clara.io
  20556. */
  20557. // points - to create a closed torus, one must use a set of points
  20558. // like so: [ a, b, c, d, a ], see first is the same as last.
  20559. // segments - the number of circumference segments to create
  20560. // phiStart - the starting radian
  20561. // phiLength - the radian (0 to 2PI) range of the lathed section
  20562. // 2PI is a closed lathe, less than 2PI is a portion.
  20563. function LatheGeometry( points, segments, phiStart, phiLength ) {
  20564. Geometry.call( this );
  20565. this.type = 'LatheGeometry';
  20566. this.parameters = {
  20567. points: points,
  20568. segments: segments,
  20569. phiStart: phiStart,
  20570. phiLength: phiLength
  20571. };
  20572. this.fromBufferGeometry( new LatheBufferGeometry( points, segments, phiStart, phiLength ) );
  20573. this.mergeVertices();
  20574. }
  20575. LatheGeometry.prototype = Object.create( Geometry.prototype );
  20576. LatheGeometry.prototype.constructor = LatheGeometry;
  20577. /**
  20578. * @author Mugen87 / https://github.com/Mugen87
  20579. *
  20580. * Creates a one-sided polygonal geometry from one or more shapes.
  20581. *
  20582. **/
  20583. function ShapeBufferGeometry( shapes, curveSegments ) {
  20584. BufferGeometry.call( this );
  20585. this.type = 'ShapeBufferGeometry';
  20586. this.parameters = {
  20587. shapes: shapes,
  20588. curveSegments: curveSegments
  20589. };
  20590. curveSegments = curveSegments || 12;
  20591. var vertices = [];
  20592. var normals = [];
  20593. var uvs = [];
  20594. var indices = [];
  20595. var groupStart = 0;
  20596. var groupCount = 0;
  20597. // allow single and array values for "shapes" parameter
  20598. if ( Array.isArray( shapes ) === false ) {
  20599. addShape( shapes );
  20600. } else {
  20601. for ( var i = 0; i < shapes.length; i++ ) {
  20602. addShape( shapes[ i ] );
  20603. this.addGroup( groupStart, groupCount, i ); // enables MultiMaterial support
  20604. groupStart += groupCount;
  20605. groupCount = 0;
  20606. }
  20607. }
  20608. // build geometry
  20609. this.setIndex( new ( indices.length > 65535 ? Uint32BufferAttribute : Uint16BufferAttribute )( indices, 1 ) );
  20610. this.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  20611. this.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
  20612. this.addAttribute( 'uv', new Float32BufferAttribute( uvs, 2 ) );
  20613. // helper functions
  20614. function addShape( shape ) {
  20615. var i, l, shapeHole;
  20616. var indexOffset = vertices.length / 3;
  20617. var points = shape.extractPoints( curveSegments );
  20618. var shapeVertices = points.shape;
  20619. var shapeHoles = points.holes;
  20620. // check direction of vertices
  20621. if ( ShapeUtils.isClockWise( shapeVertices ) === false ) {
  20622. shapeVertices = shapeVertices.reverse();
  20623. // also check if holes are in the opposite direction
  20624. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20625. shapeHole = shapeHoles[ i ];
  20626. if ( ShapeUtils.isClockWise( shapeHole ) === true ) {
  20627. shapeHoles[ i ] = shapeHole.reverse();
  20628. }
  20629. }
  20630. }
  20631. var faces = ShapeUtils.triangulateShape( shapeVertices, shapeHoles );
  20632. // join vertices of inner and outer paths to a single array
  20633. for ( i = 0, l = shapeHoles.length; i < l; i ++ ) {
  20634. shapeHole = shapeHoles[ i ];
  20635. shapeVertices = shapeVertices.concat( shapeHole );
  20636. }
  20637. // vertices, normals, uvs
  20638. for ( i = 0, l = shapeVertices.length; i < l; i ++ ) {
  20639. var vertex = shapeVertices[ i ];
  20640. vertices.push( vertex.x, vertex.y, 0 );
  20641. normals.push( 0, 0, 1 );
  20642. uvs.push( vertex.x, vertex.y ); // world uvs
  20643. }
  20644. // incides
  20645. for ( i = 0, l = faces.length; i < l; i ++ ) {
  20646. var face = faces[ i ];
  20647. var a = face[ 0 ] + indexOffset;
  20648. var b = face[ 1 ] + indexOffset;
  20649. var c = face[ 2 ] + indexOffset;
  20650. indices.push( a, b, c );
  20651. groupCount += 3;
  20652. }
  20653. }
  20654. }
  20655. ShapeBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20656. ShapeBufferGeometry.prototype.constructor = ShapeBufferGeometry;
  20657. /**
  20658. * @author jonobr1 / http://jonobr1.com
  20659. *
  20660. * Creates a one-sided polygonal geometry from a path shape.
  20661. *
  20662. **/
  20663. function ShapeGeometry( shapes, curveSegments ) {
  20664. Geometry.call( this );
  20665. this.type = 'ShapeGeometry';
  20666. if ( typeof curveSegments === 'object' ) {
  20667. console.warn( 'THREE.ShapeGeometry: Options parameter has been removed.' );
  20668. curveSegments = curveSegments.curveSegments;
  20669. }
  20670. this.parameters = {
  20671. shapes: shapes,
  20672. curveSegments: curveSegments
  20673. };
  20674. this.fromBufferGeometry( new ShapeBufferGeometry( shapes, curveSegments ) );
  20675. this.mergeVertices();
  20676. }
  20677. ShapeGeometry.prototype = Object.create( Geometry.prototype );
  20678. ShapeGeometry.prototype.constructor = ShapeGeometry;
  20679. /**
  20680. * @author WestLangley / http://github.com/WestLangley
  20681. */
  20682. function EdgesGeometry( geometry, thresholdAngle ) {
  20683. BufferGeometry.call( this );
  20684. thresholdAngle = ( thresholdAngle !== undefined ) ? thresholdAngle : 1;
  20685. var thresholdDot = Math.cos( _Math.DEG2RAD * thresholdAngle );
  20686. var edge = [ 0, 0 ], hash = {};
  20687. function sortFunction( a, b ) {
  20688. return a - b;
  20689. }
  20690. var keys = [ 'a', 'b', 'c' ];
  20691. var geometry2;
  20692. if ( geometry.isBufferGeometry ) {
  20693. geometry2 = new Geometry();
  20694. geometry2.fromBufferGeometry( geometry );
  20695. } else {
  20696. geometry2 = geometry.clone();
  20697. }
  20698. geometry2.mergeVertices();
  20699. geometry2.computeFaceNormals();
  20700. var vertices = geometry2.vertices;
  20701. var faces = geometry2.faces;
  20702. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20703. var face = faces[ i ];
  20704. for ( var j = 0; j < 3; j ++ ) {
  20705. edge[ 0 ] = face[ keys[ j ] ];
  20706. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  20707. edge.sort( sortFunction );
  20708. var key = edge.toString();
  20709. if ( hash[ key ] === undefined ) {
  20710. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  20711. } else {
  20712. hash[ key ].face2 = i;
  20713. }
  20714. }
  20715. }
  20716. var coords = [];
  20717. for ( var key in hash ) {
  20718. var h = hash[ key ];
  20719. // An edge is only rendered if the angle (in degrees) between the face normals of the adjoining faces exceeds this value. default = 1 degree.
  20720. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) <= thresholdDot ) {
  20721. var vertex = vertices[ h.vert1 ];
  20722. coords.push( vertex.x );
  20723. coords.push( vertex.y );
  20724. coords.push( vertex.z );
  20725. vertex = vertices[ h.vert2 ];
  20726. coords.push( vertex.x );
  20727. coords.push( vertex.y );
  20728. coords.push( vertex.z );
  20729. }
  20730. }
  20731. this.addAttribute( 'position', new Float32BufferAttribute( coords, 3 ) );
  20732. }
  20733. EdgesGeometry.prototype = Object.create( BufferGeometry.prototype );
  20734. EdgesGeometry.prototype.constructor = EdgesGeometry;
  20735. /**
  20736. * @author Mugen87 / https://github.com/Mugen87
  20737. */
  20738. function CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20739. BufferGeometry.call( this );
  20740. this.type = 'CylinderBufferGeometry';
  20741. this.parameters = {
  20742. radiusTop: radiusTop,
  20743. radiusBottom: radiusBottom,
  20744. height: height,
  20745. radialSegments: radialSegments,
  20746. heightSegments: heightSegments,
  20747. openEnded: openEnded,
  20748. thetaStart: thetaStart,
  20749. thetaLength: thetaLength
  20750. };
  20751. var scope = this;
  20752. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  20753. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  20754. height = height !== undefined ? height : 100;
  20755. radialSegments = Math.floor( radialSegments ) || 8;
  20756. heightSegments = Math.floor( heightSegments ) || 1;
  20757. openEnded = openEnded !== undefined ? openEnded : false;
  20758. thetaStart = thetaStart !== undefined ? thetaStart : 0.0;
  20759. thetaLength = thetaLength !== undefined ? thetaLength : 2.0 * Math.PI;
  20760. // used to calculate buffer length
  20761. var nbCap = 0;
  20762. if ( openEnded === false ) {
  20763. if ( radiusTop > 0 ) nbCap ++;
  20764. if ( radiusBottom > 0 ) nbCap ++;
  20765. }
  20766. var vertexCount = calculateVertexCount();
  20767. var indexCount = calculateIndexCount();
  20768. // buffers
  20769. var indices = new BufferAttribute( new ( indexCount > 65535 ? Uint32Array : Uint16Array )( indexCount ), 1 );
  20770. var vertices = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20771. var normals = new BufferAttribute( new Float32Array( vertexCount * 3 ), 3 );
  20772. var uvs = new BufferAttribute( new Float32Array( vertexCount * 2 ), 2 );
  20773. // helper variables
  20774. var index = 0,
  20775. indexOffset = 0,
  20776. indexArray = [],
  20777. halfHeight = height / 2;
  20778. // group variables
  20779. var groupStart = 0;
  20780. // generate geometry
  20781. generateTorso();
  20782. if ( openEnded === false ) {
  20783. if ( radiusTop > 0 ) generateCap( true );
  20784. if ( radiusBottom > 0 ) generateCap( false );
  20785. }
  20786. // build geometry
  20787. this.setIndex( indices );
  20788. this.addAttribute( 'position', vertices );
  20789. this.addAttribute( 'normal', normals );
  20790. this.addAttribute( 'uv', uvs );
  20791. // helper functions
  20792. function calculateVertexCount() {
  20793. var count = ( radialSegments + 1 ) * ( heightSegments + 1 );
  20794. if ( openEnded === false ) {
  20795. count += ( ( radialSegments + 1 ) * nbCap ) + ( radialSegments * nbCap );
  20796. }
  20797. return count;
  20798. }
  20799. function calculateIndexCount() {
  20800. var count = radialSegments * heightSegments * 2 * 3;
  20801. if ( openEnded === false ) {
  20802. count += radialSegments * nbCap * 3;
  20803. }
  20804. return count;
  20805. }
  20806. function generateTorso() {
  20807. var x, y;
  20808. var normal = new Vector3();
  20809. var vertex = new Vector3();
  20810. var groupCount = 0;
  20811. // this will be used to calculate the normal
  20812. var slope = ( radiusBottom - radiusTop ) / height;
  20813. // generate vertices, normals and uvs
  20814. for ( y = 0; y <= heightSegments; y ++ ) {
  20815. var indexRow = [];
  20816. var v = y / heightSegments;
  20817. // calculate the radius of the current row
  20818. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  20819. for ( x = 0; x <= radialSegments; x ++ ) {
  20820. var u = x / radialSegments;
  20821. var theta = u * thetaLength + thetaStart;
  20822. var sinTheta = Math.sin( theta );
  20823. var cosTheta = Math.cos( theta );
  20824. // vertex
  20825. vertex.x = radius * sinTheta;
  20826. vertex.y = - v * height + halfHeight;
  20827. vertex.z = radius * cosTheta;
  20828. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  20829. // normal
  20830. normal.set( sinTheta, slope, cosTheta ).normalize();
  20831. normals.setXYZ( index, normal.x, normal.y, normal.z );
  20832. // uv
  20833. uvs.setXY( index, u, 1 - v );
  20834. // save index of vertex in respective row
  20835. indexRow.push( index );
  20836. // increase index
  20837. index ++;
  20838. }
  20839. // now save vertices of the row in our index array
  20840. indexArray.push( indexRow );
  20841. }
  20842. // generate indices
  20843. for ( x = 0; x < radialSegments; x ++ ) {
  20844. for ( y = 0; y < heightSegments; y ++ ) {
  20845. // we use the index array to access the correct indices
  20846. var i1 = indexArray[ y ][ x ];
  20847. var i2 = indexArray[ y + 1 ][ x ];
  20848. var i3 = indexArray[ y + 1 ][ x + 1 ];
  20849. var i4 = indexArray[ y ][ x + 1 ];
  20850. // face one
  20851. indices.setX( indexOffset, i1 ); indexOffset ++;
  20852. indices.setX( indexOffset, i2 ); indexOffset ++;
  20853. indices.setX( indexOffset, i4 ); indexOffset ++;
  20854. // face two
  20855. indices.setX( indexOffset, i2 ); indexOffset ++;
  20856. indices.setX( indexOffset, i3 ); indexOffset ++;
  20857. indices.setX( indexOffset, i4 ); indexOffset ++;
  20858. // update counters
  20859. groupCount += 6;
  20860. }
  20861. }
  20862. // add a group to the geometry. this will ensure multi material support
  20863. scope.addGroup( groupStart, groupCount, 0 );
  20864. // calculate new start value for groups
  20865. groupStart += groupCount;
  20866. }
  20867. function generateCap( top ) {
  20868. var x, centerIndexStart, centerIndexEnd;
  20869. var uv = new Vector2();
  20870. var vertex = new Vector3();
  20871. var groupCount = 0;
  20872. var radius = ( top === true ) ? radiusTop : radiusBottom;
  20873. var sign = ( top === true ) ? 1 : - 1;
  20874. // save the index of the first center vertex
  20875. centerIndexStart = index;
  20876. // first we generate the center vertex data of the cap.
  20877. // because the geometry needs one set of uvs per face,
  20878. // we must generate a center vertex per face/segment
  20879. for ( x = 1; x <= radialSegments; x ++ ) {
  20880. // vertex
  20881. vertices.setXYZ( index, 0, halfHeight * sign, 0 );
  20882. // normal
  20883. normals.setXYZ( index, 0, sign, 0 );
  20884. // uv
  20885. uv.x = 0.5;
  20886. uv.y = 0.5;
  20887. uvs.setXY( index, uv.x, uv.y );
  20888. // increase index
  20889. index ++;
  20890. }
  20891. // save the index of the last center vertex
  20892. centerIndexEnd = index;
  20893. // now we generate the surrounding vertices, normals and uvs
  20894. for ( x = 0; x <= radialSegments; x ++ ) {
  20895. var u = x / radialSegments;
  20896. var theta = u * thetaLength + thetaStart;
  20897. var cosTheta = Math.cos( theta );
  20898. var sinTheta = Math.sin( theta );
  20899. // vertex
  20900. vertex.x = radius * sinTheta;
  20901. vertex.y = halfHeight * sign;
  20902. vertex.z = radius * cosTheta;
  20903. vertices.setXYZ( index, vertex.x, vertex.y, vertex.z );
  20904. // normal
  20905. normals.setXYZ( index, 0, sign, 0 );
  20906. // uv
  20907. uv.x = ( cosTheta * 0.5 ) + 0.5;
  20908. uv.y = ( sinTheta * 0.5 * sign ) + 0.5;
  20909. uvs.setXY( index, uv.x, uv.y );
  20910. // increase index
  20911. index ++;
  20912. }
  20913. // generate indices
  20914. for ( x = 0; x < radialSegments; x ++ ) {
  20915. var c = centerIndexStart + x;
  20916. var i = centerIndexEnd + x;
  20917. if ( top === true ) {
  20918. // face top
  20919. indices.setX( indexOffset, i ); indexOffset ++;
  20920. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  20921. indices.setX( indexOffset, c ); indexOffset ++;
  20922. } else {
  20923. // face bottom
  20924. indices.setX( indexOffset, i + 1 ); indexOffset ++;
  20925. indices.setX( indexOffset, i ); indexOffset ++;
  20926. indices.setX( indexOffset, c ); indexOffset ++;
  20927. }
  20928. // update counters
  20929. groupCount += 3;
  20930. }
  20931. // add a group to the geometry. this will ensure multi material support
  20932. scope.addGroup( groupStart, groupCount, top === true ? 1 : 2 );
  20933. // calculate new start value for groups
  20934. groupStart += groupCount;
  20935. }
  20936. }
  20937. CylinderBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  20938. CylinderBufferGeometry.prototype.constructor = CylinderBufferGeometry;
  20939. /**
  20940. * @author mrdoob / http://mrdoob.com/
  20941. */
  20942. function CylinderGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20943. Geometry.call( this );
  20944. this.type = 'CylinderGeometry';
  20945. this.parameters = {
  20946. radiusTop: radiusTop,
  20947. radiusBottom: radiusBottom,
  20948. height: height,
  20949. radialSegments: radialSegments,
  20950. heightSegments: heightSegments,
  20951. openEnded: openEnded,
  20952. thetaStart: thetaStart,
  20953. thetaLength: thetaLength
  20954. };
  20955. this.fromBufferGeometry( new CylinderBufferGeometry( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) );
  20956. this.mergeVertices();
  20957. }
  20958. CylinderGeometry.prototype = Object.create( Geometry.prototype );
  20959. CylinderGeometry.prototype.constructor = CylinderGeometry;
  20960. /**
  20961. * @author abelnation / http://github.com/abelnation
  20962. */
  20963. function ConeGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20964. CylinderGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20965. this.type = 'ConeGeometry';
  20966. this.parameters = {
  20967. radius: radius,
  20968. height: height,
  20969. radialSegments: radialSegments,
  20970. heightSegments: heightSegments,
  20971. openEnded: openEnded,
  20972. thetaStart: thetaStart,
  20973. thetaLength: thetaLength
  20974. };
  20975. }
  20976. ConeGeometry.prototype = Object.create( CylinderGeometry.prototype );
  20977. ConeGeometry.prototype.constructor = ConeGeometry;
  20978. /**
  20979. * @author: abelnation / http://github.com/abelnation
  20980. */
  20981. function ConeBufferGeometry( radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength ) {
  20982. CylinderBufferGeometry.call( this, 0, radius, height, radialSegments, heightSegments, openEnded, thetaStart, thetaLength );
  20983. this.type = 'ConeBufferGeometry';
  20984. this.parameters = {
  20985. radius: radius,
  20986. height: height,
  20987. radialSegments: radialSegments,
  20988. heightSegments: heightSegments,
  20989. openEnded: openEnded,
  20990. thetaStart: thetaStart,
  20991. thetaLength: thetaLength
  20992. };
  20993. }
  20994. ConeBufferGeometry.prototype = Object.create( CylinderBufferGeometry.prototype );
  20995. ConeBufferGeometry.prototype.constructor = ConeBufferGeometry;
  20996. /**
  20997. * @author benaadams / https://twitter.com/ben_a_adams
  20998. */
  20999. function CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) {
  21000. BufferGeometry.call( this );
  21001. this.type = 'CircleBufferGeometry';
  21002. this.parameters = {
  21003. radius: radius,
  21004. segments: segments,
  21005. thetaStart: thetaStart,
  21006. thetaLength: thetaLength
  21007. };
  21008. radius = radius || 50;
  21009. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  21010. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  21011. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  21012. var vertices = segments + 2;
  21013. var positions = new Float32Array( vertices * 3 );
  21014. var normals = new Float32Array( vertices * 3 );
  21015. var uvs = new Float32Array( vertices * 2 );
  21016. // center data is already zero, but need to set a few extras
  21017. normals[ 2 ] = 1.0;
  21018. uvs[ 0 ] = 0.5;
  21019. uvs[ 1 ] = 0.5;
  21020. for ( var s = 0, i = 3, ii = 2 ; s <= segments; s ++, i += 3, ii += 2 ) {
  21021. var segment = thetaStart + s / segments * thetaLength;
  21022. positions[ i ] = radius * Math.cos( segment );
  21023. positions[ i + 1 ] = radius * Math.sin( segment );
  21024. normals[ i + 2 ] = 1; // normal z
  21025. uvs[ ii ] = ( positions[ i ] / radius + 1 ) / 2;
  21026. uvs[ ii + 1 ] = ( positions[ i + 1 ] / radius + 1 ) / 2;
  21027. }
  21028. var indices = [];
  21029. for ( var i = 1; i <= segments; i ++ ) {
  21030. indices.push( i, i + 1, 0 );
  21031. }
  21032. this.setIndex( new BufferAttribute( new Uint16Array( indices ), 1 ) );
  21033. this.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  21034. this.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
  21035. this.addAttribute( 'uv', new BufferAttribute( uvs, 2 ) );
  21036. this.boundingSphere = new Sphere( new Vector3(), radius );
  21037. }
  21038. CircleBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  21039. CircleBufferGeometry.prototype.constructor = CircleBufferGeometry;
  21040. /**
  21041. * @author hughes
  21042. */
  21043. function CircleGeometry( radius, segments, thetaStart, thetaLength ) {
  21044. Geometry.call( this );
  21045. this.type = 'CircleGeometry';
  21046. this.parameters = {
  21047. radius: radius,
  21048. segments: segments,
  21049. thetaStart: thetaStart,
  21050. thetaLength: thetaLength
  21051. };
  21052. this.fromBufferGeometry( new CircleBufferGeometry( radius, segments, thetaStart, thetaLength ) );
  21053. }
  21054. CircleGeometry.prototype = Object.create( Geometry.prototype );
  21055. CircleGeometry.prototype.constructor = CircleGeometry;
  21056. /**
  21057. * @author mrdoob / http://mrdoob.com/
  21058. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  21059. */
  21060. function BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  21061. Geometry.call( this );
  21062. this.type = 'BoxGeometry';
  21063. this.parameters = {
  21064. width: width,
  21065. height: height,
  21066. depth: depth,
  21067. widthSegments: widthSegments,
  21068. heightSegments: heightSegments,
  21069. depthSegments: depthSegments
  21070. };
  21071. this.fromBufferGeometry( new BoxBufferGeometry( width, height, depth, widthSegments, heightSegments, depthSegments ) );
  21072. this.mergeVertices();
  21073. }
  21074. BoxGeometry.prototype = Object.create( Geometry.prototype );
  21075. BoxGeometry.prototype.constructor = BoxGeometry;
  21076. var Geometries = Object.freeze({
  21077. WireframeGeometry: WireframeGeometry,
  21078. ParametricGeometry: ParametricGeometry,
  21079. ParametricBufferGeometry: ParametricBufferGeometry,
  21080. TetrahedronGeometry: TetrahedronGeometry,
  21081. TetrahedronBufferGeometry: TetrahedronBufferGeometry,
  21082. OctahedronGeometry: OctahedronGeometry,
  21083. OctahedronBufferGeometry: OctahedronBufferGeometry,
  21084. IcosahedronGeometry: IcosahedronGeometry,
  21085. IcosahedronBufferGeometry: IcosahedronBufferGeometry,
  21086. DodecahedronGeometry: DodecahedronGeometry,
  21087. DodecahedronBufferGeometry: DodecahedronBufferGeometry,
  21088. PolyhedronGeometry: PolyhedronGeometry,
  21089. PolyhedronBufferGeometry: PolyhedronBufferGeometry,
  21090. TubeGeometry: TubeGeometry,
  21091. TubeBufferGeometry: TubeBufferGeometry,
  21092. TorusKnotGeometry: TorusKnotGeometry,
  21093. TorusKnotBufferGeometry: TorusKnotBufferGeometry,
  21094. TorusGeometry: TorusGeometry,
  21095. TorusBufferGeometry: TorusBufferGeometry,
  21096. TextGeometry: TextGeometry,
  21097. SphereBufferGeometry: SphereBufferGeometry,
  21098. SphereGeometry: SphereGeometry,
  21099. RingGeometry: RingGeometry,
  21100. RingBufferGeometry: RingBufferGeometry,
  21101. PlaneBufferGeometry: PlaneBufferGeometry,
  21102. PlaneGeometry: PlaneGeometry,
  21103. LatheGeometry: LatheGeometry,
  21104. LatheBufferGeometry: LatheBufferGeometry,
  21105. ShapeGeometry: ShapeGeometry,
  21106. ShapeBufferGeometry: ShapeBufferGeometry,
  21107. ExtrudeGeometry: ExtrudeGeometry,
  21108. EdgesGeometry: EdgesGeometry,
  21109. ConeGeometry: ConeGeometry,
  21110. ConeBufferGeometry: ConeBufferGeometry,
  21111. CylinderGeometry: CylinderGeometry,
  21112. CylinderBufferGeometry: CylinderBufferGeometry,
  21113. CircleBufferGeometry: CircleBufferGeometry,
  21114. CircleGeometry: CircleGeometry,
  21115. BoxBufferGeometry: BoxBufferGeometry,
  21116. BoxGeometry: BoxGeometry
  21117. });
  21118. /**
  21119. * @author mrdoob / http://mrdoob.com/
  21120. */
  21121. function ShadowMaterial() {
  21122. ShaderMaterial.call( this, {
  21123. uniforms: UniformsUtils.merge( [
  21124. UniformsLib.lights,
  21125. {
  21126. opacity: { value: 1.0 }
  21127. }
  21128. ] ),
  21129. vertexShader: ShaderChunk[ 'shadow_vert' ],
  21130. fragmentShader: ShaderChunk[ 'shadow_frag' ]
  21131. } );
  21132. this.lights = true;
  21133. this.transparent = true;
  21134. Object.defineProperties( this, {
  21135. opacity: {
  21136. enumerable: true,
  21137. get: function () {
  21138. return this.uniforms.opacity.value;
  21139. },
  21140. set: function ( value ) {
  21141. this.uniforms.opacity.value = value;
  21142. }
  21143. }
  21144. } );
  21145. }
  21146. ShadowMaterial.prototype = Object.create( ShaderMaterial.prototype );
  21147. ShadowMaterial.prototype.constructor = ShadowMaterial;
  21148. ShadowMaterial.prototype.isShadowMaterial = true;
  21149. /**
  21150. * @author mrdoob / http://mrdoob.com/
  21151. */
  21152. function RawShaderMaterial( parameters ) {
  21153. ShaderMaterial.call( this, parameters );
  21154. this.type = 'RawShaderMaterial';
  21155. }
  21156. RawShaderMaterial.prototype = Object.create( ShaderMaterial.prototype );
  21157. RawShaderMaterial.prototype.constructor = RawShaderMaterial;
  21158. RawShaderMaterial.prototype.isRawShaderMaterial = true;
  21159. /**
  21160. * @author mrdoob / http://mrdoob.com/
  21161. */
  21162. function MultiMaterial( materials ) {
  21163. this.uuid = _Math.generateUUID();
  21164. this.type = 'MultiMaterial';
  21165. this.materials = Array.isArray( materials ) ? materials : [];
  21166. this.visible = true;
  21167. }
  21168. MultiMaterial.prototype = {
  21169. constructor: MultiMaterial,
  21170. isMultiMaterial: true,
  21171. toJSON: function ( meta ) {
  21172. var output = {
  21173. metadata: {
  21174. version: 4.2,
  21175. type: 'material',
  21176. generator: 'MaterialExporter'
  21177. },
  21178. uuid: this.uuid,
  21179. type: this.type,
  21180. materials: []
  21181. };
  21182. var materials = this.materials;
  21183. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  21184. var material = materials[ i ].toJSON( meta );
  21185. delete material.metadata;
  21186. output.materials.push( material );
  21187. }
  21188. output.visible = this.visible;
  21189. return output;
  21190. },
  21191. clone: function () {
  21192. var material = new this.constructor();
  21193. for ( var i = 0; i < this.materials.length; i ++ ) {
  21194. material.materials.push( this.materials[ i ].clone() );
  21195. }
  21196. material.visible = this.visible;
  21197. return material;
  21198. }
  21199. };
  21200. /**
  21201. * @author WestLangley / http://github.com/WestLangley
  21202. *
  21203. * parameters = {
  21204. * color: <hex>,
  21205. * roughness: <float>,
  21206. * metalness: <float>,
  21207. * opacity: <float>,
  21208. *
  21209. * map: new THREE.Texture( <Image> ),
  21210. *
  21211. * lightMap: new THREE.Texture( <Image> ),
  21212. * lightMapIntensity: <float>
  21213. *
  21214. * aoMap: new THREE.Texture( <Image> ),
  21215. * aoMapIntensity: <float>
  21216. *
  21217. * emissive: <hex>,
  21218. * emissiveIntensity: <float>
  21219. * emissiveMap: new THREE.Texture( <Image> ),
  21220. *
  21221. * bumpMap: new THREE.Texture( <Image> ),
  21222. * bumpScale: <float>,
  21223. *
  21224. * normalMap: new THREE.Texture( <Image> ),
  21225. * normalScale: <Vector2>,
  21226. *
  21227. * displacementMap: new THREE.Texture( <Image> ),
  21228. * displacementScale: <float>,
  21229. * displacementBias: <float>,
  21230. *
  21231. * roughnessMap: new THREE.Texture( <Image> ),
  21232. *
  21233. * metalnessMap: new THREE.Texture( <Image> ),
  21234. *
  21235. * alphaMap: new THREE.Texture( <Image> ),
  21236. *
  21237. * envMap: new THREE.CubeTexture( [posx, negx, posy, negy, posz, negz] ),
  21238. * envMapIntensity: <float>
  21239. *
  21240. * refractionRatio: <float>,
  21241. *
  21242. * wireframe: <boolean>,
  21243. * wireframeLinewidth: <float>,
  21244. *
  21245. * skinning: <bool>,
  21246. * morphTargets: <bool>,
  21247. * morphNormals: <bool>
  21248. * }
  21249. */
  21250. function MeshStandardMaterial( parameters ) {
  21251. Material.call( this );
  21252. this.defines = { 'STANDARD': '' };
  21253. this.type = 'MeshStandardMaterial';
  21254. this.color = new Color( 0xffffff ); // diffuse
  21255. this.roughness = 0.5;
  21256. this.metalness = 0.5;
  21257. this.map = null;
  21258. this.lightMap = null;
  21259. this.lightMapIntensity = 1.0;
  21260. this.aoMap = null;
  21261. this.aoMapIntensity = 1.0;
  21262. this.emissive = new Color( 0x000000 );
  21263. this.emissiveIntensity = 1.0;
  21264. this.emissiveMap = null;
  21265. this.bumpMap = null;
  21266. this.bumpScale = 1;
  21267. this.normalMap = null;
  21268. this.normalScale = new Vector2( 1, 1 );
  21269. this.displacementMap = null;
  21270. this.displacementScale = 1;
  21271. this.displacementBias = 0;
  21272. this.roughnessMap = null;
  21273. this.metalnessMap = null;
  21274. this.alphaMap = null;
  21275. this.envMap = null;
  21276. this.envMapIntensity = 1.0;
  21277. this.refractionRatio = 0.98;
  21278. this.wireframe = false;
  21279. this.wireframeLinewidth = 1;
  21280. this.wireframeLinecap = 'round';
  21281. this.wireframeLinejoin = 'round';
  21282. this.skinning = false;
  21283. this.morphTargets = false;
  21284. this.morphNormals = false;
  21285. this.setValues( parameters );
  21286. }
  21287. MeshStandardMaterial.prototype = Object.create( Material.prototype );
  21288. MeshStandardMaterial.prototype.constructor = MeshStandardMaterial;
  21289. MeshStandardMaterial.prototype.isMeshStandardMaterial = true;
  21290. MeshStandardMaterial.prototype.copy = function ( source ) {
  21291. Material.prototype.copy.call( this, source );
  21292. this.defines = { 'STANDARD': '' };
  21293. this.color.copy( source.color );
  21294. this.roughness = source.roughness;
  21295. this.metalness = source.metalness;
  21296. this.map = source.map;
  21297. this.lightMap = source.lightMap;
  21298. this.lightMapIntensity = source.lightMapIntensity;
  21299. this.aoMap = source.aoMap;
  21300. this.aoMapIntensity = source.aoMapIntensity;
  21301. this.emissive.copy( source.emissive );
  21302. this.emissiveMap = source.emissiveMap;
  21303. this.emissiveIntensity = source.emissiveIntensity;
  21304. this.bumpMap = source.bumpMap;
  21305. this.bumpScale = source.bumpScale;
  21306. this.normalMap = source.normalMap;
  21307. this.normalScale.copy( source.normalScale );
  21308. this.displacementMap = source.displacementMap;
  21309. this.displacementScale = source.displacementScale;
  21310. this.displacementBias = source.displacementBias;
  21311. this.roughnessMap = source.roughnessMap;
  21312. this.metalnessMap = source.metalnessMap;
  21313. this.alphaMap = source.alphaMap;
  21314. this.envMap = source.envMap;
  21315. this.envMapIntensity = source.envMapIntensity;
  21316. this.refractionRatio = source.refractionRatio;
  21317. this.wireframe = source.wireframe;
  21318. this.wireframeLinewidth = source.wireframeLinewidth;
  21319. this.wireframeLinecap = source.wireframeLinecap;
  21320. this.wireframeLinejoin = source.wireframeLinejoin;
  21321. this.skinning = source.skinning;
  21322. this.morphTargets = source.morphTargets;
  21323. this.morphNormals = source.morphNormals;
  21324. return this;
  21325. };
  21326. /**
  21327. * @author WestLangley / http://github.com/WestLangley
  21328. *
  21329. * parameters = {
  21330. * reflectivity: <float>
  21331. * }
  21332. */
  21333. function MeshPhysicalMaterial( parameters ) {
  21334. MeshStandardMaterial.call( this );
  21335. this.defines = { 'PHYSICAL': '' };
  21336. this.type = 'MeshPhysicalMaterial';
  21337. this.reflectivity = 0.5; // maps to F0 = 0.04
  21338. this.clearCoat = 0.0;
  21339. this.clearCoatRoughness = 0.0;
  21340. this.setValues( parameters );
  21341. }
  21342. MeshPhysicalMaterial.prototype = Object.create( MeshStandardMaterial.prototype );
  21343. MeshPhysicalMaterial.prototype.constructor = MeshPhysicalMaterial;
  21344. MeshPhysicalMaterial.prototype.isMeshPhysicalMaterial = true;
  21345. MeshPhysicalMaterial.prototype.copy = function ( source ) {
  21346. MeshStandardMaterial.prototype.copy.call( this, source );
  21347. this.defines = { 'PHYSICAL': '' };
  21348. this.reflectivity = source.reflectivity;
  21349. this.clearCoat = source.clearCoat;
  21350. this.clearCoatRoughness = source.clearCoatRoughness;
  21351. return this;
  21352. };
  21353. /**
  21354. * @author mrdoob / http://mrdoob.com/
  21355. * @author alteredq / http://alteredqualia.com/
  21356. *
  21357. * parameters = {
  21358. * color: <hex>,
  21359. * specular: <hex>,
  21360. * shininess: <float>,
  21361. * opacity: <float>,
  21362. *
  21363. * map: new THREE.Texture( <Image> ),
  21364. *
  21365. * lightMap: new THREE.Texture( <Image> ),
  21366. * lightMapIntensity: <float>
  21367. *
  21368. * aoMap: new THREE.Texture( <Image> ),
  21369. * aoMapIntensity: <float>
  21370. *
  21371. * emissive: <hex>,
  21372. * emissiveIntensity: <float>
  21373. * emissiveMap: new THREE.Texture( <Image> ),
  21374. *
  21375. * bumpMap: new THREE.Texture( <Image> ),
  21376. * bumpScale: <float>,
  21377. *
  21378. * normalMap: new THREE.Texture( <Image> ),
  21379. * normalScale: <Vector2>,
  21380. *
  21381. * displacementMap: new THREE.Texture( <Image> ),
  21382. * displacementScale: <float>,
  21383. * displacementBias: <float>,
  21384. *
  21385. * specularMap: new THREE.Texture( <Image> ),
  21386. *
  21387. * alphaMap: new THREE.Texture( <Image> ),
  21388. *
  21389. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21390. * combine: THREE.Multiply,
  21391. * reflectivity: <float>,
  21392. * refractionRatio: <float>,
  21393. *
  21394. * wireframe: <boolean>,
  21395. * wireframeLinewidth: <float>,
  21396. *
  21397. * skinning: <bool>,
  21398. * morphTargets: <bool>,
  21399. * morphNormals: <bool>
  21400. * }
  21401. */
  21402. function MeshPhongMaterial( parameters ) {
  21403. Material.call( this );
  21404. this.type = 'MeshPhongMaterial';
  21405. this.color = new Color( 0xffffff ); // diffuse
  21406. this.specular = new Color( 0x111111 );
  21407. this.shininess = 30;
  21408. this.map = null;
  21409. this.lightMap = null;
  21410. this.lightMapIntensity = 1.0;
  21411. this.aoMap = null;
  21412. this.aoMapIntensity = 1.0;
  21413. this.emissive = new Color( 0x000000 );
  21414. this.emissiveIntensity = 1.0;
  21415. this.emissiveMap = null;
  21416. this.bumpMap = null;
  21417. this.bumpScale = 1;
  21418. this.normalMap = null;
  21419. this.normalScale = new Vector2( 1, 1 );
  21420. this.displacementMap = null;
  21421. this.displacementScale = 1;
  21422. this.displacementBias = 0;
  21423. this.specularMap = null;
  21424. this.alphaMap = null;
  21425. this.envMap = null;
  21426. this.combine = MultiplyOperation;
  21427. this.reflectivity = 1;
  21428. this.refractionRatio = 0.98;
  21429. this.wireframe = false;
  21430. this.wireframeLinewidth = 1;
  21431. this.wireframeLinecap = 'round';
  21432. this.wireframeLinejoin = 'round';
  21433. this.skinning = false;
  21434. this.morphTargets = false;
  21435. this.morphNormals = false;
  21436. this.setValues( parameters );
  21437. }
  21438. MeshPhongMaterial.prototype = Object.create( Material.prototype );
  21439. MeshPhongMaterial.prototype.constructor = MeshPhongMaterial;
  21440. MeshPhongMaterial.prototype.isMeshPhongMaterial = true;
  21441. MeshPhongMaterial.prototype.copy = function ( source ) {
  21442. Material.prototype.copy.call( this, source );
  21443. this.color.copy( source.color );
  21444. this.specular.copy( source.specular );
  21445. this.shininess = source.shininess;
  21446. this.map = source.map;
  21447. this.lightMap = source.lightMap;
  21448. this.lightMapIntensity = source.lightMapIntensity;
  21449. this.aoMap = source.aoMap;
  21450. this.aoMapIntensity = source.aoMapIntensity;
  21451. this.emissive.copy( source.emissive );
  21452. this.emissiveMap = source.emissiveMap;
  21453. this.emissiveIntensity = source.emissiveIntensity;
  21454. this.bumpMap = source.bumpMap;
  21455. this.bumpScale = source.bumpScale;
  21456. this.normalMap = source.normalMap;
  21457. this.normalScale.copy( source.normalScale );
  21458. this.displacementMap = source.displacementMap;
  21459. this.displacementScale = source.displacementScale;
  21460. this.displacementBias = source.displacementBias;
  21461. this.specularMap = source.specularMap;
  21462. this.alphaMap = source.alphaMap;
  21463. this.envMap = source.envMap;
  21464. this.combine = source.combine;
  21465. this.reflectivity = source.reflectivity;
  21466. this.refractionRatio = source.refractionRatio;
  21467. this.wireframe = source.wireframe;
  21468. this.wireframeLinewidth = source.wireframeLinewidth;
  21469. this.wireframeLinecap = source.wireframeLinecap;
  21470. this.wireframeLinejoin = source.wireframeLinejoin;
  21471. this.skinning = source.skinning;
  21472. this.morphTargets = source.morphTargets;
  21473. this.morphNormals = source.morphNormals;
  21474. return this;
  21475. };
  21476. /**
  21477. * @author takahirox / http://github.com/takahirox
  21478. *
  21479. * parameters = {
  21480. * gradientMap: new THREE.Texture( <Image> )
  21481. * }
  21482. */
  21483. function MeshToonMaterial( parameters ) {
  21484. MeshPhongMaterial.call( this );
  21485. this.defines = { 'TOON': '' };
  21486. this.type = 'MeshToonMaterial';
  21487. this.gradientMap = null;
  21488. this.setValues( parameters );
  21489. }
  21490. MeshToonMaterial.prototype = Object.create( MeshPhongMaterial.prototype );
  21491. MeshToonMaterial.prototype.constructor = MeshToonMaterial;
  21492. MeshToonMaterial.prototype.isMeshToonMaterial = true;
  21493. MeshToonMaterial.prototype.copy = function ( source ) {
  21494. MeshPhongMaterial.prototype.copy.call( this, source );
  21495. this.gradientMap = source.gradientMap;
  21496. return this;
  21497. };
  21498. /**
  21499. * @author mrdoob / http://mrdoob.com/
  21500. * @author WestLangley / http://github.com/WestLangley
  21501. *
  21502. * parameters = {
  21503. * opacity: <float>,
  21504. *
  21505. * bumpMap: new THREE.Texture( <Image> ),
  21506. * bumpScale: <float>,
  21507. *
  21508. * normalMap: new THREE.Texture( <Image> ),
  21509. * normalScale: <Vector2>,
  21510. *
  21511. * displacementMap: new THREE.Texture( <Image> ),
  21512. * displacementScale: <float>,
  21513. * displacementBias: <float>,
  21514. *
  21515. * wireframe: <boolean>,
  21516. * wireframeLinewidth: <float>
  21517. *
  21518. * skinning: <bool>,
  21519. * morphTargets: <bool>,
  21520. * morphNormals: <bool>
  21521. * }
  21522. */
  21523. function MeshNormalMaterial( parameters ) {
  21524. Material.call( this, parameters );
  21525. this.type = 'MeshNormalMaterial';
  21526. this.bumpMap = null;
  21527. this.bumpScale = 1;
  21528. this.normalMap = null;
  21529. this.normalScale = new Vector2( 1, 1 );
  21530. this.displacementMap = null;
  21531. this.displacementScale = 1;
  21532. this.displacementBias = 0;
  21533. this.wireframe = false;
  21534. this.wireframeLinewidth = 1;
  21535. this.fog = false;
  21536. this.lights = false;
  21537. this.skinning = false;
  21538. this.morphTargets = false;
  21539. this.morphNormals = false;
  21540. this.setValues( parameters );
  21541. }
  21542. MeshNormalMaterial.prototype = Object.create( Material.prototype );
  21543. MeshNormalMaterial.prototype.constructor = MeshNormalMaterial;
  21544. MeshNormalMaterial.prototype.isMeshNormalMaterial = true;
  21545. MeshNormalMaterial.prototype.copy = function ( source ) {
  21546. Material.prototype.copy.call( this, source );
  21547. this.bumpMap = source.bumpMap;
  21548. this.bumpScale = source.bumpScale;
  21549. this.normalMap = source.normalMap;
  21550. this.normalScale.copy( source.normalScale );
  21551. this.displacementMap = source.displacementMap;
  21552. this.displacementScale = source.displacementScale;
  21553. this.displacementBias = source.displacementBias;
  21554. this.wireframe = source.wireframe;
  21555. this.wireframeLinewidth = source.wireframeLinewidth;
  21556. this.skinning = source.skinning;
  21557. this.morphTargets = source.morphTargets;
  21558. this.morphNormals = source.morphNormals;
  21559. return this;
  21560. };
  21561. /**
  21562. * @author mrdoob / http://mrdoob.com/
  21563. * @author alteredq / http://alteredqualia.com/
  21564. *
  21565. * parameters = {
  21566. * color: <hex>,
  21567. * opacity: <float>,
  21568. *
  21569. * map: new THREE.Texture( <Image> ),
  21570. *
  21571. * lightMap: new THREE.Texture( <Image> ),
  21572. * lightMapIntensity: <float>
  21573. *
  21574. * aoMap: new THREE.Texture( <Image> ),
  21575. * aoMapIntensity: <float>
  21576. *
  21577. * emissive: <hex>,
  21578. * emissiveIntensity: <float>
  21579. * emissiveMap: new THREE.Texture( <Image> ),
  21580. *
  21581. * specularMap: new THREE.Texture( <Image> ),
  21582. *
  21583. * alphaMap: new THREE.Texture( <Image> ),
  21584. *
  21585. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  21586. * combine: THREE.Multiply,
  21587. * reflectivity: <float>,
  21588. * refractionRatio: <float>,
  21589. *
  21590. * wireframe: <boolean>,
  21591. * wireframeLinewidth: <float>,
  21592. *
  21593. * skinning: <bool>,
  21594. * morphTargets: <bool>,
  21595. * morphNormals: <bool>
  21596. * }
  21597. */
  21598. function MeshLambertMaterial( parameters ) {
  21599. Material.call( this );
  21600. this.type = 'MeshLambertMaterial';
  21601. this.color = new Color( 0xffffff ); // diffuse
  21602. this.map = null;
  21603. this.lightMap = null;
  21604. this.lightMapIntensity = 1.0;
  21605. this.aoMap = null;
  21606. this.aoMapIntensity = 1.0;
  21607. this.emissive = new Color( 0x000000 );
  21608. this.emissiveIntensity = 1.0;
  21609. this.emissiveMap = null;
  21610. this.specularMap = null;
  21611. this.alphaMap = null;
  21612. this.envMap = null;
  21613. this.combine = MultiplyOperation;
  21614. this.reflectivity = 1;
  21615. this.refractionRatio = 0.98;
  21616. this.wireframe = false;
  21617. this.wireframeLinewidth = 1;
  21618. this.wireframeLinecap = 'round';
  21619. this.wireframeLinejoin = 'round';
  21620. this.skinning = false;
  21621. this.morphTargets = false;
  21622. this.morphNormals = false;
  21623. this.setValues( parameters );
  21624. }
  21625. MeshLambertMaterial.prototype = Object.create( Material.prototype );
  21626. MeshLambertMaterial.prototype.constructor = MeshLambertMaterial;
  21627. MeshLambertMaterial.prototype.isMeshLambertMaterial = true;
  21628. MeshLambertMaterial.prototype.copy = function ( source ) {
  21629. Material.prototype.copy.call( this, source );
  21630. this.color.copy( source.color );
  21631. this.map = source.map;
  21632. this.lightMap = source.lightMap;
  21633. this.lightMapIntensity = source.lightMapIntensity;
  21634. this.aoMap = source.aoMap;
  21635. this.aoMapIntensity = source.aoMapIntensity;
  21636. this.emissive.copy( source.emissive );
  21637. this.emissiveMap = source.emissiveMap;
  21638. this.emissiveIntensity = source.emissiveIntensity;
  21639. this.specularMap = source.specularMap;
  21640. this.alphaMap = source.alphaMap;
  21641. this.envMap = source.envMap;
  21642. this.combine = source.combine;
  21643. this.reflectivity = source.reflectivity;
  21644. this.refractionRatio = source.refractionRatio;
  21645. this.wireframe = source.wireframe;
  21646. this.wireframeLinewidth = source.wireframeLinewidth;
  21647. this.wireframeLinecap = source.wireframeLinecap;
  21648. this.wireframeLinejoin = source.wireframeLinejoin;
  21649. this.skinning = source.skinning;
  21650. this.morphTargets = source.morphTargets;
  21651. this.morphNormals = source.morphNormals;
  21652. return this;
  21653. };
  21654. /**
  21655. * @author alteredq / http://alteredqualia.com/
  21656. *
  21657. * parameters = {
  21658. * color: <hex>,
  21659. * opacity: <float>,
  21660. *
  21661. * linewidth: <float>,
  21662. *
  21663. * scale: <float>,
  21664. * dashSize: <float>,
  21665. * gapSize: <float>
  21666. * }
  21667. */
  21668. function LineDashedMaterial( parameters ) {
  21669. Material.call( this );
  21670. this.type = 'LineDashedMaterial';
  21671. this.color = new Color( 0xffffff );
  21672. this.linewidth = 1;
  21673. this.scale = 1;
  21674. this.dashSize = 3;
  21675. this.gapSize = 1;
  21676. this.lights = false;
  21677. this.setValues( parameters );
  21678. }
  21679. LineDashedMaterial.prototype = Object.create( Material.prototype );
  21680. LineDashedMaterial.prototype.constructor = LineDashedMaterial;
  21681. LineDashedMaterial.prototype.isLineDashedMaterial = true;
  21682. LineDashedMaterial.prototype.copy = function ( source ) {
  21683. Material.prototype.copy.call( this, source );
  21684. this.color.copy( source.color );
  21685. this.linewidth = source.linewidth;
  21686. this.scale = source.scale;
  21687. this.dashSize = source.dashSize;
  21688. this.gapSize = source.gapSize;
  21689. return this;
  21690. };
  21691. var Materials = Object.freeze({
  21692. ShadowMaterial: ShadowMaterial,
  21693. SpriteMaterial: SpriteMaterial,
  21694. RawShaderMaterial: RawShaderMaterial,
  21695. ShaderMaterial: ShaderMaterial,
  21696. PointsMaterial: PointsMaterial,
  21697. MultiMaterial: MultiMaterial,
  21698. MeshPhysicalMaterial: MeshPhysicalMaterial,
  21699. MeshStandardMaterial: MeshStandardMaterial,
  21700. MeshPhongMaterial: MeshPhongMaterial,
  21701. MeshToonMaterial: MeshToonMaterial,
  21702. MeshNormalMaterial: MeshNormalMaterial,
  21703. MeshLambertMaterial: MeshLambertMaterial,
  21704. MeshDepthMaterial: MeshDepthMaterial,
  21705. MeshBasicMaterial: MeshBasicMaterial,
  21706. LineDashedMaterial: LineDashedMaterial,
  21707. LineBasicMaterial: LineBasicMaterial,
  21708. Material: Material
  21709. });
  21710. /**
  21711. * @author mrdoob / http://mrdoob.com/
  21712. */
  21713. var Cache = {
  21714. enabled: false,
  21715. files: {},
  21716. add: function ( key, file ) {
  21717. if ( this.enabled === false ) return;
  21718. // console.log( 'THREE.Cache', 'Adding key:', key );
  21719. this.files[ key ] = file;
  21720. },
  21721. get: function ( key ) {
  21722. if ( this.enabled === false ) return;
  21723. // console.log( 'THREE.Cache', 'Checking key:', key );
  21724. return this.files[ key ];
  21725. },
  21726. remove: function ( key ) {
  21727. delete this.files[ key ];
  21728. },
  21729. clear: function () {
  21730. this.files = {};
  21731. }
  21732. };
  21733. /**
  21734. * @author mrdoob / http://mrdoob.com/
  21735. */
  21736. function LoadingManager( onLoad, onProgress, onError ) {
  21737. var scope = this;
  21738. var isLoading = false, itemsLoaded = 0, itemsTotal = 0;
  21739. this.onStart = undefined;
  21740. this.onLoad = onLoad;
  21741. this.onProgress = onProgress;
  21742. this.onError = onError;
  21743. this.itemStart = function ( url ) {
  21744. itemsTotal ++;
  21745. if ( isLoading === false ) {
  21746. if ( scope.onStart !== undefined ) {
  21747. scope.onStart( url, itemsLoaded, itemsTotal );
  21748. }
  21749. }
  21750. isLoading = true;
  21751. };
  21752. this.itemEnd = function ( url ) {
  21753. itemsLoaded ++;
  21754. if ( scope.onProgress !== undefined ) {
  21755. scope.onProgress( url, itemsLoaded, itemsTotal );
  21756. }
  21757. if ( itemsLoaded === itemsTotal ) {
  21758. isLoading = false;
  21759. if ( scope.onLoad !== undefined ) {
  21760. scope.onLoad();
  21761. }
  21762. }
  21763. };
  21764. this.itemError = function ( url ) {
  21765. if ( scope.onError !== undefined ) {
  21766. scope.onError( url );
  21767. }
  21768. };
  21769. }
  21770. var DefaultLoadingManager = new LoadingManager();
  21771. /**
  21772. * @author mrdoob / http://mrdoob.com/
  21773. */
  21774. function FileLoader( manager ) {
  21775. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21776. }
  21777. Object.assign( FileLoader.prototype, {
  21778. load: function ( url, onLoad, onProgress, onError ) {
  21779. if ( url === undefined ) url = '';
  21780. if ( this.path !== undefined ) url = this.path + url;
  21781. var scope = this;
  21782. var cached = Cache.get( url );
  21783. if ( cached !== undefined ) {
  21784. scope.manager.itemStart( url );
  21785. setTimeout( function () {
  21786. if ( onLoad ) onLoad( cached );
  21787. scope.manager.itemEnd( url );
  21788. }, 0 );
  21789. return cached;
  21790. }
  21791. // Check for data: URI
  21792. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  21793. var dataUriRegexResult = url.match( dataUriRegex );
  21794. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  21795. if ( dataUriRegexResult ) {
  21796. var mimeType = dataUriRegexResult[ 1 ];
  21797. var isBase64 = !! dataUriRegexResult[ 2 ];
  21798. var data = dataUriRegexResult[ 3 ];
  21799. data = window.decodeURIComponent( data );
  21800. if ( isBase64 ) data = window.atob( data );
  21801. try {
  21802. var response;
  21803. var responseType = ( this.responseType || '' ).toLowerCase();
  21804. switch ( responseType ) {
  21805. case 'arraybuffer':
  21806. case 'blob':
  21807. response = new ArrayBuffer( data.length );
  21808. var view = new Uint8Array( response );
  21809. for ( var i = 0; i < data.length; i ++ ) {
  21810. view[ i ] = data.charCodeAt( i );
  21811. }
  21812. if ( responseType === 'blob' ) {
  21813. response = new Blob( [ response ], { type: mimeType } );
  21814. }
  21815. break;
  21816. case 'document':
  21817. var parser = new DOMParser();
  21818. response = parser.parseFromString( data, mimeType );
  21819. break;
  21820. case 'json':
  21821. response = JSON.parse( data );
  21822. break;
  21823. default: // 'text' or other
  21824. response = data;
  21825. break;
  21826. }
  21827. // Wait for next browser tick
  21828. window.setTimeout( function () {
  21829. if ( onLoad ) onLoad( response );
  21830. scope.manager.itemEnd( url );
  21831. }, 0 );
  21832. } catch ( error ) {
  21833. // Wait for next browser tick
  21834. window.setTimeout( function () {
  21835. if ( onError ) onError( error );
  21836. scope.manager.itemError( url );
  21837. }, 0 );
  21838. }
  21839. } else {
  21840. var request = new XMLHttpRequest();
  21841. request.open( 'GET', url, true );
  21842. request.addEventListener( 'load', function ( event ) {
  21843. var response = event.target.response;
  21844. Cache.add( url, response );
  21845. if ( this.status === 200 ) {
  21846. if ( onLoad ) onLoad( response );
  21847. scope.manager.itemEnd( url );
  21848. } else if ( this.status === 0 ) {
  21849. // Some browsers return HTTP Status 0 when using non-http protocol
  21850. // e.g. 'file://' or 'data://'. Handle as success.
  21851. console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  21852. if ( onLoad ) onLoad( response );
  21853. scope.manager.itemEnd( url );
  21854. } else {
  21855. if ( onError ) onError( event );
  21856. scope.manager.itemError( url );
  21857. }
  21858. }, false );
  21859. if ( onProgress !== undefined ) {
  21860. request.addEventListener( 'progress', function ( event ) {
  21861. onProgress( event );
  21862. }, false );
  21863. }
  21864. request.addEventListener( 'error', function ( event ) {
  21865. if ( onError ) onError( event );
  21866. scope.manager.itemError( url );
  21867. }, false );
  21868. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  21869. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  21870. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  21871. request.send( null );
  21872. }
  21873. scope.manager.itemStart( url );
  21874. return request;
  21875. },
  21876. setPath: function ( value ) {
  21877. this.path = value;
  21878. return this;
  21879. },
  21880. setResponseType: function ( value ) {
  21881. this.responseType = value;
  21882. return this;
  21883. },
  21884. setWithCredentials: function ( value ) {
  21885. this.withCredentials = value;
  21886. return this;
  21887. },
  21888. setMimeType: function ( value ) {
  21889. this.mimeType = value;
  21890. return this;
  21891. }
  21892. } );
  21893. /**
  21894. * @author mrdoob / http://mrdoob.com/
  21895. *
  21896. * Abstract Base class to block based textures loader (dds, pvr, ...)
  21897. */
  21898. function CompressedTextureLoader( manager ) {
  21899. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21900. // override in sub classes
  21901. this._parser = null;
  21902. }
  21903. Object.assign( CompressedTextureLoader.prototype, {
  21904. load: function ( url, onLoad, onProgress, onError ) {
  21905. var scope = this;
  21906. var images = [];
  21907. var texture = new CompressedTexture();
  21908. texture.image = images;
  21909. var loader = new FileLoader( this.manager );
  21910. loader.setPath( this.path );
  21911. loader.setResponseType( 'arraybuffer' );
  21912. function loadTexture( i ) {
  21913. loader.load( url[ i ], function ( buffer ) {
  21914. var texDatas = scope._parser( buffer, true );
  21915. images[ i ] = {
  21916. width: texDatas.width,
  21917. height: texDatas.height,
  21918. format: texDatas.format,
  21919. mipmaps: texDatas.mipmaps
  21920. };
  21921. loaded += 1;
  21922. if ( loaded === 6 ) {
  21923. if ( texDatas.mipmapCount === 1 )
  21924. texture.minFilter = LinearFilter;
  21925. texture.format = texDatas.format;
  21926. texture.needsUpdate = true;
  21927. if ( onLoad ) onLoad( texture );
  21928. }
  21929. }, onProgress, onError );
  21930. }
  21931. if ( Array.isArray( url ) ) {
  21932. var loaded = 0;
  21933. for ( var i = 0, il = url.length; i < il; ++ i ) {
  21934. loadTexture( i );
  21935. }
  21936. } else {
  21937. // compressed cubemap texture stored in a single DDS file
  21938. loader.load( url, function ( buffer ) {
  21939. var texDatas = scope._parser( buffer, true );
  21940. if ( texDatas.isCubemap ) {
  21941. var faces = texDatas.mipmaps.length / texDatas.mipmapCount;
  21942. for ( var f = 0; f < faces; f ++ ) {
  21943. images[ f ] = { mipmaps : [] };
  21944. for ( var i = 0; i < texDatas.mipmapCount; i ++ ) {
  21945. images[ f ].mipmaps.push( texDatas.mipmaps[ f * texDatas.mipmapCount + i ] );
  21946. images[ f ].format = texDatas.format;
  21947. images[ f ].width = texDatas.width;
  21948. images[ f ].height = texDatas.height;
  21949. }
  21950. }
  21951. } else {
  21952. texture.image.width = texDatas.width;
  21953. texture.image.height = texDatas.height;
  21954. texture.mipmaps = texDatas.mipmaps;
  21955. }
  21956. if ( texDatas.mipmapCount === 1 ) {
  21957. texture.minFilter = LinearFilter;
  21958. }
  21959. texture.format = texDatas.format;
  21960. texture.needsUpdate = true;
  21961. if ( onLoad ) onLoad( texture );
  21962. }, onProgress, onError );
  21963. }
  21964. return texture;
  21965. },
  21966. setPath: function ( value ) {
  21967. this.path = value;
  21968. return this;
  21969. }
  21970. } );
  21971. /**
  21972. * @author Nikos M. / https://github.com/foo123/
  21973. *
  21974. * Abstract Base class to load generic binary textures formats (rgbe, hdr, ...)
  21975. */
  21976. var DataTextureLoader = BinaryTextureLoader;
  21977. function BinaryTextureLoader( manager ) {
  21978. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  21979. // override in sub classes
  21980. this._parser = null;
  21981. }
  21982. Object.assign( BinaryTextureLoader.prototype, {
  21983. load: function ( url, onLoad, onProgress, onError ) {
  21984. var scope = this;
  21985. var texture = new DataTexture();
  21986. var loader = new FileLoader( this.manager );
  21987. loader.setResponseType( 'arraybuffer' );
  21988. loader.load( url, function ( buffer ) {
  21989. var texData = scope._parser( buffer );
  21990. if ( ! texData ) return;
  21991. if ( undefined !== texData.image ) {
  21992. texture.image = texData.image;
  21993. } else if ( undefined !== texData.data ) {
  21994. texture.image.width = texData.width;
  21995. texture.image.height = texData.height;
  21996. texture.image.data = texData.data;
  21997. }
  21998. texture.wrapS = undefined !== texData.wrapS ? texData.wrapS : ClampToEdgeWrapping;
  21999. texture.wrapT = undefined !== texData.wrapT ? texData.wrapT : ClampToEdgeWrapping;
  22000. texture.magFilter = undefined !== texData.magFilter ? texData.magFilter : LinearFilter;
  22001. texture.minFilter = undefined !== texData.minFilter ? texData.minFilter : LinearMipMapLinearFilter;
  22002. texture.anisotropy = undefined !== texData.anisotropy ? texData.anisotropy : 1;
  22003. if ( undefined !== texData.format ) {
  22004. texture.format = texData.format;
  22005. }
  22006. if ( undefined !== texData.type ) {
  22007. texture.type = texData.type;
  22008. }
  22009. if ( undefined !== texData.mipmaps ) {
  22010. texture.mipmaps = texData.mipmaps;
  22011. }
  22012. if ( 1 === texData.mipmapCount ) {
  22013. texture.minFilter = LinearFilter;
  22014. }
  22015. texture.needsUpdate = true;
  22016. if ( onLoad ) onLoad( texture, texData );
  22017. }, onProgress, onError );
  22018. return texture;
  22019. }
  22020. } );
  22021. /**
  22022. * @author mrdoob / http://mrdoob.com/
  22023. */
  22024. function ImageLoader( manager ) {
  22025. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22026. }
  22027. Object.assign( ImageLoader.prototype, {
  22028. load: function ( url, onLoad, onProgress, onError ) {
  22029. var scope = this;
  22030. var image = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'img' );
  22031. image.onload = function () {
  22032. image.onload = null;
  22033. URL.revokeObjectURL( image.src );
  22034. if ( onLoad ) onLoad( image );
  22035. scope.manager.itemEnd( url );
  22036. };
  22037. image.onerror = onError;
  22038. if ( url.indexOf( 'data:' ) === 0 ) {
  22039. image.src = url;
  22040. } else if ( this.crossOrigin !== undefined ) {
  22041. // crossOrigin doesn't work with URL.createObjectURL()?
  22042. image.crossOrigin = this.crossOrigin;
  22043. image.src = url;
  22044. } else {
  22045. var loader = new FileLoader();
  22046. loader.setPath( this.path );
  22047. loader.setResponseType( 'blob' );
  22048. loader.setWithCredentials( this.withCredentials );
  22049. loader.load( url, function ( blob ) {
  22050. image.src = URL.createObjectURL( blob );
  22051. }, onProgress, onError );
  22052. }
  22053. scope.manager.itemStart( url );
  22054. return image;
  22055. },
  22056. setCrossOrigin: function ( value ) {
  22057. this.crossOrigin = value;
  22058. return this;
  22059. },
  22060. setWithCredentials: function ( value ) {
  22061. this.withCredentials = value;
  22062. return this;
  22063. },
  22064. setPath: function ( value ) {
  22065. this.path = value;
  22066. return this;
  22067. }
  22068. } );
  22069. /**
  22070. * @author mrdoob / http://mrdoob.com/
  22071. */
  22072. function CubeTextureLoader( manager ) {
  22073. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22074. }
  22075. Object.assign( CubeTextureLoader.prototype, {
  22076. load: function ( urls, onLoad, onProgress, onError ) {
  22077. var texture = new CubeTexture();
  22078. var loader = new ImageLoader( this.manager );
  22079. loader.setCrossOrigin( this.crossOrigin );
  22080. loader.setPath( this.path );
  22081. var loaded = 0;
  22082. function loadTexture( i ) {
  22083. loader.load( urls[ i ], function ( image ) {
  22084. texture.images[ i ] = image;
  22085. loaded ++;
  22086. if ( loaded === 6 ) {
  22087. texture.needsUpdate = true;
  22088. if ( onLoad ) onLoad( texture );
  22089. }
  22090. }, undefined, onError );
  22091. }
  22092. for ( var i = 0; i < urls.length; ++ i ) {
  22093. loadTexture( i );
  22094. }
  22095. return texture;
  22096. },
  22097. setCrossOrigin: function ( value ) {
  22098. this.crossOrigin = value;
  22099. return this;
  22100. },
  22101. setPath: function ( value ) {
  22102. this.path = value;
  22103. return this;
  22104. }
  22105. } );
  22106. /**
  22107. * @author mrdoob / http://mrdoob.com/
  22108. */
  22109. function TextureLoader( manager ) {
  22110. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  22111. }
  22112. Object.assign( TextureLoader.prototype, {
  22113. load: function ( url, onLoad, onProgress, onError ) {
  22114. var texture = new Texture();
  22115. var loader = new ImageLoader( this.manager );
  22116. loader.setCrossOrigin( this.crossOrigin );
  22117. loader.setWithCredentials( this.withCredentials );
  22118. loader.setPath( this.path );
  22119. loader.load( url, function ( image ) {
  22120. // JPEGs can't have an alpha channel, so memory can be saved by storing them as RGB.
  22121. var isJPEG = url.search( /\.(jpg|jpeg)$/ ) > 0 || url.search( /^data\:image\/jpeg/ ) === 0;
  22122. texture.format = isJPEG ? RGBFormat : RGBAFormat;
  22123. texture.image = image;
  22124. texture.needsUpdate = true;
  22125. if ( onLoad !== undefined ) {
  22126. onLoad( texture );
  22127. }
  22128. }, onProgress, onError );
  22129. return texture;
  22130. },
  22131. setCrossOrigin: function ( value ) {
  22132. this.crossOrigin = value;
  22133. return this;
  22134. },
  22135. setWithCredentials: function ( value ) {
  22136. this.withCredentials = value;
  22137. return this;
  22138. },
  22139. setPath: function ( value ) {
  22140. this.path = value;
  22141. return this;
  22142. }
  22143. } );
  22144. /**
  22145. * @author mrdoob / http://mrdoob.com/
  22146. * @author alteredq / http://alteredqualia.com/
  22147. */
  22148. function Light( color, intensity ) {
  22149. Object3D.call( this );
  22150. this.type = 'Light';
  22151. this.color = new Color( color );
  22152. this.intensity = intensity !== undefined ? intensity : 1;
  22153. this.receiveShadow = undefined;
  22154. }
  22155. Light.prototype = Object.assign( Object.create( Object3D.prototype ), {
  22156. constructor: Light,
  22157. isLight: true,
  22158. copy: function ( source ) {
  22159. Object3D.prototype.copy.call( this, source );
  22160. this.color.copy( source.color );
  22161. this.intensity = source.intensity;
  22162. return this;
  22163. },
  22164. toJSON: function ( meta ) {
  22165. var data = Object3D.prototype.toJSON.call( this, meta );
  22166. data.object.color = this.color.getHex();
  22167. data.object.intensity = this.intensity;
  22168. if ( this.groundColor !== undefined ) data.object.groundColor = this.groundColor.getHex();
  22169. if ( this.distance !== undefined ) data.object.distance = this.distance;
  22170. if ( this.angle !== undefined ) data.object.angle = this.angle;
  22171. if ( this.decay !== undefined ) data.object.decay = this.decay;
  22172. if ( this.penumbra !== undefined ) data.object.penumbra = this.penumbra;
  22173. if ( this.shadow !== undefined ) data.object.shadow = this.shadow.toJSON();
  22174. return data;
  22175. }
  22176. } );
  22177. /**
  22178. * @author alteredq / http://alteredqualia.com/
  22179. */
  22180. function HemisphereLight( skyColor, groundColor, intensity ) {
  22181. Light.call( this, skyColor, intensity );
  22182. this.type = 'HemisphereLight';
  22183. this.castShadow = undefined;
  22184. this.position.copy( Object3D.DefaultUp );
  22185. this.updateMatrix();
  22186. this.groundColor = new Color( groundColor );
  22187. }
  22188. HemisphereLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22189. constructor: HemisphereLight,
  22190. isHemisphereLight: true,
  22191. copy: function ( source ) {
  22192. Light.prototype.copy.call( this, source );
  22193. this.groundColor.copy( source.groundColor );
  22194. return this;
  22195. }
  22196. } );
  22197. /**
  22198. * @author mrdoob / http://mrdoob.com/
  22199. */
  22200. function LightShadow( camera ) {
  22201. this.camera = camera;
  22202. this.bias = 0;
  22203. this.radius = 1;
  22204. this.mapSize = new Vector2( 512, 512 );
  22205. this.map = null;
  22206. this.matrix = new Matrix4();
  22207. }
  22208. Object.assign( LightShadow.prototype, {
  22209. copy: function ( source ) {
  22210. this.camera = source.camera.clone();
  22211. this.bias = source.bias;
  22212. this.radius = source.radius;
  22213. this.mapSize.copy( source.mapSize );
  22214. return this;
  22215. },
  22216. clone: function () {
  22217. return new this.constructor().copy( this );
  22218. },
  22219. toJSON: function () {
  22220. var object = {};
  22221. if ( this.bias !== 0 ) object.bias = this.bias;
  22222. if ( this.radius !== 1 ) object.radius = this.radius;
  22223. if ( this.mapSize.x !== 512 || this.mapSize.y !== 512 ) object.mapSize = this.mapSize.toArray();
  22224. object.camera = this.camera.toJSON( false ).object;
  22225. delete object.camera.matrix;
  22226. return object;
  22227. }
  22228. } );
  22229. /**
  22230. * @author mrdoob / http://mrdoob.com/
  22231. */
  22232. function SpotLightShadow() {
  22233. LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
  22234. }
  22235. SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22236. constructor: SpotLightShadow,
  22237. isSpotLightShadow: true,
  22238. update: function ( light ) {
  22239. var fov = _Math.RAD2DEG * 2 * light.angle;
  22240. var aspect = this.mapSize.width / this.mapSize.height;
  22241. var far = light.distance || 500;
  22242. var camera = this.camera;
  22243. if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
  22244. camera.fov = fov;
  22245. camera.aspect = aspect;
  22246. camera.far = far;
  22247. camera.updateProjectionMatrix();
  22248. }
  22249. }
  22250. } );
  22251. /**
  22252. * @author alteredq / http://alteredqualia.com/
  22253. */
  22254. function SpotLight( color, intensity, distance, angle, penumbra, decay ) {
  22255. Light.call( this, color, intensity );
  22256. this.type = 'SpotLight';
  22257. this.position.copy( Object3D.DefaultUp );
  22258. this.updateMatrix();
  22259. this.target = new Object3D();
  22260. Object.defineProperty( this, 'power', {
  22261. get: function () {
  22262. // intensity = power per solid angle.
  22263. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22264. return this.intensity * Math.PI;
  22265. },
  22266. set: function ( power ) {
  22267. // intensity = power per solid angle.
  22268. // ref: equation (17) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22269. this.intensity = power / Math.PI;
  22270. }
  22271. } );
  22272. this.distance = ( distance !== undefined ) ? distance : 0;
  22273. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  22274. this.penumbra = ( penumbra !== undefined ) ? penumbra : 0;
  22275. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22276. this.shadow = new SpotLightShadow();
  22277. }
  22278. SpotLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22279. constructor: SpotLight,
  22280. isSpotLight: true,
  22281. copy: function ( source ) {
  22282. Light.prototype.copy.call( this, source );
  22283. this.distance = source.distance;
  22284. this.angle = source.angle;
  22285. this.penumbra = source.penumbra;
  22286. this.decay = source.decay;
  22287. this.target = source.target.clone();
  22288. this.shadow = source.shadow.clone();
  22289. return this;
  22290. }
  22291. } );
  22292. /**
  22293. * @author mrdoob / http://mrdoob.com/
  22294. */
  22295. function PointLight( color, intensity, distance, decay ) {
  22296. Light.call( this, color, intensity );
  22297. this.type = 'PointLight';
  22298. Object.defineProperty( this, 'power', {
  22299. get: function () {
  22300. // intensity = power per solid angle.
  22301. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22302. return this.intensity * 4 * Math.PI;
  22303. },
  22304. set: function ( power ) {
  22305. // intensity = power per solid angle.
  22306. // ref: equation (15) from http://www.frostbite.com/wp-content/uploads/2014/11/course_notes_moving_frostbite_to_pbr.pdf
  22307. this.intensity = power / ( 4 * Math.PI );
  22308. }
  22309. } );
  22310. this.distance = ( distance !== undefined ) ? distance : 0;
  22311. this.decay = ( decay !== undefined ) ? decay : 1; // for physically correct lights, should be 2.
  22312. this.shadow = new LightShadow( new PerspectiveCamera( 90, 1, 0.5, 500 ) );
  22313. }
  22314. PointLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22315. constructor: PointLight,
  22316. isPointLight: true,
  22317. copy: function ( source ) {
  22318. Light.prototype.copy.call( this, source );
  22319. this.distance = source.distance;
  22320. this.decay = source.decay;
  22321. this.shadow = source.shadow.clone();
  22322. return this;
  22323. }
  22324. } );
  22325. /**
  22326. * @author mrdoob / http://mrdoob.com/
  22327. */
  22328. function DirectionalLightShadow( light ) {
  22329. LightShadow.call( this, new OrthographicCamera( - 5, 5, 5, - 5, 0.5, 500 ) );
  22330. }
  22331. DirectionalLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
  22332. constructor: DirectionalLightShadow
  22333. } );
  22334. /**
  22335. * @author mrdoob / http://mrdoob.com/
  22336. * @author alteredq / http://alteredqualia.com/
  22337. */
  22338. function DirectionalLight( color, intensity ) {
  22339. Light.call( this, color, intensity );
  22340. this.type = 'DirectionalLight';
  22341. this.position.copy( Object3D.DefaultUp );
  22342. this.updateMatrix();
  22343. this.target = new Object3D();
  22344. this.shadow = new DirectionalLightShadow();
  22345. }
  22346. DirectionalLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22347. constructor: DirectionalLight,
  22348. isDirectionalLight: true,
  22349. copy: function ( source ) {
  22350. Light.prototype.copy.call( this, source );
  22351. this.target = source.target.clone();
  22352. this.shadow = source.shadow.clone();
  22353. return this;
  22354. }
  22355. } );
  22356. /**
  22357. * @author mrdoob / http://mrdoob.com/
  22358. */
  22359. function AmbientLight( color, intensity ) {
  22360. Light.call( this, color, intensity );
  22361. this.type = 'AmbientLight';
  22362. this.castShadow = undefined;
  22363. }
  22364. AmbientLight.prototype = Object.assign( Object.create( Light.prototype ), {
  22365. constructor: AmbientLight,
  22366. isAmbientLight: true
  22367. } );
  22368. /**
  22369. * @author tschw
  22370. * @author Ben Houston / http://clara.io/
  22371. * @author David Sarno / http://lighthaus.us/
  22372. */
  22373. var AnimationUtils = {
  22374. // same as Array.prototype.slice, but also works on typed arrays
  22375. arraySlice: function( array, from, to ) {
  22376. if ( AnimationUtils.isTypedArray( array ) ) {
  22377. return new array.constructor( array.subarray( from, to ) );
  22378. }
  22379. return array.slice( from, to );
  22380. },
  22381. // converts an array to a specific type
  22382. convertArray: function( array, type, forceClone ) {
  22383. if ( ! array || // let 'undefined' and 'null' pass
  22384. ! forceClone && array.constructor === type ) return array;
  22385. if ( typeof type.BYTES_PER_ELEMENT === 'number' ) {
  22386. return new type( array ); // create typed array
  22387. }
  22388. return Array.prototype.slice.call( array ); // create Array
  22389. },
  22390. isTypedArray: function( object ) {
  22391. return ArrayBuffer.isView( object ) &&
  22392. ! ( object instanceof DataView );
  22393. },
  22394. // returns an array by which times and values can be sorted
  22395. getKeyframeOrder: function( times ) {
  22396. function compareTime( i, j ) {
  22397. return times[ i ] - times[ j ];
  22398. }
  22399. var n = times.length;
  22400. var result = new Array( n );
  22401. for ( var i = 0; i !== n; ++ i ) result[ i ] = i;
  22402. result.sort( compareTime );
  22403. return result;
  22404. },
  22405. // uses the array previously returned by 'getKeyframeOrder' to sort data
  22406. sortedArray: function( values, stride, order ) {
  22407. var nValues = values.length;
  22408. var result = new values.constructor( nValues );
  22409. for ( var i = 0, dstOffset = 0; dstOffset !== nValues; ++ i ) {
  22410. var srcOffset = order[ i ] * stride;
  22411. for ( var j = 0; j !== stride; ++ j ) {
  22412. result[ dstOffset ++ ] = values[ srcOffset + j ];
  22413. }
  22414. }
  22415. return result;
  22416. },
  22417. // function for parsing AOS keyframe formats
  22418. flattenJSON: function( jsonKeys, times, values, valuePropertyName ) {
  22419. var i = 1, key = jsonKeys[ 0 ];
  22420. while ( key !== undefined && key[ valuePropertyName ] === undefined ) {
  22421. key = jsonKeys[ i ++ ];
  22422. }
  22423. if ( key === undefined ) return; // no data
  22424. var value = key[ valuePropertyName ];
  22425. if ( value === undefined ) return; // no data
  22426. if ( Array.isArray( value ) ) {
  22427. do {
  22428. value = key[ valuePropertyName ];
  22429. if ( value !== undefined ) {
  22430. times.push( key.time );
  22431. values.push.apply( values, value ); // push all elements
  22432. }
  22433. key = jsonKeys[ i ++ ];
  22434. } while ( key !== undefined );
  22435. } else if ( value.toArray !== undefined ) {
  22436. // ...assume THREE.Math-ish
  22437. do {
  22438. value = key[ valuePropertyName ];
  22439. if ( value !== undefined ) {
  22440. times.push( key.time );
  22441. value.toArray( values, values.length );
  22442. }
  22443. key = jsonKeys[ i ++ ];
  22444. } while ( key !== undefined );
  22445. } else {
  22446. // otherwise push as-is
  22447. do {
  22448. value = key[ valuePropertyName ];
  22449. if ( value !== undefined ) {
  22450. times.push( key.time );
  22451. values.push( value );
  22452. }
  22453. key = jsonKeys[ i ++ ];
  22454. } while ( key !== undefined );
  22455. }
  22456. }
  22457. };
  22458. /**
  22459. * Abstract base class of interpolants over parametric samples.
  22460. *
  22461. * The parameter domain is one dimensional, typically the time or a path
  22462. * along a curve defined by the data.
  22463. *
  22464. * The sample values can have any dimensionality and derived classes may
  22465. * apply special interpretations to the data.
  22466. *
  22467. * This class provides the interval seek in a Template Method, deferring
  22468. * the actual interpolation to derived classes.
  22469. *
  22470. * Time complexity is O(1) for linear access crossing at most two points
  22471. * and O(log N) for random access, where N is the number of positions.
  22472. *
  22473. * References:
  22474. *
  22475. * http://www.oodesign.com/template-method-pattern.html
  22476. *
  22477. * @author tschw
  22478. */
  22479. function Interpolant(
  22480. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22481. this.parameterPositions = parameterPositions;
  22482. this._cachedIndex = 0;
  22483. this.resultBuffer = resultBuffer !== undefined ?
  22484. resultBuffer : new sampleValues.constructor( sampleSize );
  22485. this.sampleValues = sampleValues;
  22486. this.valueSize = sampleSize;
  22487. }
  22488. Interpolant.prototype = {
  22489. constructor: Interpolant,
  22490. evaluate: function( t ) {
  22491. var pp = this.parameterPositions,
  22492. i1 = this._cachedIndex,
  22493. t1 = pp[ i1 ],
  22494. t0 = pp[ i1 - 1 ];
  22495. validate_interval: {
  22496. seek: {
  22497. var right;
  22498. linear_scan: {
  22499. //- See http://jsperf.com/comparison-to-undefined/3
  22500. //- slower code:
  22501. //-
  22502. //- if ( t >= t1 || t1 === undefined ) {
  22503. forward_scan: if ( ! ( t < t1 ) ) {
  22504. for ( var giveUpAt = i1 + 2; ;) {
  22505. if ( t1 === undefined ) {
  22506. if ( t < t0 ) break forward_scan;
  22507. // after end
  22508. i1 = pp.length;
  22509. this._cachedIndex = i1;
  22510. return this.afterEnd_( i1 - 1, t, t0 );
  22511. }
  22512. if ( i1 === giveUpAt ) break; // this loop
  22513. t0 = t1;
  22514. t1 = pp[ ++ i1 ];
  22515. if ( t < t1 ) {
  22516. // we have arrived at the sought interval
  22517. break seek;
  22518. }
  22519. }
  22520. // prepare binary search on the right side of the index
  22521. right = pp.length;
  22522. break linear_scan;
  22523. }
  22524. //- slower code:
  22525. //- if ( t < t0 || t0 === undefined ) {
  22526. if ( ! ( t >= t0 ) ) {
  22527. // looping?
  22528. var t1global = pp[ 1 ];
  22529. if ( t < t1global ) {
  22530. i1 = 2; // + 1, using the scan for the details
  22531. t0 = t1global;
  22532. }
  22533. // linear reverse scan
  22534. for ( var giveUpAt = i1 - 2; ;) {
  22535. if ( t0 === undefined ) {
  22536. // before start
  22537. this._cachedIndex = 0;
  22538. return this.beforeStart_( 0, t, t1 );
  22539. }
  22540. if ( i1 === giveUpAt ) break; // this loop
  22541. t1 = t0;
  22542. t0 = pp[ -- i1 - 1 ];
  22543. if ( t >= t0 ) {
  22544. // we have arrived at the sought interval
  22545. break seek;
  22546. }
  22547. }
  22548. // prepare binary search on the left side of the index
  22549. right = i1;
  22550. i1 = 0;
  22551. break linear_scan;
  22552. }
  22553. // the interval is valid
  22554. break validate_interval;
  22555. } // linear scan
  22556. // binary search
  22557. while ( i1 < right ) {
  22558. var mid = ( i1 + right ) >>> 1;
  22559. if ( t < pp[ mid ] ) {
  22560. right = mid;
  22561. } else {
  22562. i1 = mid + 1;
  22563. }
  22564. }
  22565. t1 = pp[ i1 ];
  22566. t0 = pp[ i1 - 1 ];
  22567. // check boundary cases, again
  22568. if ( t0 === undefined ) {
  22569. this._cachedIndex = 0;
  22570. return this.beforeStart_( 0, t, t1 );
  22571. }
  22572. if ( t1 === undefined ) {
  22573. i1 = pp.length;
  22574. this._cachedIndex = i1;
  22575. return this.afterEnd_( i1 - 1, t0, t );
  22576. }
  22577. } // seek
  22578. this._cachedIndex = i1;
  22579. this.intervalChanged_( i1, t0, t1 );
  22580. } // validate_interval
  22581. return this.interpolate_( i1, t0, t, t1 );
  22582. },
  22583. settings: null, // optional, subclass-specific settings structure
  22584. // Note: The indirection allows central control of many interpolants.
  22585. // --- Protected interface
  22586. DefaultSettings_: {},
  22587. getSettings_: function() {
  22588. return this.settings || this.DefaultSettings_;
  22589. },
  22590. copySampleValue_: function( index ) {
  22591. // copies a sample value to the result buffer
  22592. var result = this.resultBuffer,
  22593. values = this.sampleValues,
  22594. stride = this.valueSize,
  22595. offset = index * stride;
  22596. for ( var i = 0; i !== stride; ++ i ) {
  22597. result[ i ] = values[ offset + i ];
  22598. }
  22599. return result;
  22600. },
  22601. // Template methods for derived classes:
  22602. interpolate_: function( i1, t0, t, t1 ) {
  22603. throw new Error( "call to abstract method" );
  22604. // implementations shall return this.resultBuffer
  22605. },
  22606. intervalChanged_: function( i1, t0, t1 ) {
  22607. // empty
  22608. }
  22609. };
  22610. Object.assign( Interpolant.prototype, {
  22611. beforeStart_: //( 0, t, t0 ), returns this.resultBuffer
  22612. Interpolant.prototype.copySampleValue_,
  22613. afterEnd_: //( N-1, tN-1, t ), returns this.resultBuffer
  22614. Interpolant.prototype.copySampleValue_
  22615. } );
  22616. /**
  22617. * Fast and simple cubic spline interpolant.
  22618. *
  22619. * It was derived from a Hermitian construction setting the first derivative
  22620. * at each sample position to the linear slope between neighboring positions
  22621. * over their parameter interval.
  22622. *
  22623. * @author tschw
  22624. */
  22625. function CubicInterpolant(
  22626. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22627. Interpolant.call(
  22628. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22629. this._weightPrev = -0;
  22630. this._offsetPrev = -0;
  22631. this._weightNext = -0;
  22632. this._offsetNext = -0;
  22633. }
  22634. CubicInterpolant.prototype =
  22635. Object.assign( Object.create( Interpolant.prototype ), {
  22636. constructor: CubicInterpolant,
  22637. DefaultSettings_: {
  22638. endingStart: ZeroCurvatureEnding,
  22639. endingEnd: ZeroCurvatureEnding
  22640. },
  22641. intervalChanged_: function( i1, t0, t1 ) {
  22642. var pp = this.parameterPositions,
  22643. iPrev = i1 - 2,
  22644. iNext = i1 + 1,
  22645. tPrev = pp[ iPrev ],
  22646. tNext = pp[ iNext ];
  22647. if ( tPrev === undefined ) {
  22648. switch ( this.getSettings_().endingStart ) {
  22649. case ZeroSlopeEnding:
  22650. // f'(t0) = 0
  22651. iPrev = i1;
  22652. tPrev = 2 * t0 - t1;
  22653. break;
  22654. case WrapAroundEnding:
  22655. // use the other end of the curve
  22656. iPrev = pp.length - 2;
  22657. tPrev = t0 + pp[ iPrev ] - pp[ iPrev + 1 ];
  22658. break;
  22659. default: // ZeroCurvatureEnding
  22660. // f''(t0) = 0 a.k.a. Natural Spline
  22661. iPrev = i1;
  22662. tPrev = t1;
  22663. }
  22664. }
  22665. if ( tNext === undefined ) {
  22666. switch ( this.getSettings_().endingEnd ) {
  22667. case ZeroSlopeEnding:
  22668. // f'(tN) = 0
  22669. iNext = i1;
  22670. tNext = 2 * t1 - t0;
  22671. break;
  22672. case WrapAroundEnding:
  22673. // use the other end of the curve
  22674. iNext = 1;
  22675. tNext = t1 + pp[ 1 ] - pp[ 0 ];
  22676. break;
  22677. default: // ZeroCurvatureEnding
  22678. // f''(tN) = 0, a.k.a. Natural Spline
  22679. iNext = i1 - 1;
  22680. tNext = t0;
  22681. }
  22682. }
  22683. var halfDt = ( t1 - t0 ) * 0.5,
  22684. stride = this.valueSize;
  22685. this._weightPrev = halfDt / ( t0 - tPrev );
  22686. this._weightNext = halfDt / ( tNext - t1 );
  22687. this._offsetPrev = iPrev * stride;
  22688. this._offsetNext = iNext * stride;
  22689. },
  22690. interpolate_: function( i1, t0, t, t1 ) {
  22691. var result = this.resultBuffer,
  22692. values = this.sampleValues,
  22693. stride = this.valueSize,
  22694. o1 = i1 * stride, o0 = o1 - stride,
  22695. oP = this._offsetPrev, oN = this._offsetNext,
  22696. wP = this._weightPrev, wN = this._weightNext,
  22697. p = ( t - t0 ) / ( t1 - t0 ),
  22698. pp = p * p,
  22699. ppp = pp * p;
  22700. // evaluate polynomials
  22701. var sP = - wP * ppp + 2 * wP * pp - wP * p;
  22702. var s0 = ( 1 + wP ) * ppp + (-1.5 - 2 * wP ) * pp + ( -0.5 + wP ) * p + 1;
  22703. var s1 = (-1 - wN ) * ppp + ( 1.5 + wN ) * pp + 0.5 * p;
  22704. var sN = wN * ppp - wN * pp;
  22705. // combine data linearly
  22706. for ( var i = 0; i !== stride; ++ i ) {
  22707. result[ i ] =
  22708. sP * values[ oP + i ] +
  22709. s0 * values[ o0 + i ] +
  22710. s1 * values[ o1 + i ] +
  22711. sN * values[ oN + i ];
  22712. }
  22713. return result;
  22714. }
  22715. } );
  22716. /**
  22717. * @author tschw
  22718. */
  22719. function LinearInterpolant(
  22720. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22721. Interpolant.call(
  22722. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22723. }
  22724. LinearInterpolant.prototype =
  22725. Object.assign( Object.create( Interpolant.prototype ), {
  22726. constructor: LinearInterpolant,
  22727. interpolate_: function( i1, t0, t, t1 ) {
  22728. var result = this.resultBuffer,
  22729. values = this.sampleValues,
  22730. stride = this.valueSize,
  22731. offset1 = i1 * stride,
  22732. offset0 = offset1 - stride,
  22733. weight1 = ( t - t0 ) / ( t1 - t0 ),
  22734. weight0 = 1 - weight1;
  22735. for ( var i = 0; i !== stride; ++ i ) {
  22736. result[ i ] =
  22737. values[ offset0 + i ] * weight0 +
  22738. values[ offset1 + i ] * weight1;
  22739. }
  22740. return result;
  22741. }
  22742. } );
  22743. /**
  22744. *
  22745. * Interpolant that evaluates to the sample value at the position preceeding
  22746. * the parameter.
  22747. *
  22748. * @author tschw
  22749. */
  22750. function DiscreteInterpolant(
  22751. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22752. Interpolant.call(
  22753. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  22754. }
  22755. DiscreteInterpolant.prototype =
  22756. Object.assign( Object.create( Interpolant.prototype ), {
  22757. constructor: DiscreteInterpolant,
  22758. interpolate_: function( i1, t0, t, t1 ) {
  22759. return this.copySampleValue_( i1 - 1 );
  22760. }
  22761. } );
  22762. var KeyframeTrackPrototype;
  22763. KeyframeTrackPrototype = {
  22764. TimeBufferType: Float32Array,
  22765. ValueBufferType: Float32Array,
  22766. DefaultInterpolation: InterpolateLinear,
  22767. InterpolantFactoryMethodDiscrete: function ( result ) {
  22768. return new DiscreteInterpolant(
  22769. this.times, this.values, this.getValueSize(), result );
  22770. },
  22771. InterpolantFactoryMethodLinear: function ( result ) {
  22772. return new LinearInterpolant(
  22773. this.times, this.values, this.getValueSize(), result );
  22774. },
  22775. InterpolantFactoryMethodSmooth: function ( result ) {
  22776. return new CubicInterpolant(
  22777. this.times, this.values, this.getValueSize(), result );
  22778. },
  22779. setInterpolation: function ( interpolation ) {
  22780. var factoryMethod;
  22781. switch ( interpolation ) {
  22782. case InterpolateDiscrete:
  22783. factoryMethod = this.InterpolantFactoryMethodDiscrete;
  22784. break;
  22785. case InterpolateLinear:
  22786. factoryMethod = this.InterpolantFactoryMethodLinear;
  22787. break;
  22788. case InterpolateSmooth:
  22789. factoryMethod = this.InterpolantFactoryMethodSmooth;
  22790. break;
  22791. }
  22792. if ( factoryMethod === undefined ) {
  22793. var message = "unsupported interpolation for " +
  22794. this.ValueTypeName + " keyframe track named " + this.name;
  22795. if ( this.createInterpolant === undefined ) {
  22796. // fall back to default, unless the default itself is messed up
  22797. if ( interpolation !== this.DefaultInterpolation ) {
  22798. this.setInterpolation( this.DefaultInterpolation );
  22799. } else {
  22800. throw new Error( message ); // fatal, in this case
  22801. }
  22802. }
  22803. console.warn( message );
  22804. return;
  22805. }
  22806. this.createInterpolant = factoryMethod;
  22807. },
  22808. getInterpolation: function () {
  22809. switch ( this.createInterpolant ) {
  22810. case this.InterpolantFactoryMethodDiscrete:
  22811. return InterpolateDiscrete;
  22812. case this.InterpolantFactoryMethodLinear:
  22813. return InterpolateLinear;
  22814. case this.InterpolantFactoryMethodSmooth:
  22815. return InterpolateSmooth;
  22816. }
  22817. },
  22818. getValueSize: function () {
  22819. return this.values.length / this.times.length;
  22820. },
  22821. // move all keyframes either forwards or backwards in time
  22822. shift: function ( timeOffset ) {
  22823. if ( timeOffset !== 0.0 ) {
  22824. var times = this.times;
  22825. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  22826. times[ i ] += timeOffset;
  22827. }
  22828. }
  22829. return this;
  22830. },
  22831. // scale all keyframe times by a factor (useful for frame <-> seconds conversions)
  22832. scale: function ( timeScale ) {
  22833. if ( timeScale !== 1.0 ) {
  22834. var times = this.times;
  22835. for ( var i = 0, n = times.length; i !== n; ++ i ) {
  22836. times[ i ] *= timeScale;
  22837. }
  22838. }
  22839. return this;
  22840. },
  22841. // removes keyframes before and after animation without changing any values within the range [startTime, endTime].
  22842. // IMPORTANT: We do not shift around keys to the start of the track time, because for interpolated keys this will change their values
  22843. trim: function ( startTime, endTime ) {
  22844. var times = this.times,
  22845. nKeys = times.length,
  22846. from = 0,
  22847. to = nKeys - 1;
  22848. while ( from !== nKeys && times[ from ] < startTime ) ++ from;
  22849. while ( to !== - 1 && times[ to ] > endTime ) -- to;
  22850. ++ to; // inclusive -> exclusive bound
  22851. if ( from !== 0 || to !== nKeys ) {
  22852. // empty tracks are forbidden, so keep at least one keyframe
  22853. if ( from >= to ) to = Math.max( to, 1 ), from = to - 1;
  22854. var stride = this.getValueSize();
  22855. this.times = AnimationUtils.arraySlice( times, from, to );
  22856. this.values = AnimationUtils.
  22857. arraySlice( this.values, from * stride, to * stride );
  22858. }
  22859. return this;
  22860. },
  22861. // ensure we do not get a GarbageInGarbageOut situation, make sure tracks are at least minimally viable
  22862. validate: function () {
  22863. var valid = true;
  22864. var valueSize = this.getValueSize();
  22865. if ( valueSize - Math.floor( valueSize ) !== 0 ) {
  22866. console.error( "invalid value size in track", this );
  22867. valid = false;
  22868. }
  22869. var times = this.times,
  22870. values = this.values,
  22871. nKeys = times.length;
  22872. if ( nKeys === 0 ) {
  22873. console.error( "track is empty", this );
  22874. valid = false;
  22875. }
  22876. var prevTime = null;
  22877. for ( var i = 0; i !== nKeys; i ++ ) {
  22878. var currTime = times[ i ];
  22879. if ( typeof currTime === 'number' && isNaN( currTime ) ) {
  22880. console.error( "time is not a valid number", this, i, currTime );
  22881. valid = false;
  22882. break;
  22883. }
  22884. if ( prevTime !== null && prevTime > currTime ) {
  22885. console.error( "out of order keys", this, i, currTime, prevTime );
  22886. valid = false;
  22887. break;
  22888. }
  22889. prevTime = currTime;
  22890. }
  22891. if ( values !== undefined ) {
  22892. if ( AnimationUtils.isTypedArray( values ) ) {
  22893. for ( var i = 0, n = values.length; i !== n; ++ i ) {
  22894. var value = values[ i ];
  22895. if ( isNaN( value ) ) {
  22896. console.error( "value is not a valid number", this, i, value );
  22897. valid = false;
  22898. break;
  22899. }
  22900. }
  22901. }
  22902. }
  22903. return valid;
  22904. },
  22905. // removes equivalent sequential keys as common in morph target sequences
  22906. // (0,0,0,0,1,1,1,0,0,0,0,0,0,0) --> (0,0,1,1,0,0)
  22907. optimize: function () {
  22908. var times = this.times,
  22909. values = this.values,
  22910. stride = this.getValueSize(),
  22911. smoothInterpolation = this.getInterpolation() === InterpolateSmooth,
  22912. writeIndex = 1,
  22913. lastIndex = times.length - 1;
  22914. for ( var i = 1; i < lastIndex; ++ i ) {
  22915. var keep = false;
  22916. var time = times[ i ];
  22917. var timeNext = times[ i + 1 ];
  22918. // remove adjacent keyframes scheduled at the same time
  22919. if ( time !== timeNext && ( i !== 1 || time !== time[ 0 ] ) ) {
  22920. if ( ! smoothInterpolation ) {
  22921. // remove unnecessary keyframes same as their neighbors
  22922. var offset = i * stride,
  22923. offsetP = offset - stride,
  22924. offsetN = offset + stride;
  22925. for ( var j = 0; j !== stride; ++ j ) {
  22926. var value = values[ offset + j ];
  22927. if ( value !== values[ offsetP + j ] ||
  22928. value !== values[ offsetN + j ] ) {
  22929. keep = true;
  22930. break;
  22931. }
  22932. }
  22933. } else keep = true;
  22934. }
  22935. // in-place compaction
  22936. if ( keep ) {
  22937. if ( i !== writeIndex ) {
  22938. times[ writeIndex ] = times[ i ];
  22939. var readOffset = i * stride,
  22940. writeOffset = writeIndex * stride;
  22941. for ( var j = 0; j !== stride; ++ j )
  22942. values[ writeOffset + j ] = values[ readOffset + j ];
  22943. }
  22944. ++ writeIndex;
  22945. }
  22946. }
  22947. // flush last keyframe (compaction looks ahead)
  22948. if ( lastIndex > 0 ) {
  22949. times[ writeIndex ] = times[ lastIndex ];
  22950. for ( var readOffset = lastIndex * stride, writeOffset = writeIndex * stride, j = 0; j !== stride; ++ j )
  22951. values[ writeOffset + j ] = values[ readOffset + j ];
  22952. ++ writeIndex;
  22953. }
  22954. if ( writeIndex !== times.length ) {
  22955. this.times = AnimationUtils.arraySlice( times, 0, writeIndex );
  22956. this.values = AnimationUtils.arraySlice( values, 0, writeIndex * stride );
  22957. }
  22958. return this;
  22959. }
  22960. };
  22961. function KeyframeTrackConstructor( name, times, values, interpolation ) {
  22962. if( name === undefined ) throw new Error( "track name is undefined" );
  22963. if( times === undefined || times.length === 0 ) {
  22964. throw new Error( "no keyframes in track named " + name );
  22965. }
  22966. this.name = name;
  22967. this.times = AnimationUtils.convertArray( times, this.TimeBufferType );
  22968. this.values = AnimationUtils.convertArray( values, this.ValueBufferType );
  22969. this.setInterpolation( interpolation || this.DefaultInterpolation );
  22970. this.validate();
  22971. this.optimize();
  22972. }
  22973. /**
  22974. *
  22975. * A Track of vectored keyframe values.
  22976. *
  22977. *
  22978. * @author Ben Houston / http://clara.io/
  22979. * @author David Sarno / http://lighthaus.us/
  22980. * @author tschw
  22981. */
  22982. function VectorKeyframeTrack( name, times, values, interpolation ) {
  22983. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  22984. }
  22985. VectorKeyframeTrack.prototype =
  22986. Object.assign( Object.create( KeyframeTrackPrototype ), {
  22987. constructor: VectorKeyframeTrack,
  22988. ValueTypeName: 'vector'
  22989. // ValueBufferType is inherited
  22990. // DefaultInterpolation is inherited
  22991. } );
  22992. /**
  22993. * Spherical linear unit quaternion interpolant.
  22994. *
  22995. * @author tschw
  22996. */
  22997. function QuaternionLinearInterpolant(
  22998. parameterPositions, sampleValues, sampleSize, resultBuffer ) {
  22999. Interpolant.call(
  23000. this, parameterPositions, sampleValues, sampleSize, resultBuffer );
  23001. }
  23002. QuaternionLinearInterpolant.prototype =
  23003. Object.assign( Object.create( Interpolant.prototype ), {
  23004. constructor: QuaternionLinearInterpolant,
  23005. interpolate_: function( i1, t0, t, t1 ) {
  23006. var result = this.resultBuffer,
  23007. values = this.sampleValues,
  23008. stride = this.valueSize,
  23009. offset = i1 * stride,
  23010. alpha = ( t - t0 ) / ( t1 - t0 );
  23011. for ( var end = offset + stride; offset !== end; offset += 4 ) {
  23012. Quaternion.slerpFlat( result, 0,
  23013. values, offset - stride, values, offset, alpha );
  23014. }
  23015. return result;
  23016. }
  23017. } );
  23018. /**
  23019. *
  23020. * A Track of quaternion keyframe values.
  23021. *
  23022. * @author Ben Houston / http://clara.io/
  23023. * @author David Sarno / http://lighthaus.us/
  23024. * @author tschw
  23025. */
  23026. function QuaternionKeyframeTrack( name, times, values, interpolation ) {
  23027. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23028. }
  23029. QuaternionKeyframeTrack.prototype =
  23030. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23031. constructor: QuaternionKeyframeTrack,
  23032. ValueTypeName: 'quaternion',
  23033. // ValueBufferType is inherited
  23034. DefaultInterpolation: InterpolateLinear,
  23035. InterpolantFactoryMethodLinear: function( result ) {
  23036. return new QuaternionLinearInterpolant(
  23037. this.times, this.values, this.getValueSize(), result );
  23038. },
  23039. InterpolantFactoryMethodSmooth: undefined // not yet implemented
  23040. } );
  23041. /**
  23042. *
  23043. * A Track of numeric keyframe values.
  23044. *
  23045. * @author Ben Houston / http://clara.io/
  23046. * @author David Sarno / http://lighthaus.us/
  23047. * @author tschw
  23048. */
  23049. function NumberKeyframeTrack( name, times, values, interpolation ) {
  23050. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23051. }
  23052. NumberKeyframeTrack.prototype =
  23053. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23054. constructor: NumberKeyframeTrack,
  23055. ValueTypeName: 'number'
  23056. // ValueBufferType is inherited
  23057. // DefaultInterpolation is inherited
  23058. } );
  23059. /**
  23060. *
  23061. * A Track that interpolates Strings
  23062. *
  23063. *
  23064. * @author Ben Houston / http://clara.io/
  23065. * @author David Sarno / http://lighthaus.us/
  23066. * @author tschw
  23067. */
  23068. function StringKeyframeTrack( name, times, values, interpolation ) {
  23069. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23070. }
  23071. StringKeyframeTrack.prototype =
  23072. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23073. constructor: StringKeyframeTrack,
  23074. ValueTypeName: 'string',
  23075. ValueBufferType: Array,
  23076. DefaultInterpolation: InterpolateDiscrete,
  23077. InterpolantFactoryMethodLinear: undefined,
  23078. InterpolantFactoryMethodSmooth: undefined
  23079. } );
  23080. /**
  23081. *
  23082. * A Track of Boolean keyframe values.
  23083. *
  23084. *
  23085. * @author Ben Houston / http://clara.io/
  23086. * @author David Sarno / http://lighthaus.us/
  23087. * @author tschw
  23088. */
  23089. function BooleanKeyframeTrack( name, times, values ) {
  23090. KeyframeTrackConstructor.call( this, name, times, values );
  23091. }
  23092. BooleanKeyframeTrack.prototype =
  23093. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23094. constructor: BooleanKeyframeTrack,
  23095. ValueTypeName: 'bool',
  23096. ValueBufferType: Array,
  23097. DefaultInterpolation: InterpolateDiscrete,
  23098. InterpolantFactoryMethodLinear: undefined,
  23099. InterpolantFactoryMethodSmooth: undefined
  23100. // Note: Actually this track could have a optimized / compressed
  23101. // representation of a single value and a custom interpolant that
  23102. // computes "firstValue ^ isOdd( index )".
  23103. } );
  23104. /**
  23105. *
  23106. * A Track of keyframe values that represent color.
  23107. *
  23108. *
  23109. * @author Ben Houston / http://clara.io/
  23110. * @author David Sarno / http://lighthaus.us/
  23111. * @author tschw
  23112. */
  23113. function ColorKeyframeTrack( name, times, values, interpolation ) {
  23114. KeyframeTrackConstructor.call( this, name, times, values, interpolation );
  23115. }
  23116. ColorKeyframeTrack.prototype =
  23117. Object.assign( Object.create( KeyframeTrackPrototype ), {
  23118. constructor: ColorKeyframeTrack,
  23119. ValueTypeName: 'color'
  23120. // ValueBufferType is inherited
  23121. // DefaultInterpolation is inherited
  23122. // Note: Very basic implementation and nothing special yet.
  23123. // However, this is the place for color space parameterization.
  23124. } );
  23125. /**
  23126. *
  23127. * A timed sequence of keyframes for a specific property.
  23128. *
  23129. *
  23130. * @author Ben Houston / http://clara.io/
  23131. * @author David Sarno / http://lighthaus.us/
  23132. * @author tschw
  23133. */
  23134. function KeyframeTrack( name, times, values, interpolation ) {
  23135. KeyframeTrackConstructor.apply( this, arguments );
  23136. }
  23137. KeyframeTrack.prototype = KeyframeTrackPrototype;
  23138. KeyframeTrackPrototype.constructor = KeyframeTrack;
  23139. // Static methods:
  23140. Object.assign( KeyframeTrack, {
  23141. // Serialization (in static context, because of constructor invocation
  23142. // and automatic invocation of .toJSON):
  23143. parse: function( json ) {
  23144. if( json.type === undefined ) {
  23145. throw new Error( "track type undefined, can not parse" );
  23146. }
  23147. var trackType = KeyframeTrack._getTrackTypeForValueTypeName( json.type );
  23148. if ( json.times === undefined ) {
  23149. var times = [], values = [];
  23150. AnimationUtils.flattenJSON( json.keys, times, values, 'value' );
  23151. json.times = times;
  23152. json.values = values;
  23153. }
  23154. // derived classes can define a static parse method
  23155. if ( trackType.parse !== undefined ) {
  23156. return trackType.parse( json );
  23157. } else {
  23158. // by default, we asssume a constructor compatible with the base
  23159. return new trackType(
  23160. json.name, json.times, json.values, json.interpolation );
  23161. }
  23162. },
  23163. toJSON: function( track ) {
  23164. var trackType = track.constructor;
  23165. var json;
  23166. // derived classes can define a static toJSON method
  23167. if ( trackType.toJSON !== undefined ) {
  23168. json = trackType.toJSON( track );
  23169. } else {
  23170. // by default, we assume the data can be serialized as-is
  23171. json = {
  23172. 'name': track.name,
  23173. 'times': AnimationUtils.convertArray( track.times, Array ),
  23174. 'values': AnimationUtils.convertArray( track.values, Array )
  23175. };
  23176. var interpolation = track.getInterpolation();
  23177. if ( interpolation !== track.DefaultInterpolation ) {
  23178. json.interpolation = interpolation;
  23179. }
  23180. }
  23181. json.type = track.ValueTypeName; // mandatory
  23182. return json;
  23183. },
  23184. _getTrackTypeForValueTypeName: function( typeName ) {
  23185. switch( typeName.toLowerCase() ) {
  23186. case "scalar":
  23187. case "double":
  23188. case "float":
  23189. case "number":
  23190. case "integer":
  23191. return NumberKeyframeTrack;
  23192. case "vector":
  23193. case "vector2":
  23194. case "vector3":
  23195. case "vector4":
  23196. return VectorKeyframeTrack;
  23197. case "color":
  23198. return ColorKeyframeTrack;
  23199. case "quaternion":
  23200. return QuaternionKeyframeTrack;
  23201. case "bool":
  23202. case "boolean":
  23203. return BooleanKeyframeTrack;
  23204. case "string":
  23205. return StringKeyframeTrack;
  23206. }
  23207. throw new Error( "Unsupported typeName: " + typeName );
  23208. }
  23209. } );
  23210. /**
  23211. *
  23212. * Reusable set of Tracks that represent an animation.
  23213. *
  23214. * @author Ben Houston / http://clara.io/
  23215. * @author David Sarno / http://lighthaus.us/
  23216. */
  23217. function AnimationClip( name, duration, tracks ) {
  23218. this.name = name;
  23219. this.tracks = tracks;
  23220. this.duration = ( duration !== undefined ) ? duration : -1;
  23221. this.uuid = _Math.generateUUID();
  23222. // this means it should figure out its duration by scanning the tracks
  23223. if ( this.duration < 0 ) {
  23224. this.resetDuration();
  23225. }
  23226. this.optimize();
  23227. }
  23228. AnimationClip.prototype = {
  23229. constructor: AnimationClip,
  23230. resetDuration: function() {
  23231. var tracks = this.tracks,
  23232. duration = 0;
  23233. for ( var i = 0, n = tracks.length; i !== n; ++ i ) {
  23234. var track = this.tracks[ i ];
  23235. duration = Math.max( duration, track.times[ track.times.length - 1 ] );
  23236. }
  23237. this.duration = duration;
  23238. },
  23239. trim: function() {
  23240. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23241. this.tracks[ i ].trim( 0, this.duration );
  23242. }
  23243. return this;
  23244. },
  23245. optimize: function() {
  23246. for ( var i = 0; i < this.tracks.length; i ++ ) {
  23247. this.tracks[ i ].optimize();
  23248. }
  23249. return this;
  23250. }
  23251. };
  23252. // Static methods:
  23253. Object.assign( AnimationClip, {
  23254. parse: function( json ) {
  23255. var tracks = [],
  23256. jsonTracks = json.tracks,
  23257. frameTime = 1.0 / ( json.fps || 1.0 );
  23258. for ( var i = 0, n = jsonTracks.length; i !== n; ++ i ) {
  23259. tracks.push( KeyframeTrack.parse( jsonTracks[ i ] ).scale( frameTime ) );
  23260. }
  23261. return new AnimationClip( json.name, json.duration, tracks );
  23262. },
  23263. toJSON: function( clip ) {
  23264. var tracks = [],
  23265. clipTracks = clip.tracks;
  23266. var json = {
  23267. 'name': clip.name,
  23268. 'duration': clip.duration,
  23269. 'tracks': tracks
  23270. };
  23271. for ( var i = 0, n = clipTracks.length; i !== n; ++ i ) {
  23272. tracks.push( KeyframeTrack.toJSON( clipTracks[ i ] ) );
  23273. }
  23274. return json;
  23275. },
  23276. CreateFromMorphTargetSequence: function( name, morphTargetSequence, fps, noLoop ) {
  23277. var numMorphTargets = morphTargetSequence.length;
  23278. var tracks = [];
  23279. for ( var i = 0; i < numMorphTargets; i ++ ) {
  23280. var times = [];
  23281. var values = [];
  23282. times.push(
  23283. ( i + numMorphTargets - 1 ) % numMorphTargets,
  23284. i,
  23285. ( i + 1 ) % numMorphTargets );
  23286. values.push( 0, 1, 0 );
  23287. var order = AnimationUtils.getKeyframeOrder( times );
  23288. times = AnimationUtils.sortedArray( times, 1, order );
  23289. values = AnimationUtils.sortedArray( values, 1, order );
  23290. // if there is a key at the first frame, duplicate it as the
  23291. // last frame as well for perfect loop.
  23292. if ( ! noLoop && times[ 0 ] === 0 ) {
  23293. times.push( numMorphTargets );
  23294. values.push( values[ 0 ] );
  23295. }
  23296. tracks.push(
  23297. new NumberKeyframeTrack(
  23298. '.morphTargetInfluences[' + morphTargetSequence[ i ].name + ']',
  23299. times, values
  23300. ).scale( 1.0 / fps ) );
  23301. }
  23302. return new AnimationClip( name, -1, tracks );
  23303. },
  23304. findByName: function( objectOrClipArray, name ) {
  23305. var clipArray = objectOrClipArray;
  23306. if ( ! Array.isArray( objectOrClipArray ) ) {
  23307. var o = objectOrClipArray;
  23308. clipArray = o.geometry && o.geometry.animations || o.animations;
  23309. }
  23310. for ( var i = 0; i < clipArray.length; i ++ ) {
  23311. if ( clipArray[ i ].name === name ) {
  23312. return clipArray[ i ];
  23313. }
  23314. }
  23315. return null;
  23316. },
  23317. CreateClipsFromMorphTargetSequences: function( morphTargets, fps, noLoop ) {
  23318. var animationToMorphTargets = {};
  23319. // tested with https://regex101.com/ on trick sequences
  23320. // such flamingo_flyA_003, flamingo_run1_003, crdeath0059
  23321. var pattern = /^([\w-]*?)([\d]+)$/;
  23322. // sort morph target names into animation groups based
  23323. // patterns like Walk_001, Walk_002, Run_001, Run_002
  23324. for ( var i = 0, il = morphTargets.length; i < il; i ++ ) {
  23325. var morphTarget = morphTargets[ i ];
  23326. var parts = morphTarget.name.match( pattern );
  23327. if ( parts && parts.length > 1 ) {
  23328. var name = parts[ 1 ];
  23329. var animationMorphTargets = animationToMorphTargets[ name ];
  23330. if ( ! animationMorphTargets ) {
  23331. animationToMorphTargets[ name ] = animationMorphTargets = [];
  23332. }
  23333. animationMorphTargets.push( morphTarget );
  23334. }
  23335. }
  23336. var clips = [];
  23337. for ( var name in animationToMorphTargets ) {
  23338. clips.push( AnimationClip.CreateFromMorphTargetSequence( name, animationToMorphTargets[ name ], fps, noLoop ) );
  23339. }
  23340. return clips;
  23341. },
  23342. // parse the animation.hierarchy format
  23343. parseAnimation: function( animation, bones ) {
  23344. if ( ! animation ) {
  23345. console.error( " no animation in JSONLoader data" );
  23346. return null;
  23347. }
  23348. var addNonemptyTrack = function(
  23349. trackType, trackName, animationKeys, propertyName, destTracks ) {
  23350. // only return track if there are actually keys.
  23351. if ( animationKeys.length !== 0 ) {
  23352. var times = [];
  23353. var values = [];
  23354. AnimationUtils.flattenJSON(
  23355. animationKeys, times, values, propertyName );
  23356. // empty keys are filtered out, so check again
  23357. if ( times.length !== 0 ) {
  23358. destTracks.push( new trackType( trackName, times, values ) );
  23359. }
  23360. }
  23361. };
  23362. var tracks = [];
  23363. var clipName = animation.name || 'default';
  23364. // automatic length determination in AnimationClip.
  23365. var duration = animation.length || -1;
  23366. var fps = animation.fps || 30;
  23367. var hierarchyTracks = animation.hierarchy || [];
  23368. for ( var h = 0; h < hierarchyTracks.length; h ++ ) {
  23369. var animationKeys = hierarchyTracks[ h ].keys;
  23370. // skip empty tracks
  23371. if ( ! animationKeys || animationKeys.length === 0 ) continue;
  23372. // process morph targets in a way exactly compatible
  23373. // with AnimationHandler.init( animation )
  23374. if ( animationKeys[0].morphTargets ) {
  23375. // figure out all morph targets used in this track
  23376. var morphTargetNames = {};
  23377. for ( var k = 0; k < animationKeys.length; k ++ ) {
  23378. if ( animationKeys[k].morphTargets ) {
  23379. for ( var m = 0; m < animationKeys[k].morphTargets.length; m ++ ) {
  23380. morphTargetNames[ animationKeys[k].morphTargets[m] ] = -1;
  23381. }
  23382. }
  23383. }
  23384. // create a track for each morph target with all zero
  23385. // morphTargetInfluences except for the keys in which
  23386. // the morphTarget is named.
  23387. for ( var morphTargetName in morphTargetNames ) {
  23388. var times = [];
  23389. var values = [];
  23390. for ( var m = 0; m !== animationKeys[k].morphTargets.length; ++ m ) {
  23391. var animationKey = animationKeys[k];
  23392. times.push( animationKey.time );
  23393. values.push( ( animationKey.morphTarget === morphTargetName ) ? 1 : 0 );
  23394. }
  23395. tracks.push( new NumberKeyframeTrack('.morphTargetInfluence[' + morphTargetName + ']', times, values ) );
  23396. }
  23397. duration = morphTargetNames.length * ( fps || 1.0 );
  23398. } else {
  23399. // ...assume skeletal animation
  23400. var boneName = '.bones[' + bones[ h ].name + ']';
  23401. addNonemptyTrack(
  23402. VectorKeyframeTrack, boneName + '.position',
  23403. animationKeys, 'pos', tracks );
  23404. addNonemptyTrack(
  23405. QuaternionKeyframeTrack, boneName + '.quaternion',
  23406. animationKeys, 'rot', tracks );
  23407. addNonemptyTrack(
  23408. VectorKeyframeTrack, boneName + '.scale',
  23409. animationKeys, 'scl', tracks );
  23410. }
  23411. }
  23412. if ( tracks.length === 0 ) {
  23413. return null;
  23414. }
  23415. var clip = new AnimationClip( clipName, duration, tracks );
  23416. return clip;
  23417. }
  23418. } );
  23419. /**
  23420. * @author mrdoob / http://mrdoob.com/
  23421. */
  23422. function MaterialLoader( manager ) {
  23423. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23424. this.textures = {};
  23425. }
  23426. Object.assign( MaterialLoader.prototype, {
  23427. load: function ( url, onLoad, onProgress, onError ) {
  23428. var scope = this;
  23429. var loader = new FileLoader( scope.manager );
  23430. loader.load( url, function ( text ) {
  23431. onLoad( scope.parse( JSON.parse( text ) ) );
  23432. }, onProgress, onError );
  23433. },
  23434. setTextures: function ( value ) {
  23435. this.textures = value;
  23436. },
  23437. parse: function ( json ) {
  23438. var textures = this.textures;
  23439. function getTexture( name ) {
  23440. if ( textures[ name ] === undefined ) {
  23441. console.warn( 'THREE.MaterialLoader: Undefined texture', name );
  23442. }
  23443. return textures[ name ];
  23444. }
  23445. var material = new Materials[ json.type ]();
  23446. if ( json.uuid !== undefined ) material.uuid = json.uuid;
  23447. if ( json.name !== undefined ) material.name = json.name;
  23448. if ( json.color !== undefined ) material.color.setHex( json.color );
  23449. if ( json.roughness !== undefined ) material.roughness = json.roughness;
  23450. if ( json.metalness !== undefined ) material.metalness = json.metalness;
  23451. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  23452. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  23453. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  23454. if ( json.clearCoat !== undefined ) material.clearCoat = json.clearCoat;
  23455. if ( json.clearCoatRoughness !== undefined ) material.clearCoatRoughness = json.clearCoatRoughness;
  23456. if ( json.uniforms !== undefined ) material.uniforms = json.uniforms;
  23457. if ( json.vertexShader !== undefined ) material.vertexShader = json.vertexShader;
  23458. if ( json.fragmentShader !== undefined ) material.fragmentShader = json.fragmentShader;
  23459. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  23460. if ( json.fog !== undefined ) material.fog = json.fog;
  23461. if ( json.shading !== undefined ) material.shading = json.shading;
  23462. if ( json.blending !== undefined ) material.blending = json.blending;
  23463. if ( json.side !== undefined ) material.side = json.side;
  23464. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  23465. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  23466. if ( json.alphaTest !== undefined ) material.alphaTest = json.alphaTest;
  23467. if ( json.depthTest !== undefined ) material.depthTest = json.depthTest;
  23468. if ( json.depthWrite !== undefined ) material.depthWrite = json.depthWrite;
  23469. if ( json.colorWrite !== undefined ) material.colorWrite = json.colorWrite;
  23470. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  23471. if ( json.wireframeLinewidth !== undefined ) material.wireframeLinewidth = json.wireframeLinewidth;
  23472. if ( json.wireframeLinecap !== undefined ) material.wireframeLinecap = json.wireframeLinecap;
  23473. if ( json.wireframeLinejoin !== undefined ) material.wireframeLinejoin = json.wireframeLinejoin;
  23474. if ( json.skinning !== undefined ) material.skinning = json.skinning;
  23475. if ( json.morphTargets !== undefined ) material.morphTargets = json.morphTargets;
  23476. // for PointsMaterial
  23477. if ( json.size !== undefined ) material.size = json.size;
  23478. if ( json.sizeAttenuation !== undefined ) material.sizeAttenuation = json.sizeAttenuation;
  23479. // maps
  23480. if ( json.map !== undefined ) material.map = getTexture( json.map );
  23481. if ( json.alphaMap !== undefined ) {
  23482. material.alphaMap = getTexture( json.alphaMap );
  23483. material.transparent = true;
  23484. }
  23485. if ( json.bumpMap !== undefined ) material.bumpMap = getTexture( json.bumpMap );
  23486. if ( json.bumpScale !== undefined ) material.bumpScale = json.bumpScale;
  23487. if ( json.normalMap !== undefined ) material.normalMap = getTexture( json.normalMap );
  23488. if ( json.normalScale !== undefined ) {
  23489. var normalScale = json.normalScale;
  23490. if ( Array.isArray( normalScale ) === false ) {
  23491. // Blender exporter used to export a scalar. See #7459
  23492. normalScale = [ normalScale, normalScale ];
  23493. }
  23494. material.normalScale = new Vector2().fromArray( normalScale );
  23495. }
  23496. if ( json.displacementMap !== undefined ) material.displacementMap = getTexture( json.displacementMap );
  23497. if ( json.displacementScale !== undefined ) material.displacementScale = json.displacementScale;
  23498. if ( json.displacementBias !== undefined ) material.displacementBias = json.displacementBias;
  23499. if ( json.roughnessMap !== undefined ) material.roughnessMap = getTexture( json.roughnessMap );
  23500. if ( json.metalnessMap !== undefined ) material.metalnessMap = getTexture( json.metalnessMap );
  23501. if ( json.emissiveMap !== undefined ) material.emissiveMap = getTexture( json.emissiveMap );
  23502. if ( json.emissiveIntensity !== undefined ) material.emissiveIntensity = json.emissiveIntensity;
  23503. if ( json.specularMap !== undefined ) material.specularMap = getTexture( json.specularMap );
  23504. if ( json.envMap !== undefined ) material.envMap = getTexture( json.envMap );
  23505. if ( json.reflectivity !== undefined ) material.reflectivity = json.reflectivity;
  23506. if ( json.lightMap !== undefined ) material.lightMap = getTexture( json.lightMap );
  23507. if ( json.lightMapIntensity !== undefined ) material.lightMapIntensity = json.lightMapIntensity;
  23508. if ( json.aoMap !== undefined ) material.aoMap = getTexture( json.aoMap );
  23509. if ( json.aoMapIntensity !== undefined ) material.aoMapIntensity = json.aoMapIntensity;
  23510. if ( json.gradientMap !== undefined ) material.gradientMap = getTexture( json.gradientMap );
  23511. // MultiMaterial
  23512. if ( json.materials !== undefined ) {
  23513. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  23514. material.materials.push( this.parse( json.materials[ i ] ) );
  23515. }
  23516. }
  23517. return material;
  23518. }
  23519. } );
  23520. /**
  23521. * @author mrdoob / http://mrdoob.com/
  23522. */
  23523. function BufferGeometryLoader( manager ) {
  23524. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23525. }
  23526. Object.assign( BufferGeometryLoader.prototype, {
  23527. load: function ( url, onLoad, onProgress, onError ) {
  23528. var scope = this;
  23529. var loader = new FileLoader( scope.manager );
  23530. loader.load( url, function ( text ) {
  23531. onLoad( scope.parse( JSON.parse( text ) ) );
  23532. }, onProgress, onError );
  23533. },
  23534. parse: function ( json ) {
  23535. var geometry = new BufferGeometry();
  23536. var index = json.data.index;
  23537. var TYPED_ARRAYS = {
  23538. 'Int8Array': Int8Array,
  23539. 'Uint8Array': Uint8Array,
  23540. 'Uint8ClampedArray': Uint8ClampedArray,
  23541. 'Int16Array': Int16Array,
  23542. 'Uint16Array': Uint16Array,
  23543. 'Int32Array': Int32Array,
  23544. 'Uint32Array': Uint32Array,
  23545. 'Float32Array': Float32Array,
  23546. 'Float64Array': Float64Array
  23547. };
  23548. if ( index !== undefined ) {
  23549. var typedArray = new TYPED_ARRAYS[ index.type ]( index.array );
  23550. geometry.setIndex( new BufferAttribute( typedArray, 1 ) );
  23551. }
  23552. var attributes = json.data.attributes;
  23553. for ( var key in attributes ) {
  23554. var attribute = attributes[ key ];
  23555. var typedArray = new TYPED_ARRAYS[ attribute.type ]( attribute.array );
  23556. geometry.addAttribute( key, new BufferAttribute( typedArray, attribute.itemSize, attribute.normalized ) );
  23557. }
  23558. var groups = json.data.groups || json.data.drawcalls || json.data.offsets;
  23559. if ( groups !== undefined ) {
  23560. for ( var i = 0, n = groups.length; i !== n; ++ i ) {
  23561. var group = groups[ i ];
  23562. geometry.addGroup( group.start, group.count, group.materialIndex );
  23563. }
  23564. }
  23565. var boundingSphere = json.data.boundingSphere;
  23566. if ( boundingSphere !== undefined ) {
  23567. var center = new Vector3();
  23568. if ( boundingSphere.center !== undefined ) {
  23569. center.fromArray( boundingSphere.center );
  23570. }
  23571. geometry.boundingSphere = new Sphere( center, boundingSphere.radius );
  23572. }
  23573. return geometry;
  23574. }
  23575. } );
  23576. /**
  23577. * @author alteredq / http://alteredqualia.com/
  23578. */
  23579. function Loader() {
  23580. this.onLoadStart = function () {};
  23581. this.onLoadProgress = function () {};
  23582. this.onLoadComplete = function () {};
  23583. }
  23584. Loader.prototype = {
  23585. constructor: Loader,
  23586. crossOrigin: undefined,
  23587. extractUrlBase: function ( url ) {
  23588. var parts = url.split( '/' );
  23589. if ( parts.length === 1 ) return './';
  23590. parts.pop();
  23591. return parts.join( '/' ) + '/';
  23592. },
  23593. initMaterials: function ( materials, texturePath, crossOrigin ) {
  23594. var array = [];
  23595. for ( var i = 0; i < materials.length; ++ i ) {
  23596. array[ i ] = this.createMaterial( materials[ i ], texturePath, crossOrigin );
  23597. }
  23598. return array;
  23599. },
  23600. createMaterial: ( function () {
  23601. var color, textureLoader, materialLoader;
  23602. return function createMaterial( m, texturePath, crossOrigin ) {
  23603. if ( color === undefined ) color = new Color();
  23604. if ( textureLoader === undefined ) textureLoader = new TextureLoader();
  23605. if ( materialLoader === undefined ) materialLoader = new MaterialLoader();
  23606. // convert from old material format
  23607. var textures = {};
  23608. function loadTexture( path, repeat, offset, wrap, anisotropy ) {
  23609. var fullPath = texturePath + path;
  23610. var loader = Loader.Handlers.get( fullPath );
  23611. var texture;
  23612. if ( loader !== null ) {
  23613. texture = loader.load( fullPath );
  23614. } else {
  23615. textureLoader.setCrossOrigin( crossOrigin );
  23616. texture = textureLoader.load( fullPath );
  23617. }
  23618. if ( repeat !== undefined ) {
  23619. texture.repeat.fromArray( repeat );
  23620. if ( repeat[ 0 ] !== 1 ) texture.wrapS = RepeatWrapping;
  23621. if ( repeat[ 1 ] !== 1 ) texture.wrapT = RepeatWrapping;
  23622. }
  23623. if ( offset !== undefined ) {
  23624. texture.offset.fromArray( offset );
  23625. }
  23626. if ( wrap !== undefined ) {
  23627. if ( wrap[ 0 ] === 'repeat' ) texture.wrapS = RepeatWrapping;
  23628. if ( wrap[ 0 ] === 'mirror' ) texture.wrapS = MirroredRepeatWrapping;
  23629. if ( wrap[ 1 ] === 'repeat' ) texture.wrapT = RepeatWrapping;
  23630. if ( wrap[ 1 ] === 'mirror' ) texture.wrapT = MirroredRepeatWrapping;
  23631. }
  23632. if ( anisotropy !== undefined ) {
  23633. texture.anisotropy = anisotropy;
  23634. }
  23635. var uuid = _Math.generateUUID();
  23636. textures[ uuid ] = texture;
  23637. return uuid;
  23638. }
  23639. //
  23640. var json = {
  23641. uuid: _Math.generateUUID(),
  23642. type: 'MeshLambertMaterial'
  23643. };
  23644. for ( var name in m ) {
  23645. var value = m[ name ];
  23646. switch ( name ) {
  23647. case 'DbgColor':
  23648. case 'DbgIndex':
  23649. case 'opticalDensity':
  23650. case 'illumination':
  23651. break;
  23652. case 'DbgName':
  23653. json.name = value;
  23654. break;
  23655. case 'blending':
  23656. json.blending = BlendingMode[ value ];
  23657. break;
  23658. case 'colorAmbient':
  23659. case 'mapAmbient':
  23660. console.warn( 'THREE.Loader.createMaterial:', name, 'is no longer supported.' );
  23661. break;
  23662. case 'colorDiffuse':
  23663. json.color = color.fromArray( value ).getHex();
  23664. break;
  23665. case 'colorSpecular':
  23666. json.specular = color.fromArray( value ).getHex();
  23667. break;
  23668. case 'colorEmissive':
  23669. json.emissive = color.fromArray( value ).getHex();
  23670. break;
  23671. case 'specularCoef':
  23672. json.shininess = value;
  23673. break;
  23674. case 'shading':
  23675. if ( value.toLowerCase() === 'basic' ) json.type = 'MeshBasicMaterial';
  23676. if ( value.toLowerCase() === 'phong' ) json.type = 'MeshPhongMaterial';
  23677. if ( value.toLowerCase() === 'standard' ) json.type = 'MeshStandardMaterial';
  23678. break;
  23679. case 'mapDiffuse':
  23680. json.map = loadTexture( value, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  23681. break;
  23682. case 'mapDiffuseRepeat':
  23683. case 'mapDiffuseOffset':
  23684. case 'mapDiffuseWrap':
  23685. case 'mapDiffuseAnisotropy':
  23686. break;
  23687. case 'mapEmissive':
  23688. json.emissiveMap = loadTexture( value, m.mapEmissiveRepeat, m.mapEmissiveOffset, m.mapEmissiveWrap, m.mapEmissiveAnisotropy );
  23689. break;
  23690. case 'mapEmissiveRepeat':
  23691. case 'mapEmissiveOffset':
  23692. case 'mapEmissiveWrap':
  23693. case 'mapEmissiveAnisotropy':
  23694. break;
  23695. case 'mapLight':
  23696. json.lightMap = loadTexture( value, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  23697. break;
  23698. case 'mapLightRepeat':
  23699. case 'mapLightOffset':
  23700. case 'mapLightWrap':
  23701. case 'mapLightAnisotropy':
  23702. break;
  23703. case 'mapAO':
  23704. json.aoMap = loadTexture( value, m.mapAORepeat, m.mapAOOffset, m.mapAOWrap, m.mapAOAnisotropy );
  23705. break;
  23706. case 'mapAORepeat':
  23707. case 'mapAOOffset':
  23708. case 'mapAOWrap':
  23709. case 'mapAOAnisotropy':
  23710. break;
  23711. case 'mapBump':
  23712. json.bumpMap = loadTexture( value, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  23713. break;
  23714. case 'mapBumpScale':
  23715. json.bumpScale = value;
  23716. break;
  23717. case 'mapBumpRepeat':
  23718. case 'mapBumpOffset':
  23719. case 'mapBumpWrap':
  23720. case 'mapBumpAnisotropy':
  23721. break;
  23722. case 'mapNormal':
  23723. json.normalMap = loadTexture( value, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  23724. break;
  23725. case 'mapNormalFactor':
  23726. json.normalScale = [ value, value ];
  23727. break;
  23728. case 'mapNormalRepeat':
  23729. case 'mapNormalOffset':
  23730. case 'mapNormalWrap':
  23731. case 'mapNormalAnisotropy':
  23732. break;
  23733. case 'mapSpecular':
  23734. json.specularMap = loadTexture( value, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  23735. break;
  23736. case 'mapSpecularRepeat':
  23737. case 'mapSpecularOffset':
  23738. case 'mapSpecularWrap':
  23739. case 'mapSpecularAnisotropy':
  23740. break;
  23741. case 'mapMetalness':
  23742. json.metalnessMap = loadTexture( value, m.mapMetalnessRepeat, m.mapMetalnessOffset, m.mapMetalnessWrap, m.mapMetalnessAnisotropy );
  23743. break;
  23744. case 'mapMetalnessRepeat':
  23745. case 'mapMetalnessOffset':
  23746. case 'mapMetalnessWrap':
  23747. case 'mapMetalnessAnisotropy':
  23748. break;
  23749. case 'mapRoughness':
  23750. json.roughnessMap = loadTexture( value, m.mapRoughnessRepeat, m.mapRoughnessOffset, m.mapRoughnessWrap, m.mapRoughnessAnisotropy );
  23751. break;
  23752. case 'mapRoughnessRepeat':
  23753. case 'mapRoughnessOffset':
  23754. case 'mapRoughnessWrap':
  23755. case 'mapRoughnessAnisotropy':
  23756. break;
  23757. case 'mapAlpha':
  23758. json.alphaMap = loadTexture( value, m.mapAlphaRepeat, m.mapAlphaOffset, m.mapAlphaWrap, m.mapAlphaAnisotropy );
  23759. break;
  23760. case 'mapAlphaRepeat':
  23761. case 'mapAlphaOffset':
  23762. case 'mapAlphaWrap':
  23763. case 'mapAlphaAnisotropy':
  23764. break;
  23765. case 'flipSided':
  23766. json.side = BackSide;
  23767. break;
  23768. case 'doubleSided':
  23769. json.side = DoubleSide;
  23770. break;
  23771. case 'transparency':
  23772. console.warn( 'THREE.Loader.createMaterial: transparency has been renamed to opacity' );
  23773. json.opacity = value;
  23774. break;
  23775. case 'depthTest':
  23776. case 'depthWrite':
  23777. case 'colorWrite':
  23778. case 'opacity':
  23779. case 'reflectivity':
  23780. case 'transparent':
  23781. case 'visible':
  23782. case 'wireframe':
  23783. json[ name ] = value;
  23784. break;
  23785. case 'vertexColors':
  23786. if ( value === true ) json.vertexColors = VertexColors;
  23787. if ( value === 'face' ) json.vertexColors = FaceColors;
  23788. break;
  23789. default:
  23790. console.error( 'THREE.Loader.createMaterial: Unsupported', name, value );
  23791. break;
  23792. }
  23793. }
  23794. if ( json.type === 'MeshBasicMaterial' ) delete json.emissive;
  23795. if ( json.type !== 'MeshPhongMaterial' ) delete json.specular;
  23796. if ( json.opacity < 1 ) json.transparent = true;
  23797. materialLoader.setTextures( textures );
  23798. return materialLoader.parse( json );
  23799. };
  23800. } )()
  23801. };
  23802. Loader.Handlers = {
  23803. handlers: [],
  23804. add: function ( regex, loader ) {
  23805. this.handlers.push( regex, loader );
  23806. },
  23807. get: function ( file ) {
  23808. var handlers = this.handlers;
  23809. for ( var i = 0, l = handlers.length; i < l; i += 2 ) {
  23810. var regex = handlers[ i ];
  23811. var loader = handlers[ i + 1 ];
  23812. if ( regex.test( file ) ) {
  23813. return loader;
  23814. }
  23815. }
  23816. return null;
  23817. }
  23818. };
  23819. /**
  23820. * @author mrdoob / http://mrdoob.com/
  23821. * @author alteredq / http://alteredqualia.com/
  23822. */
  23823. function JSONLoader( manager ) {
  23824. if ( typeof manager === 'boolean' ) {
  23825. console.warn( 'THREE.JSONLoader: showStatus parameter has been removed from constructor.' );
  23826. manager = undefined;
  23827. }
  23828. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  23829. this.withCredentials = false;
  23830. }
  23831. Object.assign( JSONLoader.prototype, {
  23832. load: function( url, onLoad, onProgress, onError ) {
  23833. var scope = this;
  23834. var texturePath = this.texturePath && ( typeof this.texturePath === "string" ) ? this.texturePath : Loader.prototype.extractUrlBase( url );
  23835. var loader = new FileLoader( this.manager );
  23836. loader.setWithCredentials( this.withCredentials );
  23837. loader.load( url, function ( text ) {
  23838. var json = JSON.parse( text );
  23839. var metadata = json.metadata;
  23840. if ( metadata !== undefined ) {
  23841. var type = metadata.type;
  23842. if ( type !== undefined ) {
  23843. if ( type.toLowerCase() === 'object' ) {
  23844. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.ObjectLoader instead.' );
  23845. return;
  23846. }
  23847. if ( type.toLowerCase() === 'scene' ) {
  23848. console.error( 'THREE.JSONLoader: ' + url + ' should be loaded with THREE.SceneLoader instead.' );
  23849. return;
  23850. }
  23851. }
  23852. }
  23853. var object = scope.parse( json, texturePath );
  23854. onLoad( object.geometry, object.materials );
  23855. }, onProgress, onError );
  23856. },
  23857. setTexturePath: function ( value ) {
  23858. this.texturePath = value;
  23859. },
  23860. parse: function ( json, texturePath ) {
  23861. var geometry = new Geometry(),
  23862. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  23863. parseModel( scale );
  23864. parseSkin();
  23865. parseMorphing( scale );
  23866. parseAnimations();
  23867. geometry.computeFaceNormals();
  23868. geometry.computeBoundingSphere();
  23869. function parseModel( scale ) {
  23870. function isBitSet( value, position ) {
  23871. return value & ( 1 << position );
  23872. }
  23873. var i, j, fi,
  23874. offset, zLength,
  23875. colorIndex, normalIndex, uvIndex, materialIndex,
  23876. type,
  23877. isQuad,
  23878. hasMaterial,
  23879. hasFaceVertexUv,
  23880. hasFaceNormal, hasFaceVertexNormal,
  23881. hasFaceColor, hasFaceVertexColor,
  23882. vertex, face, faceA, faceB, hex, normal,
  23883. uvLayer, uv, u, v,
  23884. faces = json.faces,
  23885. vertices = json.vertices,
  23886. normals = json.normals,
  23887. colors = json.colors,
  23888. nUvLayers = 0;
  23889. if ( json.uvs !== undefined ) {
  23890. // disregard empty arrays
  23891. for ( i = 0; i < json.uvs.length; i ++ ) {
  23892. if ( json.uvs[ i ].length ) nUvLayers ++;
  23893. }
  23894. for ( i = 0; i < nUvLayers; i ++ ) {
  23895. geometry.faceVertexUvs[ i ] = [];
  23896. }
  23897. }
  23898. offset = 0;
  23899. zLength = vertices.length;
  23900. while ( offset < zLength ) {
  23901. vertex = new Vector3();
  23902. vertex.x = vertices[ offset ++ ] * scale;
  23903. vertex.y = vertices[ offset ++ ] * scale;
  23904. vertex.z = vertices[ offset ++ ] * scale;
  23905. geometry.vertices.push( vertex );
  23906. }
  23907. offset = 0;
  23908. zLength = faces.length;
  23909. while ( offset < zLength ) {
  23910. type = faces[ offset ++ ];
  23911. isQuad = isBitSet( type, 0 );
  23912. hasMaterial = isBitSet( type, 1 );
  23913. hasFaceVertexUv = isBitSet( type, 3 );
  23914. hasFaceNormal = isBitSet( type, 4 );
  23915. hasFaceVertexNormal = isBitSet( type, 5 );
  23916. hasFaceColor = isBitSet( type, 6 );
  23917. hasFaceVertexColor = isBitSet( type, 7 );
  23918. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  23919. if ( isQuad ) {
  23920. faceA = new Face3();
  23921. faceA.a = faces[ offset ];
  23922. faceA.b = faces[ offset + 1 ];
  23923. faceA.c = faces[ offset + 3 ];
  23924. faceB = new Face3();
  23925. faceB.a = faces[ offset + 1 ];
  23926. faceB.b = faces[ offset + 2 ];
  23927. faceB.c = faces[ offset + 3 ];
  23928. offset += 4;
  23929. if ( hasMaterial ) {
  23930. materialIndex = faces[ offset ++ ];
  23931. faceA.materialIndex = materialIndex;
  23932. faceB.materialIndex = materialIndex;
  23933. }
  23934. // to get face <=> uv index correspondence
  23935. fi = geometry.faces.length;
  23936. if ( hasFaceVertexUv ) {
  23937. for ( i = 0; i < nUvLayers; i ++ ) {
  23938. uvLayer = json.uvs[ i ];
  23939. geometry.faceVertexUvs[ i ][ fi ] = [];
  23940. geometry.faceVertexUvs[ i ][ fi + 1 ] = [];
  23941. for ( j = 0; j < 4; j ++ ) {
  23942. uvIndex = faces[ offset ++ ];
  23943. u = uvLayer[ uvIndex * 2 ];
  23944. v = uvLayer[ uvIndex * 2 + 1 ];
  23945. uv = new Vector2( u, v );
  23946. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  23947. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  23948. }
  23949. }
  23950. }
  23951. if ( hasFaceNormal ) {
  23952. normalIndex = faces[ offset ++ ] * 3;
  23953. faceA.normal.set(
  23954. normals[ normalIndex ++ ],
  23955. normals[ normalIndex ++ ],
  23956. normals[ normalIndex ]
  23957. );
  23958. faceB.normal.copy( faceA.normal );
  23959. }
  23960. if ( hasFaceVertexNormal ) {
  23961. for ( i = 0; i < 4; i ++ ) {
  23962. normalIndex = faces[ offset ++ ] * 3;
  23963. normal = new Vector3(
  23964. normals[ normalIndex ++ ],
  23965. normals[ normalIndex ++ ],
  23966. normals[ normalIndex ]
  23967. );
  23968. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  23969. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  23970. }
  23971. }
  23972. if ( hasFaceColor ) {
  23973. colorIndex = faces[ offset ++ ];
  23974. hex = colors[ colorIndex ];
  23975. faceA.color.setHex( hex );
  23976. faceB.color.setHex( hex );
  23977. }
  23978. if ( hasFaceVertexColor ) {
  23979. for ( i = 0; i < 4; i ++ ) {
  23980. colorIndex = faces[ offset ++ ];
  23981. hex = colors[ colorIndex ];
  23982. if ( i !== 2 ) faceA.vertexColors.push( new Color( hex ) );
  23983. if ( i !== 0 ) faceB.vertexColors.push( new Color( hex ) );
  23984. }
  23985. }
  23986. geometry.faces.push( faceA );
  23987. geometry.faces.push( faceB );
  23988. } else {
  23989. face = new Face3();
  23990. face.a = faces[ offset ++ ];
  23991. face.b = faces[ offset ++ ];
  23992. face.c = faces[ offset ++ ];
  23993. if ( hasMaterial ) {
  23994. materialIndex = faces[ offset ++ ];
  23995. face.materialIndex = materialIndex;
  23996. }
  23997. // to get face <=> uv index correspondence
  23998. fi = geometry.faces.length;
  23999. if ( hasFaceVertexUv ) {
  24000. for ( i = 0; i < nUvLayers; i ++ ) {
  24001. uvLayer = json.uvs[ i ];
  24002. geometry.faceVertexUvs[ i ][ fi ] = [];
  24003. for ( j = 0; j < 3; j ++ ) {
  24004. uvIndex = faces[ offset ++ ];
  24005. u = uvLayer[ uvIndex * 2 ];
  24006. v = uvLayer[ uvIndex * 2 + 1 ];
  24007. uv = new Vector2( u, v );
  24008. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  24009. }
  24010. }
  24011. }
  24012. if ( hasFaceNormal ) {
  24013. normalIndex = faces[ offset ++ ] * 3;
  24014. face.normal.set(
  24015. normals[ normalIndex ++ ],
  24016. normals[ normalIndex ++ ],
  24017. normals[ normalIndex ]
  24018. );
  24019. }
  24020. if ( hasFaceVertexNormal ) {
  24021. for ( i = 0; i < 3; i ++ ) {
  24022. normalIndex = faces[ offset ++ ] * 3;
  24023. normal = new Vector3(
  24024. normals[ normalIndex ++ ],
  24025. normals[ normalIndex ++ ],
  24026. normals[ normalIndex ]
  24027. );
  24028. face.vertexNormals.push( normal );
  24029. }
  24030. }
  24031. if ( hasFaceColor ) {
  24032. colorIndex = faces[ offset ++ ];
  24033. face.color.setHex( colors[ colorIndex ] );
  24034. }
  24035. if ( hasFaceVertexColor ) {
  24036. for ( i = 0; i < 3; i ++ ) {
  24037. colorIndex = faces[ offset ++ ];
  24038. face.vertexColors.push( new Color( colors[ colorIndex ] ) );
  24039. }
  24040. }
  24041. geometry.faces.push( face );
  24042. }
  24043. }
  24044. }
  24045. function parseSkin() {
  24046. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  24047. if ( json.skinWeights ) {
  24048. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  24049. var x = json.skinWeights[ i ];
  24050. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  24051. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  24052. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  24053. geometry.skinWeights.push( new Vector4( x, y, z, w ) );
  24054. }
  24055. }
  24056. if ( json.skinIndices ) {
  24057. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  24058. var a = json.skinIndices[ i ];
  24059. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  24060. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  24061. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  24062. geometry.skinIndices.push( new Vector4( a, b, c, d ) );
  24063. }
  24064. }
  24065. geometry.bones = json.bones;
  24066. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  24067. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  24068. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  24069. }
  24070. }
  24071. function parseMorphing( scale ) {
  24072. if ( json.morphTargets !== undefined ) {
  24073. for ( var i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  24074. geometry.morphTargets[ i ] = {};
  24075. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  24076. geometry.morphTargets[ i ].vertices = [];
  24077. var dstVertices = geometry.morphTargets[ i ].vertices;
  24078. var srcVertices = json.morphTargets[ i ].vertices;
  24079. for ( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  24080. var vertex = new Vector3();
  24081. vertex.x = srcVertices[ v ] * scale;
  24082. vertex.y = srcVertices[ v + 1 ] * scale;
  24083. vertex.z = srcVertices[ v + 2 ] * scale;
  24084. dstVertices.push( vertex );
  24085. }
  24086. }
  24087. }
  24088. if ( json.morphColors !== undefined && json.morphColors.length > 0 ) {
  24089. console.warn( 'THREE.JSONLoader: "morphColors" no longer supported. Using them as face colors.' );
  24090. var faces = geometry.faces;
  24091. var morphColors = json.morphColors[ 0 ].colors;
  24092. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  24093. faces[ i ].color.fromArray( morphColors, i * 3 );
  24094. }
  24095. }
  24096. }
  24097. function parseAnimations() {
  24098. var outputAnimations = [];
  24099. // parse old style Bone/Hierarchy animations
  24100. var animations = [];
  24101. if ( json.animation !== undefined ) {
  24102. animations.push( json.animation );
  24103. }
  24104. if ( json.animations !== undefined ) {
  24105. if ( json.animations.length ) {
  24106. animations = animations.concat( json.animations );
  24107. } else {
  24108. animations.push( json.animations );
  24109. }
  24110. }
  24111. for ( var i = 0; i < animations.length; i ++ ) {
  24112. var clip = AnimationClip.parseAnimation( animations[ i ], geometry.bones );
  24113. if ( clip ) outputAnimations.push( clip );
  24114. }
  24115. // parse implicit morph animations
  24116. if ( geometry.morphTargets ) {
  24117. // TODO: Figure out what an appropraite FPS is for morph target animations -- defaulting to 10, but really it is completely arbitrary.
  24118. var morphAnimationClips = AnimationClip.CreateClipsFromMorphTargetSequences( geometry.morphTargets, 10 );
  24119. outputAnimations = outputAnimations.concat( morphAnimationClips );
  24120. }
  24121. if ( outputAnimations.length > 0 ) geometry.animations = outputAnimations;
  24122. }
  24123. if ( json.materials === undefined || json.materials.length === 0 ) {
  24124. return { geometry: geometry };
  24125. } else {
  24126. var materials = Loader.prototype.initMaterials( json.materials, texturePath, this.crossOrigin );
  24127. return { geometry: geometry, materials: materials };
  24128. }
  24129. }
  24130. } );
  24131. /**
  24132. * @author mrdoob / http://mrdoob.com/
  24133. */
  24134. function ObjectLoader( manager ) {
  24135. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  24136. this.texturePath = '';
  24137. }
  24138. Object.assign( ObjectLoader.prototype, {
  24139. load: function ( url, onLoad, onProgress, onError ) {
  24140. if ( this.texturePath === '' ) {
  24141. this.texturePath = url.substring( 0, url.lastIndexOf( '/' ) + 1 );
  24142. }
  24143. var scope = this;
  24144. var loader = new FileLoader( scope.manager );
  24145. loader.load( url, function ( text ) {
  24146. var json = null;
  24147. try {
  24148. json = JSON.parse( text );
  24149. } catch ( error ) {
  24150. console.error( 'THREE:ObjectLoader: Can\'t parse ' + url + '.', error.message );
  24151. return;
  24152. }
  24153. var metadata = json.metadata;
  24154. if ( metadata === undefined || metadata.type === undefined || metadata.type.toLowerCase() === 'geometry' ) {
  24155. console.error( 'THREE.ObjectLoader: Can\'t load ' + url + '. Use THREE.JSONLoader instead.' );
  24156. return;
  24157. }
  24158. scope.parse( json, onLoad );
  24159. }, onProgress, onError );
  24160. },
  24161. setTexturePath: function ( value ) {
  24162. this.texturePath = value;
  24163. },
  24164. setCrossOrigin: function ( value ) {
  24165. this.crossOrigin = value;
  24166. },
  24167. parse: function ( json, onLoad ) {
  24168. var geometries = this.parseGeometries( json.geometries );
  24169. var images = this.parseImages( json.images, function () {
  24170. if ( onLoad !== undefined ) onLoad( object );
  24171. } );
  24172. var textures = this.parseTextures( json.textures, images );
  24173. var materials = this.parseMaterials( json.materials, textures );
  24174. var object = this.parseObject( json.object, geometries, materials );
  24175. if ( json.animations ) {
  24176. object.animations = this.parseAnimations( json.animations );
  24177. }
  24178. if ( json.images === undefined || json.images.length === 0 ) {
  24179. if ( onLoad !== undefined ) onLoad( object );
  24180. }
  24181. return object;
  24182. },
  24183. parseGeometries: function ( json ) {
  24184. var geometries = {};
  24185. if ( json !== undefined ) {
  24186. var geometryLoader = new JSONLoader();
  24187. var bufferGeometryLoader = new BufferGeometryLoader();
  24188. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24189. var geometry;
  24190. var data = json[ i ];
  24191. switch ( data.type ) {
  24192. case 'PlaneGeometry':
  24193. case 'PlaneBufferGeometry':
  24194. geometry = new Geometries[ data.type ](
  24195. data.width,
  24196. data.height,
  24197. data.widthSegments,
  24198. data.heightSegments
  24199. );
  24200. break;
  24201. case 'BoxGeometry':
  24202. case 'BoxBufferGeometry':
  24203. case 'CubeGeometry': // backwards compatible
  24204. geometry = new Geometries[ data.type ](
  24205. data.width,
  24206. data.height,
  24207. data.depth,
  24208. data.widthSegments,
  24209. data.heightSegments,
  24210. data.depthSegments
  24211. );
  24212. break;
  24213. case 'CircleGeometry':
  24214. case 'CircleBufferGeometry':
  24215. geometry = new Geometries[ data.type ](
  24216. data.radius,
  24217. data.segments,
  24218. data.thetaStart,
  24219. data.thetaLength
  24220. );
  24221. break;
  24222. case 'CylinderGeometry':
  24223. case 'CylinderBufferGeometry':
  24224. geometry = new Geometries[ data.type ](
  24225. data.radiusTop,
  24226. data.radiusBottom,
  24227. data.height,
  24228. data.radialSegments,
  24229. data.heightSegments,
  24230. data.openEnded,
  24231. data.thetaStart,
  24232. data.thetaLength
  24233. );
  24234. break;
  24235. case 'ConeGeometry':
  24236. case 'ConeBufferGeometry':
  24237. geometry = new Geometries[ data.type ](
  24238. data.radius,
  24239. data.height,
  24240. data.radialSegments,
  24241. data.heightSegments,
  24242. data.openEnded,
  24243. data.thetaStart,
  24244. data.thetaLength
  24245. );
  24246. break;
  24247. case 'SphereGeometry':
  24248. case 'SphereBufferGeometry':
  24249. geometry = new Geometries[ data.type ](
  24250. data.radius,
  24251. data.widthSegments,
  24252. data.heightSegments,
  24253. data.phiStart,
  24254. data.phiLength,
  24255. data.thetaStart,
  24256. data.thetaLength
  24257. );
  24258. break;
  24259. case 'DodecahedronGeometry':
  24260. case 'IcosahedronGeometry':
  24261. case 'OctahedronGeometry':
  24262. case 'TetrahedronGeometry':
  24263. geometry = new Geometries[ data.type ](
  24264. data.radius,
  24265. data.detail
  24266. );
  24267. break;
  24268. case 'RingGeometry':
  24269. case 'RingBufferGeometry':
  24270. geometry = new Geometries[ data.type ](
  24271. data.innerRadius,
  24272. data.outerRadius,
  24273. data.thetaSegments,
  24274. data.phiSegments,
  24275. data.thetaStart,
  24276. data.thetaLength
  24277. );
  24278. break;
  24279. case 'TorusGeometry':
  24280. case 'TorusBufferGeometry':
  24281. geometry = new Geometries[ data.type ](
  24282. data.radius,
  24283. data.tube,
  24284. data.radialSegments,
  24285. data.tubularSegments,
  24286. data.arc
  24287. );
  24288. break;
  24289. case 'TorusKnotGeometry':
  24290. case 'TorusKnotBufferGeometry':
  24291. geometry = new Geometries[ data.type ](
  24292. data.radius,
  24293. data.tube,
  24294. data.tubularSegments,
  24295. data.radialSegments,
  24296. data.p,
  24297. data.q
  24298. );
  24299. break;
  24300. case 'LatheGeometry':
  24301. case 'LatheBufferGeometry':
  24302. geometry = new Geometries[ data.type ](
  24303. data.points,
  24304. data.segments,
  24305. data.phiStart,
  24306. data.phiLength
  24307. );
  24308. break;
  24309. case 'BufferGeometry':
  24310. geometry = bufferGeometryLoader.parse( data );
  24311. break;
  24312. case 'Geometry':
  24313. geometry = geometryLoader.parse( data.data, this.texturePath ).geometry;
  24314. break;
  24315. default:
  24316. console.warn( 'THREE.ObjectLoader: Unsupported geometry type "' + data.type + '"' );
  24317. continue;
  24318. }
  24319. geometry.uuid = data.uuid;
  24320. if ( data.name !== undefined ) geometry.name = data.name;
  24321. geometries[ data.uuid ] = geometry;
  24322. }
  24323. }
  24324. return geometries;
  24325. },
  24326. parseMaterials: function ( json, textures ) {
  24327. var materials = {};
  24328. if ( json !== undefined ) {
  24329. var loader = new MaterialLoader();
  24330. loader.setTextures( textures );
  24331. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24332. var material = loader.parse( json[ i ] );
  24333. materials[ material.uuid ] = material;
  24334. }
  24335. }
  24336. return materials;
  24337. },
  24338. parseAnimations: function ( json ) {
  24339. var animations = [];
  24340. for ( var i = 0; i < json.length; i ++ ) {
  24341. var clip = AnimationClip.parse( json[ i ] );
  24342. animations.push( clip );
  24343. }
  24344. return animations;
  24345. },
  24346. parseImages: function ( json, onLoad ) {
  24347. var scope = this;
  24348. var images = {};
  24349. function loadImage( url ) {
  24350. scope.manager.itemStart( url );
  24351. return loader.load( url, function () {
  24352. scope.manager.itemEnd( url );
  24353. }, undefined, function () {
  24354. scope.manager.itemError( url );
  24355. } );
  24356. }
  24357. if ( json !== undefined && json.length > 0 ) {
  24358. var manager = new LoadingManager( onLoad );
  24359. var loader = new ImageLoader( manager );
  24360. loader.setCrossOrigin( this.crossOrigin );
  24361. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24362. var image = json[ i ];
  24363. var path = /^(\/\/)|([a-z]+:(\/\/)?)/i.test( image.url ) ? image.url : scope.texturePath + image.url;
  24364. images[ image.uuid ] = loadImage( path );
  24365. }
  24366. }
  24367. return images;
  24368. },
  24369. parseTextures: function ( json, images ) {
  24370. function parseConstant( value, type ) {
  24371. if ( typeof( value ) === 'number' ) return value;
  24372. console.warn( 'THREE.ObjectLoader.parseTexture: Constant should be in numeric form.', value );
  24373. return type[ value ];
  24374. }
  24375. var textures = {};
  24376. if ( json !== undefined ) {
  24377. for ( var i = 0, l = json.length; i < l; i ++ ) {
  24378. var data = json[ i ];
  24379. if ( data.image === undefined ) {
  24380. console.warn( 'THREE.ObjectLoader: No "image" specified for', data.uuid );
  24381. }
  24382. if ( images[ data.image ] === undefined ) {
  24383. console.warn( 'THREE.ObjectLoader: Undefined image', data.image );
  24384. }
  24385. var texture = new Texture( images[ data.image ] );
  24386. texture.needsUpdate = true;
  24387. texture.uuid = data.uuid;
  24388. if ( data.name !== undefined ) texture.name = data.name;
  24389. if ( data.mapping !== undefined ) texture.mapping = parseConstant( data.mapping, TextureMapping );
  24390. if ( data.offset !== undefined ) texture.offset.fromArray( data.offset );
  24391. if ( data.repeat !== undefined ) texture.repeat.fromArray( data.repeat );
  24392. if ( data.wrap !== undefined ) {
  24393. texture.wrapS = parseConstant( data.wrap[ 0 ], TextureWrapping );
  24394. texture.wrapT = parseConstant( data.wrap[ 1 ], TextureWrapping );
  24395. }
  24396. if ( data.minFilter !== undefined ) texture.minFilter = parseConstant( data.minFilter, TextureFilter );
  24397. if ( data.magFilter !== undefined ) texture.magFilter = parseConstant( data.magFilter, TextureFilter );
  24398. if ( data.anisotropy !== undefined ) texture.anisotropy = data.anisotropy;
  24399. if ( data.flipY !== undefined ) texture.flipY = data.flipY;
  24400. textures[ data.uuid ] = texture;
  24401. }
  24402. }
  24403. return textures;
  24404. },
  24405. parseObject: function () {
  24406. var matrix = new Matrix4();
  24407. return function parseObject( data, geometries, materials ) {
  24408. var object;
  24409. function getGeometry( name ) {
  24410. if ( geometries[ name ] === undefined ) {
  24411. console.warn( 'THREE.ObjectLoader: Undefined geometry', name );
  24412. }
  24413. return geometries[ name ];
  24414. }
  24415. function getMaterial( name ) {
  24416. if ( name === undefined ) return undefined;
  24417. if ( materials[ name ] === undefined ) {
  24418. console.warn( 'THREE.ObjectLoader: Undefined material', name );
  24419. }
  24420. return materials[ name ];
  24421. }
  24422. switch ( data.type ) {
  24423. case 'Scene':
  24424. object = new Scene();
  24425. if ( data.background !== undefined ) {
  24426. if ( Number.isInteger( data.background ) ) {
  24427. object.background = new Color( data.background );
  24428. }
  24429. }
  24430. if ( data.fog !== undefined ) {
  24431. if ( data.fog.type === 'Fog' ) {
  24432. object.fog = new Fog( data.fog.color, data.fog.near, data.fog.far );
  24433. } else if ( data.fog.type === 'FogExp2' ) {
  24434. object.fog = new FogExp2( data.fog.color, data.fog.density );
  24435. }
  24436. }
  24437. break;
  24438. case 'PerspectiveCamera':
  24439. object = new PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  24440. if ( data.focus !== undefined ) object.focus = data.focus;
  24441. if ( data.zoom !== undefined ) object.zoom = data.zoom;
  24442. if ( data.filmGauge !== undefined ) object.filmGauge = data.filmGauge;
  24443. if ( data.filmOffset !== undefined ) object.filmOffset = data.filmOffset;
  24444. if ( data.view !== undefined ) object.view = Object.assign( {}, data.view );
  24445. break;
  24446. case 'OrthographicCamera':
  24447. object = new OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  24448. break;
  24449. case 'AmbientLight':
  24450. object = new AmbientLight( data.color, data.intensity );
  24451. break;
  24452. case 'DirectionalLight':
  24453. object = new DirectionalLight( data.color, data.intensity );
  24454. break;
  24455. case 'PointLight':
  24456. object = new PointLight( data.color, data.intensity, data.distance, data.decay );
  24457. break;
  24458. case 'SpotLight':
  24459. object = new SpotLight( data.color, data.intensity, data.distance, data.angle, data.penumbra, data.decay );
  24460. break;
  24461. case 'HemisphereLight':
  24462. object = new HemisphereLight( data.color, data.groundColor, data.intensity );
  24463. break;
  24464. case 'Mesh':
  24465. var geometry = getGeometry( data.geometry );
  24466. var material = getMaterial( data.material );
  24467. if ( geometry.bones && geometry.bones.length > 0 ) {
  24468. object = new SkinnedMesh( geometry, material );
  24469. } else {
  24470. object = new Mesh( geometry, material );
  24471. }
  24472. break;
  24473. case 'LOD':
  24474. object = new LOD();
  24475. break;
  24476. case 'Line':
  24477. object = new Line( getGeometry( data.geometry ), getMaterial( data.material ), data.mode );
  24478. break;
  24479. case 'LineSegments':
  24480. object = new LineSegments( getGeometry( data.geometry ), getMaterial( data.material ) );
  24481. break;
  24482. case 'PointCloud':
  24483. case 'Points':
  24484. object = new Points( getGeometry( data.geometry ), getMaterial( data.material ) );
  24485. break;
  24486. case 'Sprite':
  24487. object = new Sprite( getMaterial( data.material ) );
  24488. break;
  24489. case 'Group':
  24490. object = new Group();
  24491. break;
  24492. case 'SkinnedMesh':
  24493. console.warn( 'THREE.ObjectLoader.parseObject() does not support SkinnedMesh type. Instantiates Object3D instead.' );
  24494. default:
  24495. object = new Object3D();
  24496. }
  24497. object.uuid = data.uuid;
  24498. if ( data.name !== undefined ) object.name = data.name;
  24499. if ( data.matrix !== undefined ) {
  24500. matrix.fromArray( data.matrix );
  24501. matrix.decompose( object.position, object.quaternion, object.scale );
  24502. } else {
  24503. if ( data.position !== undefined ) object.position.fromArray( data.position );
  24504. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  24505. if ( data.quaternion !== undefined ) object.quaternion.fromArray( data.quaternion );
  24506. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  24507. }
  24508. if ( data.castShadow !== undefined ) object.castShadow = data.castShadow;
  24509. if ( data.receiveShadow !== undefined ) object.receiveShadow = data.receiveShadow;
  24510. if ( data.shadow ) {
  24511. if ( data.shadow.bias !== undefined ) object.shadow.bias = data.shadow.bias;
  24512. if ( data.shadow.radius !== undefined ) object.shadow.radius = data.shadow.radius;
  24513. if ( data.shadow.mapSize !== undefined ) object.shadow.mapSize.fromArray( data.shadow.mapSize );
  24514. if ( data.shadow.camera !== undefined ) object.shadow.camera = this.parseObject( data.shadow.camera );
  24515. }
  24516. if ( data.visible !== undefined ) object.visible = data.visible;
  24517. if ( data.userData !== undefined ) object.userData = data.userData;
  24518. if ( data.children !== undefined ) {
  24519. for ( var child in data.children ) {
  24520. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  24521. }
  24522. }
  24523. if ( data.type === 'LOD' ) {
  24524. var levels = data.levels;
  24525. for ( var l = 0; l < levels.length; l ++ ) {
  24526. var level = levels[ l ];
  24527. var child = object.getObjectByProperty( 'uuid', level.object );
  24528. if ( child !== undefined ) {
  24529. object.addLevel( child, level.distance );
  24530. }
  24531. }
  24532. }
  24533. return object;
  24534. };
  24535. }()
  24536. } );
  24537. /**
  24538. * @author zz85 / http://www.lab4games.net/zz85/blog
  24539. * Extensible curve object
  24540. *
  24541. * Some common of Curve methods
  24542. * .getPoint(t), getTangent(t)
  24543. * .getPointAt(u), getTangentAt(u)
  24544. * .getPoints(), .getSpacedPoints()
  24545. * .getLength()
  24546. * .updateArcLengths()
  24547. *
  24548. * This following classes subclasses THREE.Curve:
  24549. *
  24550. * -- 2d classes --
  24551. * THREE.LineCurve
  24552. * THREE.QuadraticBezierCurve
  24553. * THREE.CubicBezierCurve
  24554. * THREE.SplineCurve
  24555. * THREE.ArcCurve
  24556. * THREE.EllipseCurve
  24557. *
  24558. * -- 3d classes --
  24559. * THREE.LineCurve3
  24560. * THREE.QuadraticBezierCurve3
  24561. * THREE.CubicBezierCurve3
  24562. * THREE.SplineCurve3
  24563. *
  24564. * A series of curves can be represented as a THREE.CurvePath
  24565. *
  24566. **/
  24567. /**************************************************************
  24568. * Abstract Curve base class
  24569. **************************************************************/
  24570. function Curve() {}
  24571. Curve.prototype = {
  24572. constructor: Curve,
  24573. // Virtual base class method to overwrite and implement in subclasses
  24574. // - t [0 .. 1]
  24575. getPoint: function ( t ) {
  24576. console.warn( "THREE.Curve: Warning, getPoint() not implemented!" );
  24577. return null;
  24578. },
  24579. // Get point at relative position in curve according to arc length
  24580. // - u [0 .. 1]
  24581. getPointAt: function ( u ) {
  24582. var t = this.getUtoTmapping( u );
  24583. return this.getPoint( t );
  24584. },
  24585. // Get sequence of points using getPoint( t )
  24586. getPoints: function ( divisions ) {
  24587. if ( ! divisions ) divisions = 5;
  24588. var points = [];
  24589. for ( var d = 0; d <= divisions; d ++ ) {
  24590. points.push( this.getPoint( d / divisions ) );
  24591. }
  24592. return points;
  24593. },
  24594. // Get sequence of points using getPointAt( u )
  24595. getSpacedPoints: function ( divisions ) {
  24596. if ( ! divisions ) divisions = 5;
  24597. var points = [];
  24598. for ( var d = 0; d <= divisions; d ++ ) {
  24599. points.push( this.getPointAt( d / divisions ) );
  24600. }
  24601. return points;
  24602. },
  24603. // Get total curve arc length
  24604. getLength: function () {
  24605. var lengths = this.getLengths();
  24606. return lengths[ lengths.length - 1 ];
  24607. },
  24608. // Get list of cumulative segment lengths
  24609. getLengths: function ( divisions ) {
  24610. if ( ! divisions ) divisions = ( this.__arcLengthDivisions ) ? ( this.__arcLengthDivisions ) : 200;
  24611. if ( this.cacheArcLengths
  24612. && ( this.cacheArcLengths.length === divisions + 1 )
  24613. && ! this.needsUpdate ) {
  24614. //console.log( "cached", this.cacheArcLengths );
  24615. return this.cacheArcLengths;
  24616. }
  24617. this.needsUpdate = false;
  24618. var cache = [];
  24619. var current, last = this.getPoint( 0 );
  24620. var p, sum = 0;
  24621. cache.push( 0 );
  24622. for ( p = 1; p <= divisions; p ++ ) {
  24623. current = this.getPoint ( p / divisions );
  24624. sum += current.distanceTo( last );
  24625. cache.push( sum );
  24626. last = current;
  24627. }
  24628. this.cacheArcLengths = cache;
  24629. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  24630. },
  24631. updateArcLengths: function() {
  24632. this.needsUpdate = true;
  24633. this.getLengths();
  24634. },
  24635. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equidistant
  24636. getUtoTmapping: function ( u, distance ) {
  24637. var arcLengths = this.getLengths();
  24638. var i = 0, il = arcLengths.length;
  24639. var targetArcLength; // The targeted u distance value to get
  24640. if ( distance ) {
  24641. targetArcLength = distance;
  24642. } else {
  24643. targetArcLength = u * arcLengths[ il - 1 ];
  24644. }
  24645. //var time = Date.now();
  24646. // binary search for the index with largest value smaller than target u distance
  24647. var low = 0, high = il - 1, comparison;
  24648. while ( low <= high ) {
  24649. 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
  24650. comparison = arcLengths[ i ] - targetArcLength;
  24651. if ( comparison < 0 ) {
  24652. low = i + 1;
  24653. } else if ( comparison > 0 ) {
  24654. high = i - 1;
  24655. } else {
  24656. high = i;
  24657. break;
  24658. // DONE
  24659. }
  24660. }
  24661. i = high;
  24662. //console.log('b' , i, low, high, Date.now()- time);
  24663. if ( arcLengths[ i ] === targetArcLength ) {
  24664. var t = i / ( il - 1 );
  24665. return t;
  24666. }
  24667. // we could get finer grain at lengths, or use simple interpolation between two points
  24668. var lengthBefore = arcLengths[ i ];
  24669. var lengthAfter = arcLengths[ i + 1 ];
  24670. var segmentLength = lengthAfter - lengthBefore;
  24671. // determine where we are between the 'before' and 'after' points
  24672. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  24673. // add that fractional amount to t
  24674. var t = ( i + segmentFraction ) / ( il - 1 );
  24675. return t;
  24676. },
  24677. // Returns a unit vector tangent at t
  24678. // In case any sub curve does not implement its tangent derivation,
  24679. // 2 points a small delta apart will be used to find its gradient
  24680. // which seems to give a reasonable approximation
  24681. getTangent: function( t ) {
  24682. var delta = 0.0001;
  24683. var t1 = t - delta;
  24684. var t2 = t + delta;
  24685. // Capping in case of danger
  24686. if ( t1 < 0 ) t1 = 0;
  24687. if ( t2 > 1 ) t2 = 1;
  24688. var pt1 = this.getPoint( t1 );
  24689. var pt2 = this.getPoint( t2 );
  24690. var vec = pt2.clone().sub( pt1 );
  24691. return vec.normalize();
  24692. },
  24693. getTangentAt: function ( u ) {
  24694. var t = this.getUtoTmapping( u );
  24695. return this.getTangent( t );
  24696. },
  24697. computeFrenetFrames: function ( segments, closed ) {
  24698. // see http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  24699. var normal = new Vector3();
  24700. var tangents = [];
  24701. var normals = [];
  24702. var binormals = [];
  24703. var vec = new Vector3();
  24704. var mat = new Matrix4();
  24705. var i, u, theta;
  24706. // compute the tangent vectors for each segment on the curve
  24707. for ( i = 0; i <= segments; i ++ ) {
  24708. u = i / segments;
  24709. tangents[ i ] = this.getTangentAt( u );
  24710. tangents[ i ].normalize();
  24711. }
  24712. // select an initial normal vector perpendicular to the first tangent vector,
  24713. // and in the direction of the minimum tangent xyz component
  24714. normals[ 0 ] = new Vector3();
  24715. binormals[ 0 ] = new Vector3();
  24716. var min = Number.MAX_VALUE;
  24717. var tx = Math.abs( tangents[ 0 ].x );
  24718. var ty = Math.abs( tangents[ 0 ].y );
  24719. var tz = Math.abs( tangents[ 0 ].z );
  24720. if ( tx <= min ) {
  24721. min = tx;
  24722. normal.set( 1, 0, 0 );
  24723. }
  24724. if ( ty <= min ) {
  24725. min = ty;
  24726. normal.set( 0, 1, 0 );
  24727. }
  24728. if ( tz <= min ) {
  24729. normal.set( 0, 0, 1 );
  24730. }
  24731. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  24732. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  24733. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  24734. // compute the slowly-varying normal and binormal vectors for each segment on the curve
  24735. for ( i = 1; i <= segments; i ++ ) {
  24736. normals[ i ] = normals[ i - 1 ].clone();
  24737. binormals[ i ] = binormals[ i - 1 ].clone();
  24738. vec.crossVectors( tangents[ i - 1 ], tangents[ i ] );
  24739. if ( vec.length() > Number.EPSILON ) {
  24740. vec.normalize();
  24741. theta = Math.acos( _Math.clamp( tangents[ i - 1 ].dot( tangents[ i ] ), - 1, 1 ) ); // clamp for floating pt errors
  24742. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  24743. }
  24744. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24745. }
  24746. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  24747. if ( closed === true ) {
  24748. theta = Math.acos( _Math.clamp( normals[ 0 ].dot( normals[ segments ] ), - 1, 1 ) );
  24749. theta /= segments;
  24750. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ segments ] ) ) > 0 ) {
  24751. theta = - theta;
  24752. }
  24753. for ( i = 1; i <= segments; i ++ ) {
  24754. // twist a little...
  24755. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  24756. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  24757. }
  24758. }
  24759. return {
  24760. tangents: tangents,
  24761. normals: normals,
  24762. binormals: binormals
  24763. };
  24764. }
  24765. };
  24766. // TODO: Transformation for Curves?
  24767. /**************************************************************
  24768. * 3D Curves
  24769. **************************************************************/
  24770. // A Factory method for creating new curve subclasses
  24771. Curve.create = function ( constructor, getPointFunc ) {
  24772. constructor.prototype = Object.create( Curve.prototype );
  24773. constructor.prototype.constructor = constructor;
  24774. constructor.prototype.getPoint = getPointFunc;
  24775. return constructor;
  24776. };
  24777. /**************************************************************
  24778. * Line
  24779. **************************************************************/
  24780. function LineCurve( v1, v2 ) {
  24781. this.v1 = v1;
  24782. this.v2 = v2;
  24783. }
  24784. LineCurve.prototype = Object.create( Curve.prototype );
  24785. LineCurve.prototype.constructor = LineCurve;
  24786. LineCurve.prototype.isLineCurve = true;
  24787. LineCurve.prototype.getPoint = function ( t ) {
  24788. if ( t === 1 ) {
  24789. return this.v2.clone();
  24790. }
  24791. var point = this.v2.clone().sub( this.v1 );
  24792. point.multiplyScalar( t ).add( this.v1 );
  24793. return point;
  24794. };
  24795. // Line curve is linear, so we can overwrite default getPointAt
  24796. LineCurve.prototype.getPointAt = function ( u ) {
  24797. return this.getPoint( u );
  24798. };
  24799. LineCurve.prototype.getTangent = function( t ) {
  24800. var tangent = this.v2.clone().sub( this.v1 );
  24801. return tangent.normalize();
  24802. };
  24803. /**
  24804. * @author zz85 / http://www.lab4games.net/zz85/blog
  24805. *
  24806. **/
  24807. /**************************************************************
  24808. * Curved Path - a curve path is simply a array of connected
  24809. * curves, but retains the api of a curve
  24810. **************************************************************/
  24811. function CurvePath() {
  24812. this.curves = [];
  24813. this.autoClose = false; // Automatically closes the path
  24814. }
  24815. CurvePath.prototype = Object.assign( Object.create( Curve.prototype ), {
  24816. constructor: CurvePath,
  24817. add: function ( curve ) {
  24818. this.curves.push( curve );
  24819. },
  24820. closePath: function () {
  24821. // Add a line curve if start and end of lines are not connected
  24822. var startPoint = this.curves[ 0 ].getPoint( 0 );
  24823. var endPoint = this.curves[ this.curves.length - 1 ].getPoint( 1 );
  24824. if ( ! startPoint.equals( endPoint ) ) {
  24825. this.curves.push( new LineCurve( endPoint, startPoint ) );
  24826. }
  24827. },
  24828. // To get accurate point with reference to
  24829. // entire path distance at time t,
  24830. // following has to be done:
  24831. // 1. Length of each sub path have to be known
  24832. // 2. Locate and identify type of curve
  24833. // 3. Get t for the curve
  24834. // 4. Return curve.getPointAt(t')
  24835. getPoint: function ( t ) {
  24836. var d = t * this.getLength();
  24837. var curveLengths = this.getCurveLengths();
  24838. var i = 0;
  24839. // To think about boundaries points.
  24840. while ( i < curveLengths.length ) {
  24841. if ( curveLengths[ i ] >= d ) {
  24842. var diff = curveLengths[ i ] - d;
  24843. var curve = this.curves[ i ];
  24844. var segmentLength = curve.getLength();
  24845. var u = segmentLength === 0 ? 0 : 1 - diff / segmentLength;
  24846. return curve.getPointAt( u );
  24847. }
  24848. i ++;
  24849. }
  24850. return null;
  24851. // loop where sum != 0, sum > d , sum+1 <d
  24852. },
  24853. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  24854. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  24855. // getPoint() depends on getLength
  24856. getLength: function () {
  24857. var lens = this.getCurveLengths();
  24858. return lens[ lens.length - 1 ];
  24859. },
  24860. // cacheLengths must be recalculated.
  24861. updateArcLengths: function () {
  24862. this.needsUpdate = true;
  24863. this.cacheLengths = null;
  24864. this.getLengths();
  24865. },
  24866. // Compute lengths and cache them
  24867. // We cannot overwrite getLengths() because UtoT mapping uses it.
  24868. getCurveLengths: function () {
  24869. // We use cache values if curves and cache array are same length
  24870. if ( this.cacheLengths && this.cacheLengths.length === this.curves.length ) {
  24871. return this.cacheLengths;
  24872. }
  24873. // Get length of sub-curve
  24874. // Push sums into cached array
  24875. var lengths = [], sums = 0;
  24876. for ( var i = 0, l = this.curves.length; i < l; i ++ ) {
  24877. sums += this.curves[ i ].getLength();
  24878. lengths.push( sums );
  24879. }
  24880. this.cacheLengths = lengths;
  24881. return lengths;
  24882. },
  24883. getSpacedPoints: function ( divisions ) {
  24884. if ( ! divisions ) divisions = 40;
  24885. var points = [];
  24886. for ( var i = 0; i <= divisions; i ++ ) {
  24887. points.push( this.getPoint( i / divisions ) );
  24888. }
  24889. if ( this.autoClose ) {
  24890. points.push( points[ 0 ] );
  24891. }
  24892. return points;
  24893. },
  24894. getPoints: function ( divisions ) {
  24895. divisions = divisions || 12;
  24896. var points = [], last;
  24897. for ( var i = 0, curves = this.curves; i < curves.length; i ++ ) {
  24898. var curve = curves[ i ];
  24899. var resolution = (curve && curve.isEllipseCurve) ? divisions * 2
  24900. : (curve && curve.isLineCurve) ? 1
  24901. : (curve && curve.isSplineCurve) ? divisions * curve.points.length
  24902. : divisions;
  24903. var pts = curve.getPoints( resolution );
  24904. for ( var j = 0; j < pts.length; j++ ) {
  24905. var point = pts[ j ];
  24906. if ( last && last.equals( point ) ) continue; // ensures no consecutive points are duplicates
  24907. points.push( point );
  24908. last = point;
  24909. }
  24910. }
  24911. if ( this.autoClose && points.length > 1 && !points[ points.length - 1 ].equals( points[ 0 ] ) ) {
  24912. points.push( points[ 0 ] );
  24913. }
  24914. return points;
  24915. },
  24916. /**************************************************************
  24917. * Create Geometries Helpers
  24918. **************************************************************/
  24919. /// Generate geometry from path points (for Line or Points objects)
  24920. createPointsGeometry: function ( divisions ) {
  24921. var pts = this.getPoints( divisions );
  24922. return this.createGeometry( pts );
  24923. },
  24924. // Generate geometry from equidistant sampling along the path
  24925. createSpacedPointsGeometry: function ( divisions ) {
  24926. var pts = this.getSpacedPoints( divisions );
  24927. return this.createGeometry( pts );
  24928. },
  24929. createGeometry: function ( points ) {
  24930. var geometry = new Geometry();
  24931. for ( var i = 0, l = points.length; i < l; i ++ ) {
  24932. var point = points[ i ];
  24933. geometry.vertices.push( new Vector3( point.x, point.y, point.z || 0 ) );
  24934. }
  24935. return geometry;
  24936. }
  24937. } );
  24938. /**************************************************************
  24939. * Ellipse curve
  24940. **************************************************************/
  24941. function EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  24942. this.aX = aX;
  24943. this.aY = aY;
  24944. this.xRadius = xRadius;
  24945. this.yRadius = yRadius;
  24946. this.aStartAngle = aStartAngle;
  24947. this.aEndAngle = aEndAngle;
  24948. this.aClockwise = aClockwise;
  24949. this.aRotation = aRotation || 0;
  24950. }
  24951. EllipseCurve.prototype = Object.create( Curve.prototype );
  24952. EllipseCurve.prototype.constructor = EllipseCurve;
  24953. EllipseCurve.prototype.isEllipseCurve = true;
  24954. EllipseCurve.prototype.getPoint = function( t ) {
  24955. var twoPi = Math.PI * 2;
  24956. var deltaAngle = this.aEndAngle - this.aStartAngle;
  24957. var samePoints = Math.abs( deltaAngle ) < Number.EPSILON;
  24958. // ensures that deltaAngle is 0 .. 2 PI
  24959. while ( deltaAngle < 0 ) deltaAngle += twoPi;
  24960. while ( deltaAngle > twoPi ) deltaAngle -= twoPi;
  24961. if ( deltaAngle < Number.EPSILON ) {
  24962. if ( samePoints ) {
  24963. deltaAngle = 0;
  24964. } else {
  24965. deltaAngle = twoPi;
  24966. }
  24967. }
  24968. if ( this.aClockwise === true && ! samePoints ) {
  24969. if ( deltaAngle === twoPi ) {
  24970. deltaAngle = - twoPi;
  24971. } else {
  24972. deltaAngle = deltaAngle - twoPi;
  24973. }
  24974. }
  24975. var angle = this.aStartAngle + t * deltaAngle;
  24976. var x = this.aX + this.xRadius * Math.cos( angle );
  24977. var y = this.aY + this.yRadius * Math.sin( angle );
  24978. if ( this.aRotation !== 0 ) {
  24979. var cos = Math.cos( this.aRotation );
  24980. var sin = Math.sin( this.aRotation );
  24981. var tx = x - this.aX;
  24982. var ty = y - this.aY;
  24983. // Rotate the point about the center of the ellipse.
  24984. x = tx * cos - ty * sin + this.aX;
  24985. y = tx * sin + ty * cos + this.aY;
  24986. }
  24987. return new Vector2( x, y );
  24988. };
  24989. /**
  24990. * @author zz85 / http://www.lab4games.net/zz85/blog
  24991. */
  24992. var CurveUtils = {
  24993. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  24994. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  24995. },
  24996. // Puay Bing, thanks for helping with this derivative!
  24997. tangentCubicBezier: function ( t, p0, p1, p2, p3 ) {
  24998. return - 3 * p0 * ( 1 - t ) * ( 1 - t ) +
  24999. 3 * p1 * ( 1 - t ) * ( 1 - t ) - 6 * t * p1 * ( 1 - t ) +
  25000. 6 * t * p2 * ( 1 - t ) - 3 * t * t * p2 +
  25001. 3 * t * t * p3;
  25002. },
  25003. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  25004. // To check if my formulas are correct
  25005. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  25006. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  25007. var h01 = - 6 * t * t + 6 * t; // − 2t3 + 3t2
  25008. var h11 = 3 * t * t - 2 * t; // t3 − t2
  25009. return h00 + h10 + h01 + h11;
  25010. },
  25011. // Catmull-Rom
  25012. interpolate: function( p0, p1, p2, p3, t ) {
  25013. var v0 = ( p2 - p0 ) * 0.5;
  25014. var v1 = ( p3 - p1 ) * 0.5;
  25015. var t2 = t * t;
  25016. var t3 = t * t2;
  25017. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  25018. }
  25019. };
  25020. /**************************************************************
  25021. * Spline curve
  25022. **************************************************************/
  25023. function SplineCurve( points /* array of Vector2 */ ) {
  25024. this.points = ( points === undefined ) ? [] : points;
  25025. }
  25026. SplineCurve.prototype = Object.create( Curve.prototype );
  25027. SplineCurve.prototype.constructor = SplineCurve;
  25028. SplineCurve.prototype.isSplineCurve = true;
  25029. SplineCurve.prototype.getPoint = function ( t ) {
  25030. var points = this.points;
  25031. var point = ( points.length - 1 ) * t;
  25032. var intPoint = Math.floor( point );
  25033. var weight = point - intPoint;
  25034. var point0 = points[ intPoint === 0 ? intPoint : intPoint - 1 ];
  25035. var point1 = points[ intPoint ];
  25036. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  25037. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  25038. var interpolate = CurveUtils.interpolate;
  25039. return new Vector2(
  25040. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  25041. interpolate( point0.y, point1.y, point2.y, point3.y, weight )
  25042. );
  25043. };
  25044. /**************************************************************
  25045. * Cubic Bezier curve
  25046. **************************************************************/
  25047. function CubicBezierCurve( v0, v1, v2, v3 ) {
  25048. this.v0 = v0;
  25049. this.v1 = v1;
  25050. this.v2 = v2;
  25051. this.v3 = v3;
  25052. }
  25053. CubicBezierCurve.prototype = Object.create( Curve.prototype );
  25054. CubicBezierCurve.prototype.constructor = CubicBezierCurve;
  25055. CubicBezierCurve.prototype.getPoint = function ( t ) {
  25056. var b3 = ShapeUtils.b3;
  25057. return new Vector2(
  25058. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  25059. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  25060. );
  25061. };
  25062. CubicBezierCurve.prototype.getTangent = function( t ) {
  25063. var tangentCubicBezier = CurveUtils.tangentCubicBezier;
  25064. return new Vector2(
  25065. tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  25066. tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y )
  25067. ).normalize();
  25068. };
  25069. /**************************************************************
  25070. * Quadratic Bezier curve
  25071. **************************************************************/
  25072. function QuadraticBezierCurve( v0, v1, v2 ) {
  25073. this.v0 = v0;
  25074. this.v1 = v1;
  25075. this.v2 = v2;
  25076. }
  25077. QuadraticBezierCurve.prototype = Object.create( Curve.prototype );
  25078. QuadraticBezierCurve.prototype.constructor = QuadraticBezierCurve;
  25079. QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  25080. var b2 = ShapeUtils.b2;
  25081. return new Vector2(
  25082. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  25083. b2( t, this.v0.y, this.v1.y, this.v2.y )
  25084. );
  25085. };
  25086. QuadraticBezierCurve.prototype.getTangent = function( t ) {
  25087. var tangentQuadraticBezier = CurveUtils.tangentQuadraticBezier;
  25088. return new Vector2(
  25089. tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x ),
  25090. tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y )
  25091. ).normalize();
  25092. };
  25093. var PathPrototype = Object.assign( Object.create( CurvePath.prototype ), {
  25094. fromPoints: function ( vectors ) {
  25095. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  25096. for ( var i = 1, l = vectors.length; i < l; i ++ ) {
  25097. this.lineTo( vectors[ i ].x, vectors[ i ].y );
  25098. }
  25099. },
  25100. moveTo: function ( x, y ) {
  25101. this.currentPoint.set( x, y ); // TODO consider referencing vectors instead of copying?
  25102. },
  25103. lineTo: function ( x, y ) {
  25104. var curve = new LineCurve( this.currentPoint.clone(), new Vector2( x, y ) );
  25105. this.curves.push( curve );
  25106. this.currentPoint.set( x, y );
  25107. },
  25108. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25109. var curve = new QuadraticBezierCurve(
  25110. this.currentPoint.clone(),
  25111. new Vector2( aCPx, aCPy ),
  25112. new Vector2( aX, aY )
  25113. );
  25114. this.curves.push( curve );
  25115. this.currentPoint.set( aX, aY );
  25116. },
  25117. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25118. var curve = new CubicBezierCurve(
  25119. this.currentPoint.clone(),
  25120. new Vector2( aCP1x, aCP1y ),
  25121. new Vector2( aCP2x, aCP2y ),
  25122. new Vector2( aX, aY )
  25123. );
  25124. this.curves.push( curve );
  25125. this.currentPoint.set( aX, aY );
  25126. },
  25127. splineThru: function ( pts /*Array of Vector*/ ) {
  25128. var npts = [ this.currentPoint.clone() ].concat( pts );
  25129. var curve = new SplineCurve( npts );
  25130. this.curves.push( curve );
  25131. this.currentPoint.copy( pts[ pts.length - 1 ] );
  25132. },
  25133. arc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25134. var x0 = this.currentPoint.x;
  25135. var y0 = this.currentPoint.y;
  25136. this.absarc( aX + x0, aY + y0, aRadius,
  25137. aStartAngle, aEndAngle, aClockwise );
  25138. },
  25139. absarc: function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  25140. this.absellipse( aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  25141. },
  25142. ellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25143. var x0 = this.currentPoint.x;
  25144. var y0 = this.currentPoint.y;
  25145. this.absellipse( aX + x0, aY + y0, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25146. },
  25147. absellipse: function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation ) {
  25148. var curve = new EllipseCurve( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise, aRotation );
  25149. if ( this.curves.length > 0 ) {
  25150. // if a previous curve is present, attempt to join
  25151. var firstPoint = curve.getPoint( 0 );
  25152. if ( ! firstPoint.equals( this.currentPoint ) ) {
  25153. this.lineTo( firstPoint.x, firstPoint.y );
  25154. }
  25155. }
  25156. this.curves.push( curve );
  25157. var lastPoint = curve.getPoint( 1 );
  25158. this.currentPoint.copy( lastPoint );
  25159. }
  25160. } );
  25161. /**
  25162. * @author zz85 / http://www.lab4games.net/zz85/blog
  25163. * Defines a 2d shape plane using paths.
  25164. **/
  25165. // STEP 1 Create a path.
  25166. // STEP 2 Turn path into shape.
  25167. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  25168. // STEP 3a - Extract points from each shape, turn to vertices
  25169. // STEP 3b - Triangulate each shape, add faces.
  25170. function Shape() {
  25171. Path.apply( this, arguments );
  25172. this.holes = [];
  25173. }
  25174. Shape.prototype = Object.assign( Object.create( PathPrototype ), {
  25175. constructor: Shape,
  25176. getPointsHoles: function ( divisions ) {
  25177. var holesPts = [];
  25178. for ( var i = 0, l = this.holes.length; i < l; i ++ ) {
  25179. holesPts[ i ] = this.holes[ i ].getPoints( divisions );
  25180. }
  25181. return holesPts;
  25182. },
  25183. // Get points of shape and holes (keypoints based on segments parameter)
  25184. extractAllPoints: function ( divisions ) {
  25185. return {
  25186. shape: this.getPoints( divisions ),
  25187. holes: this.getPointsHoles( divisions )
  25188. };
  25189. },
  25190. extractPoints: function ( divisions ) {
  25191. return this.extractAllPoints( divisions );
  25192. }
  25193. } );
  25194. /**
  25195. * @author zz85 / http://www.lab4games.net/zz85/blog
  25196. * Creates free form 2d path using series of points, lines or curves.
  25197. *
  25198. **/
  25199. function Path( points ) {
  25200. CurvePath.call( this );
  25201. this.currentPoint = new Vector2();
  25202. if ( points ) {
  25203. this.fromPoints( points );
  25204. }
  25205. }
  25206. Path.prototype = PathPrototype;
  25207. PathPrototype.constructor = Path;
  25208. // minimal class for proxing functions to Path. Replaces old "extractSubpaths()"
  25209. function ShapePath() {
  25210. this.subPaths = [];
  25211. this.currentPath = null;
  25212. }
  25213. ShapePath.prototype = {
  25214. moveTo: function ( x, y ) {
  25215. this.currentPath = new Path();
  25216. this.subPaths.push(this.currentPath);
  25217. this.currentPath.moveTo( x, y );
  25218. },
  25219. lineTo: function ( x, y ) {
  25220. this.currentPath.lineTo( x, y );
  25221. },
  25222. quadraticCurveTo: function ( aCPx, aCPy, aX, aY ) {
  25223. this.currentPath.quadraticCurveTo( aCPx, aCPy, aX, aY );
  25224. },
  25225. bezierCurveTo: function ( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY ) {
  25226. this.currentPath.bezierCurveTo( aCP1x, aCP1y, aCP2x, aCP2y, aX, aY );
  25227. },
  25228. splineThru: function ( pts ) {
  25229. this.currentPath.splineThru( pts );
  25230. },
  25231. toShapes: function ( isCCW, noHoles ) {
  25232. function toShapesNoHoles( inSubpaths ) {
  25233. var shapes = [];
  25234. for ( var i = 0, l = inSubpaths.length; i < l; i ++ ) {
  25235. var tmpPath = inSubpaths[ i ];
  25236. var tmpShape = new Shape();
  25237. tmpShape.curves = tmpPath.curves;
  25238. shapes.push( tmpShape );
  25239. }
  25240. return shapes;
  25241. }
  25242. function isPointInsidePolygon( inPt, inPolygon ) {
  25243. var polyLen = inPolygon.length;
  25244. // inPt on polygon contour => immediate success or
  25245. // toggling of inside/outside at every single! intersection point of an edge
  25246. // with the horizontal line through inPt, left of inPt
  25247. // not counting lowerY endpoints of edges and whole edges on that line
  25248. var inside = false;
  25249. for ( var p = polyLen - 1, q = 0; q < polyLen; p = q ++ ) {
  25250. var edgeLowPt = inPolygon[ p ];
  25251. var edgeHighPt = inPolygon[ q ];
  25252. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  25253. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  25254. if ( Math.abs( edgeDy ) > Number.EPSILON ) {
  25255. // not parallel
  25256. if ( edgeDy < 0 ) {
  25257. edgeLowPt = inPolygon[ q ]; edgeDx = - edgeDx;
  25258. edgeHighPt = inPolygon[ p ]; edgeDy = - edgeDy;
  25259. }
  25260. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  25261. if ( inPt.y === edgeLowPt.y ) {
  25262. if ( inPt.x === edgeLowPt.x ) return true; // inPt is on contour ?
  25263. // continue; // no intersection or edgeLowPt => doesn't count !!!
  25264. } else {
  25265. var perpEdge = edgeDy * ( inPt.x - edgeLowPt.x ) - edgeDx * ( inPt.y - edgeLowPt.y );
  25266. if ( perpEdge === 0 ) return true; // inPt is on contour ?
  25267. if ( perpEdge < 0 ) continue;
  25268. inside = ! inside; // true intersection left of inPt
  25269. }
  25270. } else {
  25271. // parallel or collinear
  25272. if ( inPt.y !== edgeLowPt.y ) continue; // parallel
  25273. // edge lies on the same horizontal line as inPt
  25274. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  25275. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  25276. // continue;
  25277. }
  25278. }
  25279. return inside;
  25280. }
  25281. var isClockWise = ShapeUtils.isClockWise;
  25282. var subPaths = this.subPaths;
  25283. if ( subPaths.length === 0 ) return [];
  25284. if ( noHoles === true ) return toShapesNoHoles( subPaths );
  25285. var solid, tmpPath, tmpShape, shapes = [];
  25286. if ( subPaths.length === 1 ) {
  25287. tmpPath = subPaths[ 0 ];
  25288. tmpShape = new Shape();
  25289. tmpShape.curves = tmpPath.curves;
  25290. shapes.push( tmpShape );
  25291. return shapes;
  25292. }
  25293. var holesFirst = ! isClockWise( subPaths[ 0 ].getPoints() );
  25294. holesFirst = isCCW ? ! holesFirst : holesFirst;
  25295. // console.log("Holes first", holesFirst);
  25296. var betterShapeHoles = [];
  25297. var newShapes = [];
  25298. var newShapeHoles = [];
  25299. var mainIdx = 0;
  25300. var tmpPoints;
  25301. newShapes[ mainIdx ] = undefined;
  25302. newShapeHoles[ mainIdx ] = [];
  25303. for ( var i = 0, l = subPaths.length; i < l; i ++ ) {
  25304. tmpPath = subPaths[ i ];
  25305. tmpPoints = tmpPath.getPoints();
  25306. solid = isClockWise( tmpPoints );
  25307. solid = isCCW ? ! solid : solid;
  25308. if ( solid ) {
  25309. if ( ( ! holesFirst ) && ( newShapes[ mainIdx ] ) ) mainIdx ++;
  25310. newShapes[ mainIdx ] = { s: new Shape(), p: tmpPoints };
  25311. newShapes[ mainIdx ].s.curves = tmpPath.curves;
  25312. if ( holesFirst ) mainIdx ++;
  25313. newShapeHoles[ mainIdx ] = [];
  25314. //console.log('cw', i);
  25315. } else {
  25316. newShapeHoles[ mainIdx ].push( { h: tmpPath, p: tmpPoints[ 0 ] } );
  25317. //console.log('ccw', i);
  25318. }
  25319. }
  25320. // only Holes? -> probably all Shapes with wrong orientation
  25321. if ( ! newShapes[ 0 ] ) return toShapesNoHoles( subPaths );
  25322. if ( newShapes.length > 1 ) {
  25323. var ambiguous = false;
  25324. var toChange = [];
  25325. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25326. betterShapeHoles[ sIdx ] = [];
  25327. }
  25328. for ( var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx ++ ) {
  25329. var sho = newShapeHoles[ sIdx ];
  25330. for ( var hIdx = 0; hIdx < sho.length; hIdx ++ ) {
  25331. var ho = sho[ hIdx ];
  25332. var hole_unassigned = true;
  25333. for ( var s2Idx = 0; s2Idx < newShapes.length; s2Idx ++ ) {
  25334. if ( isPointInsidePolygon( ho.p, newShapes[ s2Idx ].p ) ) {
  25335. if ( sIdx !== s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  25336. if ( hole_unassigned ) {
  25337. hole_unassigned = false;
  25338. betterShapeHoles[ s2Idx ].push( ho );
  25339. } else {
  25340. ambiguous = true;
  25341. }
  25342. }
  25343. }
  25344. if ( hole_unassigned ) {
  25345. betterShapeHoles[ sIdx ].push( ho );
  25346. }
  25347. }
  25348. }
  25349. // console.log("ambiguous: ", ambiguous);
  25350. if ( toChange.length > 0 ) {
  25351. // console.log("to change: ", toChange);
  25352. if ( ! ambiguous ) newShapeHoles = betterShapeHoles;
  25353. }
  25354. }
  25355. var tmpHoles;
  25356. for ( var i = 0, il = newShapes.length; i < il; i ++ ) {
  25357. tmpShape = newShapes[ i ].s;
  25358. shapes.push( tmpShape );
  25359. tmpHoles = newShapeHoles[ i ];
  25360. for ( var j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  25361. tmpShape.holes.push( tmpHoles[ j ].h );
  25362. }
  25363. }
  25364. //console.log("shape", shapes);
  25365. return shapes;
  25366. }
  25367. };
  25368. /**
  25369. * @author zz85 / http://www.lab4games.net/zz85/blog
  25370. * @author mrdoob / http://mrdoob.com/
  25371. */
  25372. function Font( data ) {
  25373. this.data = data;
  25374. }
  25375. Object.assign( Font.prototype, {
  25376. isFont: true,
  25377. generateShapes: function ( text, size, divisions ) {
  25378. function createPaths( text ) {
  25379. var chars = String( text ).split( '' );
  25380. var scale = size / data.resolution;
  25381. var offset = 0;
  25382. var paths = [];
  25383. for ( var i = 0; i < chars.length; i ++ ) {
  25384. var ret = createPath( chars[ i ], scale, offset );
  25385. offset += ret.offset;
  25386. paths.push( ret.path );
  25387. }
  25388. return paths;
  25389. }
  25390. function createPath( c, scale, offset ) {
  25391. var glyph = data.glyphs[ c ] || data.glyphs[ '?' ];
  25392. if ( ! glyph ) return;
  25393. var path = new ShapePath();
  25394. var pts = [], b2 = ShapeUtils.b2, b3 = ShapeUtils.b3;
  25395. var x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2, laste;
  25396. if ( glyph.o ) {
  25397. var outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  25398. for ( var i = 0, l = outline.length; i < l; ) {
  25399. var action = outline[ i ++ ];
  25400. switch ( action ) {
  25401. case 'm': // moveTo
  25402. x = outline[ i ++ ] * scale + offset;
  25403. y = outline[ i ++ ] * scale;
  25404. path.moveTo( x, y );
  25405. break;
  25406. case 'l': // lineTo
  25407. x = outline[ i ++ ] * scale + offset;
  25408. y = outline[ i ++ ] * scale;
  25409. path.lineTo( x, y );
  25410. break;
  25411. case 'q': // quadraticCurveTo
  25412. cpx = outline[ i ++ ] * scale + offset;
  25413. cpy = outline[ i ++ ] * scale;
  25414. cpx1 = outline[ i ++ ] * scale + offset;
  25415. cpy1 = outline[ i ++ ] * scale;
  25416. path.quadraticCurveTo( cpx1, cpy1, cpx, cpy );
  25417. laste = pts[ pts.length - 1 ];
  25418. if ( laste ) {
  25419. cpx0 = laste.x;
  25420. cpy0 = laste.y;
  25421. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25422. var t = i2 / divisions;
  25423. b2( t, cpx0, cpx1, cpx );
  25424. b2( t, cpy0, cpy1, cpy );
  25425. }
  25426. }
  25427. break;
  25428. case 'b': // bezierCurveTo
  25429. cpx = outline[ i ++ ] * scale + offset;
  25430. cpy = outline[ i ++ ] * scale;
  25431. cpx1 = outline[ i ++ ] * scale + offset;
  25432. cpy1 = outline[ i ++ ] * scale;
  25433. cpx2 = outline[ i ++ ] * scale + offset;
  25434. cpy2 = outline[ i ++ ] * scale;
  25435. path.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, cpx, cpy );
  25436. laste = pts[ pts.length - 1 ];
  25437. if ( laste ) {
  25438. cpx0 = laste.x;
  25439. cpy0 = laste.y;
  25440. for ( var i2 = 1; i2 <= divisions; i2 ++ ) {
  25441. var t = i2 / divisions;
  25442. b3( t, cpx0, cpx1, cpx2, cpx );
  25443. b3( t, cpy0, cpy1, cpy2, cpy );
  25444. }
  25445. }
  25446. break;
  25447. }
  25448. }
  25449. }
  25450. return { offset: glyph.ha * scale, path: path };
  25451. }
  25452. //
  25453. if ( size === undefined ) size = 100;
  25454. if ( divisions === undefined ) divisions = 4;
  25455. var data = this.data;
  25456. var paths = createPaths( text );
  25457. var shapes = [];
  25458. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  25459. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  25460. }
  25461. return shapes;
  25462. }
  25463. } );
  25464. /**
  25465. * @author mrdoob / http://mrdoob.com/
  25466. */
  25467. function FontLoader( manager ) {
  25468. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25469. }
  25470. Object.assign( FontLoader.prototype, {
  25471. load: function ( url, onLoad, onProgress, onError ) {
  25472. var scope = this;
  25473. var loader = new FileLoader( this.manager );
  25474. loader.load( url, function ( text ) {
  25475. var json;
  25476. try {
  25477. json = JSON.parse( text );
  25478. } catch ( e ) {
  25479. console.warn( 'THREE.FontLoader: typeface.js support is being deprecated. Use typeface.json instead.' );
  25480. json = JSON.parse( text.substring( 65, text.length - 2 ) );
  25481. }
  25482. var font = scope.parse( json );
  25483. if ( onLoad ) onLoad( font );
  25484. }, onProgress, onError );
  25485. },
  25486. parse: function ( json ) {
  25487. return new Font( json );
  25488. }
  25489. } );
  25490. var context;
  25491. var AudioContext = {
  25492. getContext: function () {
  25493. if ( context === undefined ) {
  25494. context = new ( window.AudioContext || window.webkitAudioContext )();
  25495. }
  25496. return context;
  25497. },
  25498. setContext: function ( value ) {
  25499. context = value;
  25500. }
  25501. };
  25502. /**
  25503. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25504. */
  25505. function AudioLoader( manager ) {
  25506. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager;
  25507. }
  25508. Object.assign( AudioLoader.prototype, {
  25509. load: function ( url, onLoad, onProgress, onError ) {
  25510. var loader = new FileLoader( this.manager );
  25511. loader.setResponseType( 'arraybuffer' );
  25512. loader.load( url, function ( buffer ) {
  25513. var context = AudioContext.getContext();
  25514. context.decodeAudioData( buffer, function ( audioBuffer ) {
  25515. onLoad( audioBuffer );
  25516. } );
  25517. }, onProgress, onError );
  25518. }
  25519. } );
  25520. /**
  25521. * @author abelnation / http://github.com/abelnation
  25522. */
  25523. function RectAreaLight ( color, intensity, width, height ) {
  25524. Light.call( this, color, intensity );
  25525. this.type = 'RectAreaLight';
  25526. this.position.set( 0, 1, 0 );
  25527. this.updateMatrix();
  25528. this.width = ( width !== undefined ) ? width : 10;
  25529. this.height = ( height !== undefined ) ? height : 10;
  25530. // TODO (abelnation): distance/decay
  25531. // TODO (abelnation): update method for RectAreaLight to update transform to lookat target
  25532. // TODO (abelnation): shadows
  25533. // this.shadow = new THREE.RectAreaLightShadow( new THREE.PerspectiveCamera( 90, 1, 0.5, 500 ) );
  25534. }
  25535. // TODO (abelnation): RectAreaLight update when light shape is changed
  25536. RectAreaLight.prototype = Object.assign( Object.create( Light.prototype ), {
  25537. constructor: RectAreaLight,
  25538. isRectAreaLight: true,
  25539. copy: function ( source ) {
  25540. Light.prototype.copy.call( this, source );
  25541. this.width = source.width;
  25542. this.height = source.height;
  25543. // this.shadow = source.shadow.clone();
  25544. return this;
  25545. }
  25546. } );
  25547. /**
  25548. * @author mrdoob / http://mrdoob.com/
  25549. */
  25550. function StereoCamera() {
  25551. this.type = 'StereoCamera';
  25552. this.aspect = 1;
  25553. this.eyeSep = 0.064;
  25554. this.cameraL = new PerspectiveCamera();
  25555. this.cameraL.layers.enable( 1 );
  25556. this.cameraL.matrixAutoUpdate = false;
  25557. this.cameraR = new PerspectiveCamera();
  25558. this.cameraR.layers.enable( 2 );
  25559. this.cameraR.matrixAutoUpdate = false;
  25560. }
  25561. Object.assign( StereoCamera.prototype, {
  25562. update: ( function () {
  25563. var instance, focus, fov, aspect, near, far, zoom;
  25564. var eyeRight = new Matrix4();
  25565. var eyeLeft = new Matrix4();
  25566. return function update( camera ) {
  25567. var needsUpdate = instance !== this || focus !== camera.focus || fov !== camera.fov ||
  25568. aspect !== camera.aspect * this.aspect || near !== camera.near ||
  25569. far !== camera.far || zoom !== camera.zoom;
  25570. if ( needsUpdate ) {
  25571. instance = this;
  25572. focus = camera.focus;
  25573. fov = camera.fov;
  25574. aspect = camera.aspect * this.aspect;
  25575. near = camera.near;
  25576. far = camera.far;
  25577. zoom = camera.zoom;
  25578. // Off-axis stereoscopic effect based on
  25579. // http://paulbourke.net/stereographics/stereorender/
  25580. var projectionMatrix = camera.projectionMatrix.clone();
  25581. var eyeSep = this.eyeSep / 2;
  25582. var eyeSepOnProjection = eyeSep * near / focus;
  25583. var ymax = ( near * Math.tan( _Math.DEG2RAD * fov * 0.5 ) ) / zoom;
  25584. var xmin, xmax;
  25585. // translate xOffset
  25586. eyeLeft.elements[ 12 ] = - eyeSep;
  25587. eyeRight.elements[ 12 ] = eyeSep;
  25588. // for left eye
  25589. xmin = - ymax * aspect + eyeSepOnProjection;
  25590. xmax = ymax * aspect + eyeSepOnProjection;
  25591. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25592. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25593. this.cameraL.projectionMatrix.copy( projectionMatrix );
  25594. // for right eye
  25595. xmin = - ymax * aspect - eyeSepOnProjection;
  25596. xmax = ymax * aspect - eyeSepOnProjection;
  25597. projectionMatrix.elements[ 0 ] = 2 * near / ( xmax - xmin );
  25598. projectionMatrix.elements[ 8 ] = ( xmax + xmin ) / ( xmax - xmin );
  25599. this.cameraR.projectionMatrix.copy( projectionMatrix );
  25600. }
  25601. this.cameraL.matrixWorld.copy( camera.matrixWorld ).multiply( eyeLeft );
  25602. this.cameraR.matrixWorld.copy( camera.matrixWorld ).multiply( eyeRight );
  25603. };
  25604. } )()
  25605. } );
  25606. /**
  25607. * Camera for rendering cube maps
  25608. * - renders scene into axis-aligned cube
  25609. *
  25610. * @author alteredq / http://alteredqualia.com/
  25611. */
  25612. function CubeCamera( near, far, cubeResolution ) {
  25613. Object3D.call( this );
  25614. this.type = 'CubeCamera';
  25615. var fov = 90, aspect = 1;
  25616. var cameraPX = new PerspectiveCamera( fov, aspect, near, far );
  25617. cameraPX.up.set( 0, - 1, 0 );
  25618. cameraPX.lookAt( new Vector3( 1, 0, 0 ) );
  25619. this.add( cameraPX );
  25620. var cameraNX = new PerspectiveCamera( fov, aspect, near, far );
  25621. cameraNX.up.set( 0, - 1, 0 );
  25622. cameraNX.lookAt( new Vector3( - 1, 0, 0 ) );
  25623. this.add( cameraNX );
  25624. var cameraPY = new PerspectiveCamera( fov, aspect, near, far );
  25625. cameraPY.up.set( 0, 0, 1 );
  25626. cameraPY.lookAt( new Vector3( 0, 1, 0 ) );
  25627. this.add( cameraPY );
  25628. var cameraNY = new PerspectiveCamera( fov, aspect, near, far );
  25629. cameraNY.up.set( 0, 0, - 1 );
  25630. cameraNY.lookAt( new Vector3( 0, - 1, 0 ) );
  25631. this.add( cameraNY );
  25632. var cameraPZ = new PerspectiveCamera( fov, aspect, near, far );
  25633. cameraPZ.up.set( 0, - 1, 0 );
  25634. cameraPZ.lookAt( new Vector3( 0, 0, 1 ) );
  25635. this.add( cameraPZ );
  25636. var cameraNZ = new PerspectiveCamera( fov, aspect, near, far );
  25637. cameraNZ.up.set( 0, - 1, 0 );
  25638. cameraNZ.lookAt( new Vector3( 0, 0, - 1 ) );
  25639. this.add( cameraNZ );
  25640. var options = { format: RGBFormat, magFilter: LinearFilter, minFilter: LinearFilter };
  25641. this.renderTarget = new WebGLRenderTargetCube( cubeResolution, cubeResolution, options );
  25642. this.updateCubeMap = function ( renderer, scene ) {
  25643. if ( this.parent === null ) this.updateMatrixWorld();
  25644. var renderTarget = this.renderTarget;
  25645. var generateMipmaps = renderTarget.texture.generateMipmaps;
  25646. renderTarget.texture.generateMipmaps = false;
  25647. renderTarget.activeCubeFace = 0;
  25648. renderer.render( scene, cameraPX, renderTarget );
  25649. renderTarget.activeCubeFace = 1;
  25650. renderer.render( scene, cameraNX, renderTarget );
  25651. renderTarget.activeCubeFace = 2;
  25652. renderer.render( scene, cameraPY, renderTarget );
  25653. renderTarget.activeCubeFace = 3;
  25654. renderer.render( scene, cameraNY, renderTarget );
  25655. renderTarget.activeCubeFace = 4;
  25656. renderer.render( scene, cameraPZ, renderTarget );
  25657. renderTarget.texture.generateMipmaps = generateMipmaps;
  25658. renderTarget.activeCubeFace = 5;
  25659. renderer.render( scene, cameraNZ, renderTarget );
  25660. renderer.setRenderTarget( null );
  25661. };
  25662. }
  25663. CubeCamera.prototype = Object.create( Object3D.prototype );
  25664. CubeCamera.prototype.constructor = CubeCamera;
  25665. /**
  25666. * @author mrdoob / http://mrdoob.com/
  25667. */
  25668. function AudioListener() {
  25669. Object3D.call( this );
  25670. this.type = 'AudioListener';
  25671. this.context = AudioContext.getContext();
  25672. this.gain = this.context.createGain();
  25673. this.gain.connect( this.context.destination );
  25674. this.filter = null;
  25675. }
  25676. AudioListener.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25677. constructor: AudioListener,
  25678. getInput: function () {
  25679. return this.gain;
  25680. },
  25681. removeFilter: function ( ) {
  25682. if ( this.filter !== null ) {
  25683. this.gain.disconnect( this.filter );
  25684. this.filter.disconnect( this.context.destination );
  25685. this.gain.connect( this.context.destination );
  25686. this.filter = null;
  25687. }
  25688. },
  25689. getFilter: function () {
  25690. return this.filter;
  25691. },
  25692. setFilter: function ( value ) {
  25693. if ( this.filter !== null ) {
  25694. this.gain.disconnect( this.filter );
  25695. this.filter.disconnect( this.context.destination );
  25696. } else {
  25697. this.gain.disconnect( this.context.destination );
  25698. }
  25699. this.filter = value;
  25700. this.gain.connect( this.filter );
  25701. this.filter.connect( this.context.destination );
  25702. },
  25703. getMasterVolume: function () {
  25704. return this.gain.gain.value;
  25705. },
  25706. setMasterVolume: function ( value ) {
  25707. this.gain.gain.value = value;
  25708. },
  25709. updateMatrixWorld: ( function () {
  25710. var position = new Vector3();
  25711. var quaternion = new Quaternion();
  25712. var scale = new Vector3();
  25713. var orientation = new Vector3();
  25714. return function updateMatrixWorld( force ) {
  25715. Object3D.prototype.updateMatrixWorld.call( this, force );
  25716. var listener = this.context.listener;
  25717. var up = this.up;
  25718. this.matrixWorld.decompose( position, quaternion, scale );
  25719. orientation.set( 0, 0, - 1 ).applyQuaternion( quaternion );
  25720. if ( listener.positionX ) {
  25721. listener.positionX.setValueAtTime( position.x, this.context.currentTime );
  25722. listener.positionY.setValueAtTime( position.y, this.context.currentTime );
  25723. listener.positionZ.setValueAtTime( position.z, this.context.currentTime );
  25724. listener.forwardX.setValueAtTime( orientation.x, this.context.currentTime );
  25725. listener.forwardY.setValueAtTime( orientation.y, this.context.currentTime );
  25726. listener.forwardZ.setValueAtTime( orientation.z, this.context.currentTime );
  25727. listener.upX.setValueAtTime( up.x, this.context.currentTime );
  25728. listener.upY.setValueAtTime( up.y, this.context.currentTime );
  25729. listener.upZ.setValueAtTime( up.z, this.context.currentTime );
  25730. } else {
  25731. listener.setPosition( position.x, position.y, position.z );
  25732. listener.setOrientation( orientation.x, orientation.y, orientation.z, up.x, up.y, up.z );
  25733. }
  25734. };
  25735. } )()
  25736. } );
  25737. /**
  25738. * @author mrdoob / http://mrdoob.com/
  25739. * @author Reece Aaron Lecrivain / http://reecenotes.com/
  25740. */
  25741. function Audio( listener ) {
  25742. Object3D.call( this );
  25743. this.type = 'Audio';
  25744. this.context = listener.context;
  25745. this.gain = this.context.createGain();
  25746. this.gain.connect( listener.getInput() );
  25747. this.autoplay = false;
  25748. this.buffer = null;
  25749. this.loop = false;
  25750. this.startTime = 0;
  25751. this.playbackRate = 1;
  25752. this.isPlaying = false;
  25753. this.hasPlaybackControl = true;
  25754. this.sourceType = 'empty';
  25755. this.filters = [];
  25756. }
  25757. Audio.prototype = Object.assign( Object.create( Object3D.prototype ), {
  25758. constructor: Audio,
  25759. getOutput: function () {
  25760. return this.gain;
  25761. },
  25762. setNodeSource: function ( audioNode ) {
  25763. this.hasPlaybackControl = false;
  25764. this.sourceType = 'audioNode';
  25765. this.source = audioNode;
  25766. this.connect();
  25767. return this;
  25768. },
  25769. setBuffer: function ( audioBuffer ) {
  25770. this.buffer = audioBuffer;
  25771. this.sourceType = 'buffer';
  25772. if ( this.autoplay ) this.play();
  25773. return this;
  25774. },
  25775. play: function () {
  25776. if ( this.isPlaying === true ) {
  25777. console.warn( 'THREE.Audio: Audio is already playing.' );
  25778. return;
  25779. }
  25780. if ( this.hasPlaybackControl === false ) {
  25781. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25782. return;
  25783. }
  25784. var source = this.context.createBufferSource();
  25785. source.buffer = this.buffer;
  25786. source.loop = this.loop;
  25787. source.onended = this.onEnded.bind( this );
  25788. source.playbackRate.setValueAtTime( this.playbackRate, this.startTime );
  25789. source.start( 0, this.startTime );
  25790. this.isPlaying = true;
  25791. this.source = source;
  25792. return this.connect();
  25793. },
  25794. pause: function () {
  25795. if ( this.hasPlaybackControl === false ) {
  25796. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25797. return;
  25798. }
  25799. this.source.stop();
  25800. this.startTime = this.context.currentTime;
  25801. this.isPlaying = false;
  25802. return this;
  25803. },
  25804. stop: function () {
  25805. if ( this.hasPlaybackControl === false ) {
  25806. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25807. return;
  25808. }
  25809. this.source.stop();
  25810. this.startTime = 0;
  25811. this.isPlaying = false;
  25812. return this;
  25813. },
  25814. connect: function () {
  25815. if ( this.filters.length > 0 ) {
  25816. this.source.connect( this.filters[ 0 ] );
  25817. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  25818. this.filters[ i - 1 ].connect( this.filters[ i ] );
  25819. }
  25820. this.filters[ this.filters.length - 1 ].connect( this.getOutput() );
  25821. } else {
  25822. this.source.connect( this.getOutput() );
  25823. }
  25824. return this;
  25825. },
  25826. disconnect: function () {
  25827. if ( this.filters.length > 0 ) {
  25828. this.source.disconnect( this.filters[ 0 ] );
  25829. for ( var i = 1, l = this.filters.length; i < l; i ++ ) {
  25830. this.filters[ i - 1 ].disconnect( this.filters[ i ] );
  25831. }
  25832. this.filters[ this.filters.length - 1 ].disconnect( this.getOutput() );
  25833. } else {
  25834. this.source.disconnect( this.getOutput() );
  25835. }
  25836. return this;
  25837. },
  25838. getFilters: function () {
  25839. return this.filters;
  25840. },
  25841. setFilters: function ( value ) {
  25842. if ( ! value ) value = [];
  25843. if ( this.isPlaying === true ) {
  25844. this.disconnect();
  25845. this.filters = value;
  25846. this.connect();
  25847. } else {
  25848. this.filters = value;
  25849. }
  25850. return this;
  25851. },
  25852. getFilter: function () {
  25853. return this.getFilters()[ 0 ];
  25854. },
  25855. setFilter: function ( filter ) {
  25856. return this.setFilters( filter ? [ filter ] : [] );
  25857. },
  25858. setPlaybackRate: function ( value ) {
  25859. if ( this.hasPlaybackControl === false ) {
  25860. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25861. return;
  25862. }
  25863. this.playbackRate = value;
  25864. if ( this.isPlaying === true ) {
  25865. this.source.playbackRate.setValueAtTime( this.playbackRate, this.context.currentTime );
  25866. }
  25867. return this;
  25868. },
  25869. getPlaybackRate: function () {
  25870. return this.playbackRate;
  25871. },
  25872. onEnded: function () {
  25873. this.isPlaying = false;
  25874. },
  25875. getLoop: function () {
  25876. if ( this.hasPlaybackControl === false ) {
  25877. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25878. return false;
  25879. }
  25880. return this.loop;
  25881. },
  25882. setLoop: function ( value ) {
  25883. if ( this.hasPlaybackControl === false ) {
  25884. console.warn( 'THREE.Audio: this Audio has no playback control.' );
  25885. return;
  25886. }
  25887. this.loop = value;
  25888. if ( this.isPlaying === true ) {
  25889. this.source.loop = this.loop;
  25890. }
  25891. return this;
  25892. },
  25893. getVolume: function () {
  25894. return this.gain.gain.value;
  25895. },
  25896. setVolume: function ( value ) {
  25897. this.gain.gain.value = value;
  25898. return this;
  25899. }
  25900. } );
  25901. /**
  25902. * @author mrdoob / http://mrdoob.com/
  25903. */
  25904. function PositionalAudio( listener ) {
  25905. Audio.call( this, listener );
  25906. this.panner = this.context.createPanner();
  25907. this.panner.connect( this.gain );
  25908. }
  25909. PositionalAudio.prototype = Object.assign( Object.create( Audio.prototype ), {
  25910. constructor: PositionalAudio,
  25911. getOutput: function () {
  25912. return this.panner;
  25913. },
  25914. getRefDistance: function () {
  25915. return this.panner.refDistance;
  25916. },
  25917. setRefDistance: function ( value ) {
  25918. this.panner.refDistance = value;
  25919. },
  25920. getRolloffFactor: function () {
  25921. return this.panner.rolloffFactor;
  25922. },
  25923. setRolloffFactor: function ( value ) {
  25924. this.panner.rolloffFactor = value;
  25925. },
  25926. getDistanceModel: function () {
  25927. return this.panner.distanceModel;
  25928. },
  25929. setDistanceModel: function ( value ) {
  25930. this.panner.distanceModel = value;
  25931. },
  25932. getMaxDistance: function () {
  25933. return this.panner.maxDistance;
  25934. },
  25935. setMaxDistance: function ( value ) {
  25936. this.panner.maxDistance = value;
  25937. },
  25938. updateMatrixWorld: ( function () {
  25939. var position = new Vector3();
  25940. return function updateMatrixWorld( force ) {
  25941. Object3D.prototype.updateMatrixWorld.call( this, force );
  25942. position.setFromMatrixPosition( this.matrixWorld );
  25943. this.panner.setPosition( position.x, position.y, position.z );
  25944. };
  25945. } )()
  25946. } );
  25947. /**
  25948. * @author mrdoob / http://mrdoob.com/
  25949. */
  25950. function AudioAnalyser( audio, fftSize ) {
  25951. this.analyser = audio.context.createAnalyser();
  25952. this.analyser.fftSize = fftSize !== undefined ? fftSize : 2048;
  25953. this.data = new Uint8Array( this.analyser.frequencyBinCount );
  25954. audio.getOutput().connect( this.analyser );
  25955. }
  25956. Object.assign( AudioAnalyser.prototype, {
  25957. getFrequencyData: function () {
  25958. this.analyser.getByteFrequencyData( this.data );
  25959. return this.data;
  25960. },
  25961. getAverageFrequency: function () {
  25962. var value = 0, data = this.getFrequencyData();
  25963. for ( var i = 0; i < data.length; i ++ ) {
  25964. value += data[ i ];
  25965. }
  25966. return value / data.length;
  25967. }
  25968. } );
  25969. /**
  25970. *
  25971. * Buffered scene graph property that allows weighted accumulation.
  25972. *
  25973. *
  25974. * @author Ben Houston / http://clara.io/
  25975. * @author David Sarno / http://lighthaus.us/
  25976. * @author tschw
  25977. */
  25978. function PropertyMixer( binding, typeName, valueSize ) {
  25979. this.binding = binding;
  25980. this.valueSize = valueSize;
  25981. var bufferType = Float64Array,
  25982. mixFunction;
  25983. switch ( typeName ) {
  25984. case 'quaternion':
  25985. mixFunction = this._slerp;
  25986. break;
  25987. case 'string':
  25988. case 'bool':
  25989. bufferType = Array;
  25990. mixFunction = this._select;
  25991. break;
  25992. default:
  25993. mixFunction = this._lerp;
  25994. }
  25995. this.buffer = new bufferType( valueSize * 4 );
  25996. // layout: [ incoming | accu0 | accu1 | orig ]
  25997. //
  25998. // interpolators can use .buffer as their .result
  25999. // the data then goes to 'incoming'
  26000. //
  26001. // 'accu0' and 'accu1' are used frame-interleaved for
  26002. // the cumulative result and are compared to detect
  26003. // changes
  26004. //
  26005. // 'orig' stores the original state of the property
  26006. this._mixBufferRegion = mixFunction;
  26007. this.cumulativeWeight = 0;
  26008. this.useCount = 0;
  26009. this.referenceCount = 0;
  26010. }
  26011. PropertyMixer.prototype = {
  26012. constructor: PropertyMixer,
  26013. // accumulate data in the 'incoming' region into 'accu<i>'
  26014. accumulate: function( accuIndex, weight ) {
  26015. // note: happily accumulating nothing when weight = 0, the caller knows
  26016. // the weight and shouldn't have made the call in the first place
  26017. var buffer = this.buffer,
  26018. stride = this.valueSize,
  26019. offset = accuIndex * stride + stride,
  26020. currentWeight = this.cumulativeWeight;
  26021. if ( currentWeight === 0 ) {
  26022. // accuN := incoming * weight
  26023. for ( var i = 0; i !== stride; ++ i ) {
  26024. buffer[ offset + i ] = buffer[ i ];
  26025. }
  26026. currentWeight = weight;
  26027. } else {
  26028. // accuN := accuN + incoming * weight
  26029. currentWeight += weight;
  26030. var mix = weight / currentWeight;
  26031. this._mixBufferRegion( buffer, offset, 0, mix, stride );
  26032. }
  26033. this.cumulativeWeight = currentWeight;
  26034. },
  26035. // apply the state of 'accu<i>' to the binding when accus differ
  26036. apply: function( accuIndex ) {
  26037. var stride = this.valueSize,
  26038. buffer = this.buffer,
  26039. offset = accuIndex * stride + stride,
  26040. weight = this.cumulativeWeight,
  26041. binding = this.binding;
  26042. this.cumulativeWeight = 0;
  26043. if ( weight < 1 ) {
  26044. // accuN := accuN + original * ( 1 - cumulativeWeight )
  26045. var originalValueOffset = stride * 3;
  26046. this._mixBufferRegion(
  26047. buffer, offset, originalValueOffset, 1 - weight, stride );
  26048. }
  26049. for ( var i = stride, e = stride + stride; i !== e; ++ i ) {
  26050. if ( buffer[ i ] !== buffer[ i + stride ] ) {
  26051. // value has changed -> update scene graph
  26052. binding.setValue( buffer, offset );
  26053. break;
  26054. }
  26055. }
  26056. },
  26057. // remember the state of the bound property and copy it to both accus
  26058. saveOriginalState: function() {
  26059. var binding = this.binding;
  26060. var buffer = this.buffer,
  26061. stride = this.valueSize,
  26062. originalValueOffset = stride * 3;
  26063. binding.getValue( buffer, originalValueOffset );
  26064. // accu[0..1] := orig -- initially detect changes against the original
  26065. for ( var i = stride, e = originalValueOffset; i !== e; ++ i ) {
  26066. buffer[ i ] = buffer[ originalValueOffset + ( i % stride ) ];
  26067. }
  26068. this.cumulativeWeight = 0;
  26069. },
  26070. // apply the state previously taken via 'saveOriginalState' to the binding
  26071. restoreOriginalState: function() {
  26072. var originalValueOffset = this.valueSize * 3;
  26073. this.binding.setValue( this.buffer, originalValueOffset );
  26074. },
  26075. // mix functions
  26076. _select: function( buffer, dstOffset, srcOffset, t, stride ) {
  26077. if ( t >= 0.5 ) {
  26078. for ( var i = 0; i !== stride; ++ i ) {
  26079. buffer[ dstOffset + i ] = buffer[ srcOffset + i ];
  26080. }
  26081. }
  26082. },
  26083. _slerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  26084. Quaternion.slerpFlat( buffer, dstOffset,
  26085. buffer, dstOffset, buffer, srcOffset, t );
  26086. },
  26087. _lerp: function( buffer, dstOffset, srcOffset, t, stride ) {
  26088. var s = 1 - t;
  26089. for ( var i = 0; i !== stride; ++ i ) {
  26090. var j = dstOffset + i;
  26091. buffer[ j ] = buffer[ j ] * s + buffer[ srcOffset + i ] * t;
  26092. }
  26093. }
  26094. };
  26095. /**
  26096. *
  26097. * A reference to a real property in the scene graph.
  26098. *
  26099. *
  26100. * @author Ben Houston / http://clara.io/
  26101. * @author David Sarno / http://lighthaus.us/
  26102. * @author tschw
  26103. */
  26104. function PropertyBinding( rootNode, path, parsedPath ) {
  26105. this.path = path;
  26106. this.parsedPath = parsedPath ||
  26107. PropertyBinding.parseTrackName( path );
  26108. this.node = PropertyBinding.findNode(
  26109. rootNode, this.parsedPath.nodeName ) || rootNode;
  26110. this.rootNode = rootNode;
  26111. }
  26112. PropertyBinding.prototype = {
  26113. constructor: PropertyBinding,
  26114. getValue: function getValue_unbound( targetArray, offset ) {
  26115. this.bind();
  26116. this.getValue( targetArray, offset );
  26117. // Note: This class uses a State pattern on a per-method basis:
  26118. // 'bind' sets 'this.getValue' / 'setValue' and shadows the
  26119. // prototype version of these methods with one that represents
  26120. // the bound state. When the property is not found, the methods
  26121. // become no-ops.
  26122. },
  26123. setValue: function getValue_unbound( sourceArray, offset ) {
  26124. this.bind();
  26125. this.setValue( sourceArray, offset );
  26126. },
  26127. // create getter / setter pair for a property in the scene graph
  26128. bind: function() {
  26129. var targetObject = this.node,
  26130. parsedPath = this.parsedPath,
  26131. objectName = parsedPath.objectName,
  26132. propertyName = parsedPath.propertyName,
  26133. propertyIndex = parsedPath.propertyIndex;
  26134. if ( ! targetObject ) {
  26135. targetObject = PropertyBinding.findNode(
  26136. this.rootNode, parsedPath.nodeName ) || this.rootNode;
  26137. this.node = targetObject;
  26138. }
  26139. // set fail state so we can just 'return' on error
  26140. this.getValue = this._getValue_unavailable;
  26141. this.setValue = this._setValue_unavailable;
  26142. // ensure there is a value node
  26143. if ( ! targetObject ) {
  26144. console.error( " trying to update node for track: " + this.path + " but it wasn't found." );
  26145. return;
  26146. }
  26147. if ( objectName ) {
  26148. var objectIndex = parsedPath.objectIndex;
  26149. // special cases were we need to reach deeper into the hierarchy to get the face materials....
  26150. switch ( objectName ) {
  26151. case 'materials':
  26152. if ( ! targetObject.material ) {
  26153. console.error( ' can not bind to material as node does not have a material', this );
  26154. return;
  26155. }
  26156. if ( ! targetObject.material.materials ) {
  26157. console.error( ' can not bind to material.materials as node.material does not have a materials array', this );
  26158. return;
  26159. }
  26160. targetObject = targetObject.material.materials;
  26161. break;
  26162. case 'bones':
  26163. if ( ! targetObject.skeleton ) {
  26164. console.error( ' can not bind to bones as node does not have a skeleton', this );
  26165. return;
  26166. }
  26167. // potential future optimization: skip this if propertyIndex is already an integer
  26168. // and convert the integer string to a true integer.
  26169. targetObject = targetObject.skeleton.bones;
  26170. // support resolving morphTarget names into indices.
  26171. for ( var i = 0; i < targetObject.length; i ++ ) {
  26172. if ( targetObject[ i ].name === objectIndex ) {
  26173. objectIndex = i;
  26174. break;
  26175. }
  26176. }
  26177. break;
  26178. default:
  26179. if ( targetObject[ objectName ] === undefined ) {
  26180. console.error( ' can not bind to objectName of node, undefined', this );
  26181. return;
  26182. }
  26183. targetObject = targetObject[ objectName ];
  26184. }
  26185. if ( objectIndex !== undefined ) {
  26186. if ( targetObject[ objectIndex ] === undefined ) {
  26187. console.error( " trying to bind to objectIndex of objectName, but is undefined:", this, targetObject );
  26188. return;
  26189. }
  26190. targetObject = targetObject[ objectIndex ];
  26191. }
  26192. }
  26193. // resolve property
  26194. var nodeProperty = targetObject[ propertyName ];
  26195. if ( nodeProperty === undefined ) {
  26196. var nodeName = parsedPath.nodeName;
  26197. console.error( " trying to update property for track: " + nodeName +
  26198. '.' + propertyName + " but it wasn't found.", targetObject );
  26199. return;
  26200. }
  26201. // determine versioning scheme
  26202. var versioning = this.Versioning.None;
  26203. if ( targetObject.needsUpdate !== undefined ) { // material
  26204. versioning = this.Versioning.NeedsUpdate;
  26205. this.targetObject = targetObject;
  26206. } else if ( targetObject.matrixWorldNeedsUpdate !== undefined ) { // node transform
  26207. versioning = this.Versioning.MatrixWorldNeedsUpdate;
  26208. this.targetObject = targetObject;
  26209. }
  26210. // determine how the property gets bound
  26211. var bindingType = this.BindingType.Direct;
  26212. if ( propertyIndex !== undefined ) {
  26213. // access a sub element of the property array (only primitives are supported right now)
  26214. if ( propertyName === "morphTargetInfluences" ) {
  26215. // potential optimization, skip this if propertyIndex is already an integer, and convert the integer string to a true integer.
  26216. // support resolving morphTarget names into indices.
  26217. if ( ! targetObject.geometry ) {
  26218. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry', this );
  26219. return;
  26220. }
  26221. if ( ! targetObject.geometry.morphTargets ) {
  26222. console.error( ' can not bind to morphTargetInfluences becasuse node does not have a geometry.morphTargets', this );
  26223. return;
  26224. }
  26225. for ( var i = 0; i < this.node.geometry.morphTargets.length; i ++ ) {
  26226. if ( targetObject.geometry.morphTargets[ i ].name === propertyIndex ) {
  26227. propertyIndex = i;
  26228. break;
  26229. }
  26230. }
  26231. }
  26232. bindingType = this.BindingType.ArrayElement;
  26233. this.resolvedProperty = nodeProperty;
  26234. this.propertyIndex = propertyIndex;
  26235. } else if ( nodeProperty.fromArray !== undefined && nodeProperty.toArray !== undefined ) {
  26236. // must use copy for Object3D.Euler/Quaternion
  26237. bindingType = this.BindingType.HasFromToArray;
  26238. this.resolvedProperty = nodeProperty;
  26239. } else if ( nodeProperty.length !== undefined ) {
  26240. bindingType = this.BindingType.EntireArray;
  26241. this.resolvedProperty = nodeProperty;
  26242. } else {
  26243. this.propertyName = propertyName;
  26244. }
  26245. // select getter / setter
  26246. this.getValue = this.GetterByBindingType[ bindingType ];
  26247. this.setValue = this.SetterByBindingTypeAndVersioning[ bindingType ][ versioning ];
  26248. },
  26249. unbind: function() {
  26250. this.node = null;
  26251. // back to the prototype version of getValue / setValue
  26252. // note: avoiding to mutate the shape of 'this' via 'delete'
  26253. this.getValue = this._getValue_unbound;
  26254. this.setValue = this._setValue_unbound;
  26255. }
  26256. };
  26257. Object.assign( PropertyBinding.prototype, { // prototype, continued
  26258. // these are used to "bind" a nonexistent property
  26259. _getValue_unavailable: function() {},
  26260. _setValue_unavailable: function() {},
  26261. // initial state of these methods that calls 'bind'
  26262. _getValue_unbound: PropertyBinding.prototype.getValue,
  26263. _setValue_unbound: PropertyBinding.prototype.setValue,
  26264. BindingType: {
  26265. Direct: 0,
  26266. EntireArray: 1,
  26267. ArrayElement: 2,
  26268. HasFromToArray: 3
  26269. },
  26270. Versioning: {
  26271. None: 0,
  26272. NeedsUpdate: 1,
  26273. MatrixWorldNeedsUpdate: 2
  26274. },
  26275. GetterByBindingType: [
  26276. function getValue_direct( buffer, offset ) {
  26277. buffer[ offset ] = this.node[ this.propertyName ];
  26278. },
  26279. function getValue_array( buffer, offset ) {
  26280. var source = this.resolvedProperty;
  26281. for ( var i = 0, n = source.length; i !== n; ++ i ) {
  26282. buffer[ offset ++ ] = source[ i ];
  26283. }
  26284. },
  26285. function getValue_arrayElement( buffer, offset ) {
  26286. buffer[ offset ] = this.resolvedProperty[ this.propertyIndex ];
  26287. },
  26288. function getValue_toArray( buffer, offset ) {
  26289. this.resolvedProperty.toArray( buffer, offset );
  26290. }
  26291. ],
  26292. SetterByBindingTypeAndVersioning: [
  26293. [
  26294. // Direct
  26295. function setValue_direct( buffer, offset ) {
  26296. this.node[ this.propertyName ] = buffer[ offset ];
  26297. },
  26298. function setValue_direct_setNeedsUpdate( buffer, offset ) {
  26299. this.node[ this.propertyName ] = buffer[ offset ];
  26300. this.targetObject.needsUpdate = true;
  26301. },
  26302. function setValue_direct_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26303. this.node[ this.propertyName ] = buffer[ offset ];
  26304. this.targetObject.matrixWorldNeedsUpdate = true;
  26305. }
  26306. ], [
  26307. // EntireArray
  26308. function setValue_array( buffer, offset ) {
  26309. var dest = this.resolvedProperty;
  26310. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26311. dest[ i ] = buffer[ offset ++ ];
  26312. }
  26313. },
  26314. function setValue_array_setNeedsUpdate( buffer, offset ) {
  26315. var dest = this.resolvedProperty;
  26316. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26317. dest[ i ] = buffer[ offset ++ ];
  26318. }
  26319. this.targetObject.needsUpdate = true;
  26320. },
  26321. function setValue_array_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26322. var dest = this.resolvedProperty;
  26323. for ( var i = 0, n = dest.length; i !== n; ++ i ) {
  26324. dest[ i ] = buffer[ offset ++ ];
  26325. }
  26326. this.targetObject.matrixWorldNeedsUpdate = true;
  26327. }
  26328. ], [
  26329. // ArrayElement
  26330. function setValue_arrayElement( buffer, offset ) {
  26331. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26332. },
  26333. function setValue_arrayElement_setNeedsUpdate( buffer, offset ) {
  26334. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26335. this.targetObject.needsUpdate = true;
  26336. },
  26337. function setValue_arrayElement_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26338. this.resolvedProperty[ this.propertyIndex ] = buffer[ offset ];
  26339. this.targetObject.matrixWorldNeedsUpdate = true;
  26340. }
  26341. ], [
  26342. // HasToFromArray
  26343. function setValue_fromArray( buffer, offset ) {
  26344. this.resolvedProperty.fromArray( buffer, offset );
  26345. },
  26346. function setValue_fromArray_setNeedsUpdate( buffer, offset ) {
  26347. this.resolvedProperty.fromArray( buffer, offset );
  26348. this.targetObject.needsUpdate = true;
  26349. },
  26350. function setValue_fromArray_setMatrixWorldNeedsUpdate( buffer, offset ) {
  26351. this.resolvedProperty.fromArray( buffer, offset );
  26352. this.targetObject.matrixWorldNeedsUpdate = true;
  26353. }
  26354. ]
  26355. ]
  26356. } );
  26357. PropertyBinding.Composite =
  26358. function( targetGroup, path, optionalParsedPath ) {
  26359. var parsedPath = optionalParsedPath ||
  26360. PropertyBinding.parseTrackName( path );
  26361. this._targetGroup = targetGroup;
  26362. this._bindings = targetGroup.subscribe_( path, parsedPath );
  26363. };
  26364. PropertyBinding.Composite.prototype = {
  26365. constructor: PropertyBinding.Composite,
  26366. getValue: function( array, offset ) {
  26367. this.bind(); // bind all binding
  26368. var firstValidIndex = this._targetGroup.nCachedObjects_,
  26369. binding = this._bindings[ firstValidIndex ];
  26370. // and only call .getValue on the first
  26371. if ( binding !== undefined ) binding.getValue( array, offset );
  26372. },
  26373. setValue: function( array, offset ) {
  26374. var bindings = this._bindings;
  26375. for ( var i = this._targetGroup.nCachedObjects_,
  26376. n = bindings.length; i !== n; ++ i ) {
  26377. bindings[ i ].setValue( array, offset );
  26378. }
  26379. },
  26380. bind: function() {
  26381. var bindings = this._bindings;
  26382. for ( var i = this._targetGroup.nCachedObjects_,
  26383. n = bindings.length; i !== n; ++ i ) {
  26384. bindings[ i ].bind();
  26385. }
  26386. },
  26387. unbind: function() {
  26388. var bindings = this._bindings;
  26389. for ( var i = this._targetGroup.nCachedObjects_,
  26390. n = bindings.length; i !== n; ++ i ) {
  26391. bindings[ i ].unbind();
  26392. }
  26393. }
  26394. };
  26395. PropertyBinding.create = function( root, path, parsedPath ) {
  26396. if ( ! ( root && root.isAnimationObjectGroup ) ) {
  26397. return new PropertyBinding( root, path, parsedPath );
  26398. } else {
  26399. return new PropertyBinding.Composite( root, path, parsedPath );
  26400. }
  26401. };
  26402. PropertyBinding.parseTrackName = function( trackName ) {
  26403. // matches strings in the form of:
  26404. // nodeName.property
  26405. // nodeName.property[accessor]
  26406. // nodeName.material.property[accessor]
  26407. // uuid.property[accessor]
  26408. // uuid.objectName[objectIndex].propertyName[propertyIndex]
  26409. // parentName/nodeName.property
  26410. // parentName/parentName/nodeName.property[index]
  26411. // .bone[Armature.DEF_cog].position
  26412. // scene:helium_balloon_model:helium_balloon_model.position
  26413. // created and tested via https://regex101.com/#javascript
  26414. var re = /^((?:[\w-]+[\/:])*)([\w-]+)?(?:\.([\w-]+)(?:\[(.+)\])?)?\.([\w-]+)(?:\[(.+)\])?$/;
  26415. var matches = re.exec( trackName );
  26416. if ( ! matches ) {
  26417. throw new Error( "cannot parse trackName at all: " + trackName );
  26418. }
  26419. var results = {
  26420. // directoryName: matches[ 1 ], // (tschw) currently unused
  26421. nodeName: matches[ 2 ], // allowed to be null, specified root node.
  26422. objectName: matches[ 3 ],
  26423. objectIndex: matches[ 4 ],
  26424. propertyName: matches[ 5 ],
  26425. propertyIndex: matches[ 6 ] // allowed to be null, specifies that the whole property is set.
  26426. };
  26427. if ( results.propertyName === null || results.propertyName.length === 0 ) {
  26428. throw new Error( "can not parse propertyName from trackName: " + trackName );
  26429. }
  26430. return results;
  26431. };
  26432. PropertyBinding.findNode = function( root, nodeName ) {
  26433. if ( ! nodeName || nodeName === "" || nodeName === "root" || nodeName === "." || nodeName === -1 || nodeName === root.name || nodeName === root.uuid ) {
  26434. return root;
  26435. }
  26436. // search into skeleton bones.
  26437. if ( root.skeleton ) {
  26438. var searchSkeleton = function( skeleton ) {
  26439. for( var i = 0; i < skeleton.bones.length; i ++ ) {
  26440. var bone = skeleton.bones[ i ];
  26441. if ( bone.name === nodeName ) {
  26442. return bone;
  26443. }
  26444. }
  26445. return null;
  26446. };
  26447. var bone = searchSkeleton( root.skeleton );
  26448. if ( bone ) {
  26449. return bone;
  26450. }
  26451. }
  26452. // search into node subtree.
  26453. if ( root.children ) {
  26454. var searchNodeSubtree = function( children ) {
  26455. for( var i = 0; i < children.length; i ++ ) {
  26456. var childNode = children[ i ];
  26457. if ( childNode.name === nodeName || childNode.uuid === nodeName ) {
  26458. return childNode;
  26459. }
  26460. var result = searchNodeSubtree( childNode.children );
  26461. if ( result ) return result;
  26462. }
  26463. return null;
  26464. };
  26465. var subTreeNode = searchNodeSubtree( root.children );
  26466. if ( subTreeNode ) {
  26467. return subTreeNode;
  26468. }
  26469. }
  26470. return null;
  26471. };
  26472. /**
  26473. *
  26474. * A group of objects that receives a shared animation state.
  26475. *
  26476. * Usage:
  26477. *
  26478. * - Add objects you would otherwise pass as 'root' to the
  26479. * constructor or the .clipAction method of AnimationMixer.
  26480. *
  26481. * - Instead pass this object as 'root'.
  26482. *
  26483. * - You can also add and remove objects later when the mixer
  26484. * is running.
  26485. *
  26486. * Note:
  26487. *
  26488. * Objects of this class appear as one object to the mixer,
  26489. * so cache control of the individual objects must be done
  26490. * on the group.
  26491. *
  26492. * Limitation:
  26493. *
  26494. * - The animated properties must be compatible among the
  26495. * all objects in the group.
  26496. *
  26497. * - A single property can either be controlled through a
  26498. * target group or directly, but not both.
  26499. *
  26500. * @author tschw
  26501. */
  26502. function AnimationObjectGroup( var_args ) {
  26503. this.uuid = _Math.generateUUID();
  26504. // cached objects followed by the active ones
  26505. this._objects = Array.prototype.slice.call( arguments );
  26506. this.nCachedObjects_ = 0; // threshold
  26507. // note: read by PropertyBinding.Composite
  26508. var indices = {};
  26509. this._indicesByUUID = indices; // for bookkeeping
  26510. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26511. indices[ arguments[ i ].uuid ] = i;
  26512. }
  26513. this._paths = []; // inside: string
  26514. this._parsedPaths = []; // inside: { we don't care, here }
  26515. this._bindings = []; // inside: Array< PropertyBinding >
  26516. this._bindingsIndicesByPath = {}; // inside: indices in these arrays
  26517. var scope = this;
  26518. this.stats = {
  26519. objects: {
  26520. get total() { return scope._objects.length; },
  26521. get inUse() { return this.total - scope.nCachedObjects_; }
  26522. },
  26523. get bindingsPerObject() { return scope._bindings.length; }
  26524. };
  26525. }
  26526. AnimationObjectGroup.prototype = {
  26527. constructor: AnimationObjectGroup,
  26528. isAnimationObjectGroup: true,
  26529. add: function( var_args ) {
  26530. var objects = this._objects,
  26531. nObjects = objects.length,
  26532. nCachedObjects = this.nCachedObjects_,
  26533. indicesByUUID = this._indicesByUUID,
  26534. paths = this._paths,
  26535. parsedPaths = this._parsedPaths,
  26536. bindings = this._bindings,
  26537. nBindings = bindings.length;
  26538. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26539. var object = arguments[ i ],
  26540. uuid = object.uuid,
  26541. index = indicesByUUID[ uuid ],
  26542. knownObject = undefined;
  26543. if ( index === undefined ) {
  26544. // unknown object -> add it to the ACTIVE region
  26545. index = nObjects ++;
  26546. indicesByUUID[ uuid ] = index;
  26547. objects.push( object );
  26548. // accounting is done, now do the same for all bindings
  26549. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26550. bindings[ j ].push(
  26551. new PropertyBinding(
  26552. object, paths[ j ], parsedPaths[ j ] ) );
  26553. }
  26554. } else if ( index < nCachedObjects ) {
  26555. knownObject = objects[ index ];
  26556. // move existing object to the ACTIVE region
  26557. var firstActiveIndex = -- nCachedObjects,
  26558. lastCachedObject = objects[ firstActiveIndex ];
  26559. indicesByUUID[ lastCachedObject.uuid ] = index;
  26560. objects[ index ] = lastCachedObject;
  26561. indicesByUUID[ uuid ] = firstActiveIndex;
  26562. objects[ firstActiveIndex ] = object;
  26563. // accounting is done, now do the same for all bindings
  26564. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26565. var bindingsForPath = bindings[ j ],
  26566. lastCached = bindingsForPath[ firstActiveIndex ],
  26567. binding = bindingsForPath[ index ];
  26568. bindingsForPath[ index ] = lastCached;
  26569. if ( binding === undefined ) {
  26570. // since we do not bother to create new bindings
  26571. // for objects that are cached, the binding may
  26572. // or may not exist
  26573. binding = new PropertyBinding(
  26574. object, paths[ j ], parsedPaths[ j ] );
  26575. }
  26576. bindingsForPath[ firstActiveIndex ] = binding;
  26577. }
  26578. } else if ( objects[ index ] !== knownObject) {
  26579. console.error( "Different objects with the same UUID " +
  26580. "detected. Clean the caches or recreate your " +
  26581. "infrastructure when reloading scenes..." );
  26582. } // else the object is already where we want it to be
  26583. } // for arguments
  26584. this.nCachedObjects_ = nCachedObjects;
  26585. },
  26586. remove: function( var_args ) {
  26587. var objects = this._objects,
  26588. nCachedObjects = this.nCachedObjects_,
  26589. indicesByUUID = this._indicesByUUID,
  26590. bindings = this._bindings,
  26591. nBindings = bindings.length;
  26592. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26593. var object = arguments[ i ],
  26594. uuid = object.uuid,
  26595. index = indicesByUUID[ uuid ];
  26596. if ( index !== undefined && index >= nCachedObjects ) {
  26597. // move existing object into the CACHED region
  26598. var lastCachedIndex = nCachedObjects ++,
  26599. firstActiveObject = objects[ lastCachedIndex ];
  26600. indicesByUUID[ firstActiveObject.uuid ] = index;
  26601. objects[ index ] = firstActiveObject;
  26602. indicesByUUID[ uuid ] = lastCachedIndex;
  26603. objects[ lastCachedIndex ] = object;
  26604. // accounting is done, now do the same for all bindings
  26605. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26606. var bindingsForPath = bindings[ j ],
  26607. firstActive = bindingsForPath[ lastCachedIndex ],
  26608. binding = bindingsForPath[ index ];
  26609. bindingsForPath[ index ] = firstActive;
  26610. bindingsForPath[ lastCachedIndex ] = binding;
  26611. }
  26612. }
  26613. } // for arguments
  26614. this.nCachedObjects_ = nCachedObjects;
  26615. },
  26616. // remove & forget
  26617. uncache: function( var_args ) {
  26618. var objects = this._objects,
  26619. nObjects = objects.length,
  26620. nCachedObjects = this.nCachedObjects_,
  26621. indicesByUUID = this._indicesByUUID,
  26622. bindings = this._bindings,
  26623. nBindings = bindings.length;
  26624. for ( var i = 0, n = arguments.length; i !== n; ++ i ) {
  26625. var object = arguments[ i ],
  26626. uuid = object.uuid,
  26627. index = indicesByUUID[ uuid ];
  26628. if ( index !== undefined ) {
  26629. delete indicesByUUID[ uuid ];
  26630. if ( index < nCachedObjects ) {
  26631. // object is cached, shrink the CACHED region
  26632. var firstActiveIndex = -- nCachedObjects,
  26633. lastCachedObject = objects[ firstActiveIndex ],
  26634. lastIndex = -- nObjects,
  26635. lastObject = objects[ lastIndex ];
  26636. // last cached object takes this object's place
  26637. indicesByUUID[ lastCachedObject.uuid ] = index;
  26638. objects[ index ] = lastCachedObject;
  26639. // last object goes to the activated slot and pop
  26640. indicesByUUID[ lastObject.uuid ] = firstActiveIndex;
  26641. objects[ firstActiveIndex ] = lastObject;
  26642. objects.pop();
  26643. // accounting is done, now do the same for all bindings
  26644. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26645. var bindingsForPath = bindings[ j ],
  26646. lastCached = bindingsForPath[ firstActiveIndex ],
  26647. last = bindingsForPath[ lastIndex ];
  26648. bindingsForPath[ index ] = lastCached;
  26649. bindingsForPath[ firstActiveIndex ] = last;
  26650. bindingsForPath.pop();
  26651. }
  26652. } else {
  26653. // object is active, just swap with the last and pop
  26654. var lastIndex = -- nObjects,
  26655. lastObject = objects[ lastIndex ];
  26656. indicesByUUID[ lastObject.uuid ] = index;
  26657. objects[ index ] = lastObject;
  26658. objects.pop();
  26659. // accounting is done, now do the same for all bindings
  26660. for ( var j = 0, m = nBindings; j !== m; ++ j ) {
  26661. var bindingsForPath = bindings[ j ];
  26662. bindingsForPath[ index ] = bindingsForPath[ lastIndex ];
  26663. bindingsForPath.pop();
  26664. }
  26665. } // cached or active
  26666. } // if object is known
  26667. } // for arguments
  26668. this.nCachedObjects_ = nCachedObjects;
  26669. },
  26670. // Internal interface used by befriended PropertyBinding.Composite:
  26671. subscribe_: function( path, parsedPath ) {
  26672. // returns an array of bindings for the given path that is changed
  26673. // according to the contained objects in the group
  26674. var indicesByPath = this._bindingsIndicesByPath,
  26675. index = indicesByPath[ path ],
  26676. bindings = this._bindings;
  26677. if ( index !== undefined ) return bindings[ index ];
  26678. var paths = this._paths,
  26679. parsedPaths = this._parsedPaths,
  26680. objects = this._objects,
  26681. nObjects = objects.length,
  26682. nCachedObjects = this.nCachedObjects_,
  26683. bindingsForPath = new Array( nObjects );
  26684. index = bindings.length;
  26685. indicesByPath[ path ] = index;
  26686. paths.push( path );
  26687. parsedPaths.push( parsedPath );
  26688. bindings.push( bindingsForPath );
  26689. for ( var i = nCachedObjects,
  26690. n = objects.length; i !== n; ++ i ) {
  26691. var object = objects[ i ];
  26692. bindingsForPath[ i ] =
  26693. new PropertyBinding( object, path, parsedPath );
  26694. }
  26695. return bindingsForPath;
  26696. },
  26697. unsubscribe_: function( path ) {
  26698. // tells the group to forget about a property path and no longer
  26699. // update the array previously obtained with 'subscribe_'
  26700. var indicesByPath = this._bindingsIndicesByPath,
  26701. index = indicesByPath[ path ];
  26702. if ( index !== undefined ) {
  26703. var paths = this._paths,
  26704. parsedPaths = this._parsedPaths,
  26705. bindings = this._bindings,
  26706. lastBindingsIndex = bindings.length - 1,
  26707. lastBindings = bindings[ lastBindingsIndex ],
  26708. lastBindingsPath = path[ lastBindingsIndex ];
  26709. indicesByPath[ lastBindingsPath ] = index;
  26710. bindings[ index ] = lastBindings;
  26711. bindings.pop();
  26712. parsedPaths[ index ] = parsedPaths[ lastBindingsIndex ];
  26713. parsedPaths.pop();
  26714. paths[ index ] = paths[ lastBindingsIndex ];
  26715. paths.pop();
  26716. }
  26717. }
  26718. };
  26719. /**
  26720. *
  26721. * Action provided by AnimationMixer for scheduling clip playback on specific
  26722. * objects.
  26723. *
  26724. * @author Ben Houston / http://clara.io/
  26725. * @author David Sarno / http://lighthaus.us/
  26726. * @author tschw
  26727. *
  26728. */
  26729. function AnimationAction( mixer, clip, localRoot ) {
  26730. this._mixer = mixer;
  26731. this._clip = clip;
  26732. this._localRoot = localRoot || null;
  26733. var tracks = clip.tracks,
  26734. nTracks = tracks.length,
  26735. interpolants = new Array( nTracks );
  26736. var interpolantSettings = {
  26737. endingStart: ZeroCurvatureEnding,
  26738. endingEnd: ZeroCurvatureEnding
  26739. };
  26740. for ( var i = 0; i !== nTracks; ++ i ) {
  26741. var interpolant = tracks[ i ].createInterpolant( null );
  26742. interpolants[ i ] = interpolant;
  26743. interpolant.settings = interpolantSettings;
  26744. }
  26745. this._interpolantSettings = interpolantSettings;
  26746. this._interpolants = interpolants; // bound by the mixer
  26747. // inside: PropertyMixer (managed by the mixer)
  26748. this._propertyBindings = new Array( nTracks );
  26749. this._cacheIndex = null; // for the memory manager
  26750. this._byClipCacheIndex = null; // for the memory manager
  26751. this._timeScaleInterpolant = null;
  26752. this._weightInterpolant = null;
  26753. this.loop = LoopRepeat;
  26754. this._loopCount = -1;
  26755. // global mixer time when the action is to be started
  26756. // it's set back to 'null' upon start of the action
  26757. this._startTime = null;
  26758. // scaled local time of the action
  26759. // gets clamped or wrapped to 0..clip.duration according to loop
  26760. this.time = 0;
  26761. this.timeScale = 1;
  26762. this._effectiveTimeScale = 1;
  26763. this.weight = 1;
  26764. this._effectiveWeight = 1;
  26765. this.repetitions = Infinity; // no. of repetitions when looping
  26766. this.paused = false; // false -> zero effective time scale
  26767. this.enabled = true; // true -> zero effective weight
  26768. this.clampWhenFinished = false; // keep feeding the last frame?
  26769. this.zeroSlopeAtStart = true; // for smooth interpolation w/o separate
  26770. this.zeroSlopeAtEnd = true; // clips for start, loop and end
  26771. }
  26772. AnimationAction.prototype = {
  26773. constructor: AnimationAction,
  26774. // State & Scheduling
  26775. play: function() {
  26776. this._mixer._activateAction( this );
  26777. return this;
  26778. },
  26779. stop: function() {
  26780. this._mixer._deactivateAction( this );
  26781. return this.reset();
  26782. },
  26783. reset: function() {
  26784. this.paused = false;
  26785. this.enabled = true;
  26786. this.time = 0; // restart clip
  26787. this._loopCount = -1; // forget previous loops
  26788. this._startTime = null; // forget scheduling
  26789. return this.stopFading().stopWarping();
  26790. },
  26791. isRunning: function() {
  26792. return this.enabled && ! this.paused && this.timeScale !== 0 &&
  26793. this._startTime === null && this._mixer._isActiveAction( this );
  26794. },
  26795. // return true when play has been called
  26796. isScheduled: function() {
  26797. return this._mixer._isActiveAction( this );
  26798. },
  26799. startAt: function( time ) {
  26800. this._startTime = time;
  26801. return this;
  26802. },
  26803. setLoop: function( mode, repetitions ) {
  26804. this.loop = mode;
  26805. this.repetitions = repetitions;
  26806. return this;
  26807. },
  26808. // Weight
  26809. // set the weight stopping any scheduled fading
  26810. // although .enabled = false yields an effective weight of zero, this
  26811. // method does *not* change .enabled, because it would be confusing
  26812. setEffectiveWeight: function( weight ) {
  26813. this.weight = weight;
  26814. // note: same logic as when updated at runtime
  26815. this._effectiveWeight = this.enabled ? weight : 0;
  26816. return this.stopFading();
  26817. },
  26818. // return the weight considering fading and .enabled
  26819. getEffectiveWeight: function() {
  26820. return this._effectiveWeight;
  26821. },
  26822. fadeIn: function( duration ) {
  26823. return this._scheduleFading( duration, 0, 1 );
  26824. },
  26825. fadeOut: function( duration ) {
  26826. return this._scheduleFading( duration, 1, 0 );
  26827. },
  26828. crossFadeFrom: function( fadeOutAction, duration, warp ) {
  26829. fadeOutAction.fadeOut( duration );
  26830. this.fadeIn( duration );
  26831. if( warp ) {
  26832. var fadeInDuration = this._clip.duration,
  26833. fadeOutDuration = fadeOutAction._clip.duration,
  26834. startEndRatio = fadeOutDuration / fadeInDuration,
  26835. endStartRatio = fadeInDuration / fadeOutDuration;
  26836. fadeOutAction.warp( 1.0, startEndRatio, duration );
  26837. this.warp( endStartRatio, 1.0, duration );
  26838. }
  26839. return this;
  26840. },
  26841. crossFadeTo: function( fadeInAction, duration, warp ) {
  26842. return fadeInAction.crossFadeFrom( this, duration, warp );
  26843. },
  26844. stopFading: function() {
  26845. var weightInterpolant = this._weightInterpolant;
  26846. if ( weightInterpolant !== null ) {
  26847. this._weightInterpolant = null;
  26848. this._mixer._takeBackControlInterpolant( weightInterpolant );
  26849. }
  26850. return this;
  26851. },
  26852. // Time Scale Control
  26853. // set the weight stopping any scheduled warping
  26854. // although .paused = true yields an effective time scale of zero, this
  26855. // method does *not* change .paused, because it would be confusing
  26856. setEffectiveTimeScale: function( timeScale ) {
  26857. this.timeScale = timeScale;
  26858. this._effectiveTimeScale = this.paused ? 0 :timeScale;
  26859. return this.stopWarping();
  26860. },
  26861. // return the time scale considering warping and .paused
  26862. getEffectiveTimeScale: function() {
  26863. return this._effectiveTimeScale;
  26864. },
  26865. setDuration: function( duration ) {
  26866. this.timeScale = this._clip.duration / duration;
  26867. return this.stopWarping();
  26868. },
  26869. syncWith: function( action ) {
  26870. this.time = action.time;
  26871. this.timeScale = action.timeScale;
  26872. return this.stopWarping();
  26873. },
  26874. halt: function( duration ) {
  26875. return this.warp( this._effectiveTimeScale, 0, duration );
  26876. },
  26877. warp: function( startTimeScale, endTimeScale, duration ) {
  26878. var mixer = this._mixer, now = mixer.time,
  26879. interpolant = this._timeScaleInterpolant,
  26880. timeScale = this.timeScale;
  26881. if ( interpolant === null ) {
  26882. interpolant = mixer._lendControlInterpolant();
  26883. this._timeScaleInterpolant = interpolant;
  26884. }
  26885. var times = interpolant.parameterPositions,
  26886. values = interpolant.sampleValues;
  26887. times[ 0 ] = now;
  26888. times[ 1 ] = now + duration;
  26889. values[ 0 ] = startTimeScale / timeScale;
  26890. values[ 1 ] = endTimeScale / timeScale;
  26891. return this;
  26892. },
  26893. stopWarping: function() {
  26894. var timeScaleInterpolant = this._timeScaleInterpolant;
  26895. if ( timeScaleInterpolant !== null ) {
  26896. this._timeScaleInterpolant = null;
  26897. this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
  26898. }
  26899. return this;
  26900. },
  26901. // Object Accessors
  26902. getMixer: function() {
  26903. return this._mixer;
  26904. },
  26905. getClip: function() {
  26906. return this._clip;
  26907. },
  26908. getRoot: function() {
  26909. return this._localRoot || this._mixer._root;
  26910. },
  26911. // Interna
  26912. _update: function( time, deltaTime, timeDirection, accuIndex ) {
  26913. // called by the mixer
  26914. var startTime = this._startTime;
  26915. if ( startTime !== null ) {
  26916. // check for scheduled start of action
  26917. var timeRunning = ( time - startTime ) * timeDirection;
  26918. if ( timeRunning < 0 || timeDirection === 0 ) {
  26919. return; // yet to come / don't decide when delta = 0
  26920. }
  26921. // start
  26922. this._startTime = null; // unschedule
  26923. deltaTime = timeDirection * timeRunning;
  26924. }
  26925. // apply time scale and advance time
  26926. deltaTime *= this._updateTimeScale( time );
  26927. var clipTime = this._updateTime( deltaTime );
  26928. // note: _updateTime may disable the action resulting in
  26929. // an effective weight of 0
  26930. var weight = this._updateWeight( time );
  26931. if ( weight > 0 ) {
  26932. var interpolants = this._interpolants;
  26933. var propertyMixers = this._propertyBindings;
  26934. for ( var j = 0, m = interpolants.length; j !== m; ++ j ) {
  26935. interpolants[ j ].evaluate( clipTime );
  26936. propertyMixers[ j ].accumulate( accuIndex, weight );
  26937. }
  26938. }
  26939. },
  26940. _updateWeight: function( time ) {
  26941. var weight = 0;
  26942. if ( this.enabled ) {
  26943. weight = this.weight;
  26944. var interpolant = this._weightInterpolant;
  26945. if ( interpolant !== null ) {
  26946. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  26947. weight *= interpolantValue;
  26948. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26949. this.stopFading();
  26950. if ( interpolantValue === 0 ) {
  26951. // faded out, disable
  26952. this.enabled = false;
  26953. }
  26954. }
  26955. }
  26956. }
  26957. this._effectiveWeight = weight;
  26958. return weight;
  26959. },
  26960. _updateTimeScale: function( time ) {
  26961. var timeScale = 0;
  26962. if ( ! this.paused ) {
  26963. timeScale = this.timeScale;
  26964. var interpolant = this._timeScaleInterpolant;
  26965. if ( interpolant !== null ) {
  26966. var interpolantValue = interpolant.evaluate( time )[ 0 ];
  26967. timeScale *= interpolantValue;
  26968. if ( time > interpolant.parameterPositions[ 1 ] ) {
  26969. this.stopWarping();
  26970. if ( timeScale === 0 ) {
  26971. // motion has halted, pause
  26972. this.paused = true;
  26973. } else {
  26974. // warp done - apply final time scale
  26975. this.timeScale = timeScale;
  26976. }
  26977. }
  26978. }
  26979. }
  26980. this._effectiveTimeScale = timeScale;
  26981. return timeScale;
  26982. },
  26983. _updateTime: function( deltaTime ) {
  26984. var time = this.time + deltaTime;
  26985. if ( deltaTime === 0 ) return time;
  26986. var duration = this._clip.duration,
  26987. loop = this.loop,
  26988. loopCount = this._loopCount;
  26989. if ( loop === LoopOnce ) {
  26990. if ( loopCount === -1 ) {
  26991. // just started
  26992. this._loopCount = 0;
  26993. this._setEndings( true, true, false );
  26994. }
  26995. handle_stop: {
  26996. if ( time >= duration ) {
  26997. time = duration;
  26998. } else if ( time < 0 ) {
  26999. time = 0;
  27000. } else break handle_stop;
  27001. if ( this.clampWhenFinished ) this.paused = true;
  27002. else this.enabled = false;
  27003. this._mixer.dispatchEvent( {
  27004. type: 'finished', action: this,
  27005. direction: deltaTime < 0 ? -1 : 1
  27006. } );
  27007. }
  27008. } else { // repetitive Repeat or PingPong
  27009. var pingPong = ( loop === LoopPingPong );
  27010. if ( loopCount === -1 ) {
  27011. // just started
  27012. if ( deltaTime >= 0 ) {
  27013. loopCount = 0;
  27014. this._setEndings(
  27015. true, this.repetitions === 0, pingPong );
  27016. } else {
  27017. // when looping in reverse direction, the initial
  27018. // transition through zero counts as a repetition,
  27019. // so leave loopCount at -1
  27020. this._setEndings(
  27021. this.repetitions === 0, true, pingPong );
  27022. }
  27023. }
  27024. if ( time >= duration || time < 0 ) {
  27025. // wrap around
  27026. var loopDelta = Math.floor( time / duration ); // signed
  27027. time -= duration * loopDelta;
  27028. loopCount += Math.abs( loopDelta );
  27029. var pending = this.repetitions - loopCount;
  27030. if ( pending < 0 ) {
  27031. // have to stop (switch state, clamp time, fire event)
  27032. if ( this.clampWhenFinished ) this.paused = true;
  27033. else this.enabled = false;
  27034. time = deltaTime > 0 ? duration : 0;
  27035. this._mixer.dispatchEvent( {
  27036. type: 'finished', action: this,
  27037. direction: deltaTime > 0 ? 1 : -1
  27038. } );
  27039. } else {
  27040. // keep running
  27041. if ( pending === 0 ) {
  27042. // entering the last round
  27043. var atStart = deltaTime < 0;
  27044. this._setEndings( atStart, ! atStart, pingPong );
  27045. } else {
  27046. this._setEndings( false, false, pingPong );
  27047. }
  27048. this._loopCount = loopCount;
  27049. this._mixer.dispatchEvent( {
  27050. type: 'loop', action: this, loopDelta: loopDelta
  27051. } );
  27052. }
  27053. }
  27054. if ( pingPong && ( loopCount & 1 ) === 1 ) {
  27055. // invert time for the "pong round"
  27056. this.time = time;
  27057. return duration - time;
  27058. }
  27059. }
  27060. this.time = time;
  27061. return time;
  27062. },
  27063. _setEndings: function( atStart, atEnd, pingPong ) {
  27064. var settings = this._interpolantSettings;
  27065. if ( pingPong ) {
  27066. settings.endingStart = ZeroSlopeEnding;
  27067. settings.endingEnd = ZeroSlopeEnding;
  27068. } else {
  27069. // assuming for LoopOnce atStart == atEnd == true
  27070. if ( atStart ) {
  27071. settings.endingStart = this.zeroSlopeAtStart ?
  27072. ZeroSlopeEnding : ZeroCurvatureEnding;
  27073. } else {
  27074. settings.endingStart = WrapAroundEnding;
  27075. }
  27076. if ( atEnd ) {
  27077. settings.endingEnd = this.zeroSlopeAtEnd ?
  27078. ZeroSlopeEnding : ZeroCurvatureEnding;
  27079. } else {
  27080. settings.endingEnd = WrapAroundEnding;
  27081. }
  27082. }
  27083. },
  27084. _scheduleFading: function( duration, weightNow, weightThen ) {
  27085. var mixer = this._mixer, now = mixer.time,
  27086. interpolant = this._weightInterpolant;
  27087. if ( interpolant === null ) {
  27088. interpolant = mixer._lendControlInterpolant();
  27089. this._weightInterpolant = interpolant;
  27090. }
  27091. var times = interpolant.parameterPositions,
  27092. values = interpolant.sampleValues;
  27093. times[ 0 ] = now; values[ 0 ] = weightNow;
  27094. times[ 1 ] = now + duration; values[ 1 ] = weightThen;
  27095. return this;
  27096. }
  27097. };
  27098. /**
  27099. *
  27100. * Player for AnimationClips.
  27101. *
  27102. *
  27103. * @author Ben Houston / http://clara.io/
  27104. * @author David Sarno / http://lighthaus.us/
  27105. * @author tschw
  27106. */
  27107. function AnimationMixer( root ) {
  27108. this._root = root;
  27109. this._initMemoryManager();
  27110. this._accuIndex = 0;
  27111. this.time = 0;
  27112. this.timeScale = 1.0;
  27113. }
  27114. Object.assign( AnimationMixer.prototype, EventDispatcher.prototype, {
  27115. // return an action for a clip optionally using a custom root target
  27116. // object (this method allocates a lot of dynamic memory in case a
  27117. // previously unknown clip/root combination is specified)
  27118. clipAction: function( clip, optionalRoot ) {
  27119. var root = optionalRoot || this._root,
  27120. rootUuid = root.uuid,
  27121. clipObject = typeof clip === 'string' ?
  27122. AnimationClip.findByName( root, clip ) : clip,
  27123. clipUuid = clipObject !== null ? clipObject.uuid : clip,
  27124. actionsForClip = this._actionsByClip[ clipUuid ],
  27125. prototypeAction = null;
  27126. if ( actionsForClip !== undefined ) {
  27127. var existingAction =
  27128. actionsForClip.actionByRoot[ rootUuid ];
  27129. if ( existingAction !== undefined ) {
  27130. return existingAction;
  27131. }
  27132. // we know the clip, so we don't have to parse all
  27133. // the bindings again but can just copy
  27134. prototypeAction = actionsForClip.knownActions[ 0 ];
  27135. // also, take the clip from the prototype action
  27136. if ( clipObject === null )
  27137. clipObject = prototypeAction._clip;
  27138. }
  27139. // clip must be known when specified via string
  27140. if ( clipObject === null ) return null;
  27141. // allocate all resources required to run it
  27142. var newAction = new AnimationAction( this, clipObject, optionalRoot );
  27143. this._bindAction( newAction, prototypeAction );
  27144. // and make the action known to the memory manager
  27145. this._addInactiveAction( newAction, clipUuid, rootUuid );
  27146. return newAction;
  27147. },
  27148. // get an existing action
  27149. existingAction: function( clip, optionalRoot ) {
  27150. var root = optionalRoot || this._root,
  27151. rootUuid = root.uuid,
  27152. clipObject = typeof clip === 'string' ?
  27153. AnimationClip.findByName( root, clip ) : clip,
  27154. clipUuid = clipObject ? clipObject.uuid : clip,
  27155. actionsForClip = this._actionsByClip[ clipUuid ];
  27156. if ( actionsForClip !== undefined ) {
  27157. return actionsForClip.actionByRoot[ rootUuid ] || null;
  27158. }
  27159. return null;
  27160. },
  27161. // deactivates all previously scheduled actions
  27162. stopAllAction: function() {
  27163. var actions = this._actions,
  27164. nActions = this._nActiveActions,
  27165. bindings = this._bindings,
  27166. nBindings = this._nActiveBindings;
  27167. this._nActiveActions = 0;
  27168. this._nActiveBindings = 0;
  27169. for ( var i = 0; i !== nActions; ++ i ) {
  27170. actions[ i ].reset();
  27171. }
  27172. for ( var i = 0; i !== nBindings; ++ i ) {
  27173. bindings[ i ].useCount = 0;
  27174. }
  27175. return this;
  27176. },
  27177. // advance the time and update apply the animation
  27178. update: function( deltaTime ) {
  27179. deltaTime *= this.timeScale;
  27180. var actions = this._actions,
  27181. nActions = this._nActiveActions,
  27182. time = this.time += deltaTime,
  27183. timeDirection = Math.sign( deltaTime ),
  27184. accuIndex = this._accuIndex ^= 1;
  27185. // run active actions
  27186. for ( var i = 0; i !== nActions; ++ i ) {
  27187. var action = actions[ i ];
  27188. if ( action.enabled ) {
  27189. action._update( time, deltaTime, timeDirection, accuIndex );
  27190. }
  27191. }
  27192. // update scene graph
  27193. var bindings = this._bindings,
  27194. nBindings = this._nActiveBindings;
  27195. for ( var i = 0; i !== nBindings; ++ i ) {
  27196. bindings[ i ].apply( accuIndex );
  27197. }
  27198. return this;
  27199. },
  27200. // return this mixer's root target object
  27201. getRoot: function() {
  27202. return this._root;
  27203. },
  27204. // free all resources specific to a particular clip
  27205. uncacheClip: function( clip ) {
  27206. var actions = this._actions,
  27207. clipUuid = clip.uuid,
  27208. actionsByClip = this._actionsByClip,
  27209. actionsForClip = actionsByClip[ clipUuid ];
  27210. if ( actionsForClip !== undefined ) {
  27211. // note: just calling _removeInactiveAction would mess up the
  27212. // iteration state and also require updating the state we can
  27213. // just throw away
  27214. var actionsToRemove = actionsForClip.knownActions;
  27215. for ( var i = 0, n = actionsToRemove.length; i !== n; ++ i ) {
  27216. var action = actionsToRemove[ i ];
  27217. this._deactivateAction( action );
  27218. var cacheIndex = action._cacheIndex,
  27219. lastInactiveAction = actions[ actions.length - 1 ];
  27220. action._cacheIndex = null;
  27221. action._byClipCacheIndex = null;
  27222. lastInactiveAction._cacheIndex = cacheIndex;
  27223. actions[ cacheIndex ] = lastInactiveAction;
  27224. actions.pop();
  27225. this._removeInactiveBindingsForAction( action );
  27226. }
  27227. delete actionsByClip[ clipUuid ];
  27228. }
  27229. },
  27230. // free all resources specific to a particular root target object
  27231. uncacheRoot: function( root ) {
  27232. var rootUuid = root.uuid,
  27233. actionsByClip = this._actionsByClip;
  27234. for ( var clipUuid in actionsByClip ) {
  27235. var actionByRoot = actionsByClip[ clipUuid ].actionByRoot,
  27236. action = actionByRoot[ rootUuid ];
  27237. if ( action !== undefined ) {
  27238. this._deactivateAction( action );
  27239. this._removeInactiveAction( action );
  27240. }
  27241. }
  27242. var bindingsByRoot = this._bindingsByRootAndName,
  27243. bindingByName = bindingsByRoot[ rootUuid ];
  27244. if ( bindingByName !== undefined ) {
  27245. for ( var trackName in bindingByName ) {
  27246. var binding = bindingByName[ trackName ];
  27247. binding.restoreOriginalState();
  27248. this._removeInactiveBinding( binding );
  27249. }
  27250. }
  27251. },
  27252. // remove a targeted clip from the cache
  27253. uncacheAction: function( clip, optionalRoot ) {
  27254. var action = this.existingAction( clip, optionalRoot );
  27255. if ( action !== null ) {
  27256. this._deactivateAction( action );
  27257. this._removeInactiveAction( action );
  27258. }
  27259. }
  27260. } );
  27261. // Implementation details:
  27262. Object.assign( AnimationMixer.prototype, {
  27263. _bindAction: function( action, prototypeAction ) {
  27264. var root = action._localRoot || this._root,
  27265. tracks = action._clip.tracks,
  27266. nTracks = tracks.length,
  27267. bindings = action._propertyBindings,
  27268. interpolants = action._interpolants,
  27269. rootUuid = root.uuid,
  27270. bindingsByRoot = this._bindingsByRootAndName,
  27271. bindingsByName = bindingsByRoot[ rootUuid ];
  27272. if ( bindingsByName === undefined ) {
  27273. bindingsByName = {};
  27274. bindingsByRoot[ rootUuid ] = bindingsByName;
  27275. }
  27276. for ( var i = 0; i !== nTracks; ++ i ) {
  27277. var track = tracks[ i ],
  27278. trackName = track.name,
  27279. binding = bindingsByName[ trackName ];
  27280. if ( binding !== undefined ) {
  27281. bindings[ i ] = binding;
  27282. } else {
  27283. binding = bindings[ i ];
  27284. if ( binding !== undefined ) {
  27285. // existing binding, make sure the cache knows
  27286. if ( binding._cacheIndex === null ) {
  27287. ++ binding.referenceCount;
  27288. this._addInactiveBinding( binding, rootUuid, trackName );
  27289. }
  27290. continue;
  27291. }
  27292. var path = prototypeAction && prototypeAction.
  27293. _propertyBindings[ i ].binding.parsedPath;
  27294. binding = new PropertyMixer(
  27295. PropertyBinding.create( root, trackName, path ),
  27296. track.ValueTypeName, track.getValueSize() );
  27297. ++ binding.referenceCount;
  27298. this._addInactiveBinding( binding, rootUuid, trackName );
  27299. bindings[ i ] = binding;
  27300. }
  27301. interpolants[ i ].resultBuffer = binding.buffer;
  27302. }
  27303. },
  27304. _activateAction: function( action ) {
  27305. if ( ! this._isActiveAction( action ) ) {
  27306. if ( action._cacheIndex === null ) {
  27307. // this action has been forgotten by the cache, but the user
  27308. // appears to be still using it -> rebind
  27309. var rootUuid = ( action._localRoot || this._root ).uuid,
  27310. clipUuid = action._clip.uuid,
  27311. actionsForClip = this._actionsByClip[ clipUuid ];
  27312. this._bindAction( action,
  27313. actionsForClip && actionsForClip.knownActions[ 0 ] );
  27314. this._addInactiveAction( action, clipUuid, rootUuid );
  27315. }
  27316. var bindings = action._propertyBindings;
  27317. // increment reference counts / sort out state
  27318. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27319. var binding = bindings[ i ];
  27320. if ( binding.useCount ++ === 0 ) {
  27321. this._lendBinding( binding );
  27322. binding.saveOriginalState();
  27323. }
  27324. }
  27325. this._lendAction( action );
  27326. }
  27327. },
  27328. _deactivateAction: function( action ) {
  27329. if ( this._isActiveAction( action ) ) {
  27330. var bindings = action._propertyBindings;
  27331. // decrement reference counts / sort out state
  27332. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27333. var binding = bindings[ i ];
  27334. if ( -- binding.useCount === 0 ) {
  27335. binding.restoreOriginalState();
  27336. this._takeBackBinding( binding );
  27337. }
  27338. }
  27339. this._takeBackAction( action );
  27340. }
  27341. },
  27342. // Memory manager
  27343. _initMemoryManager: function() {
  27344. this._actions = []; // 'nActiveActions' followed by inactive ones
  27345. this._nActiveActions = 0;
  27346. this._actionsByClip = {};
  27347. // inside:
  27348. // {
  27349. // knownActions: Array< AnimationAction > - used as prototypes
  27350. // actionByRoot: AnimationAction - lookup
  27351. // }
  27352. this._bindings = []; // 'nActiveBindings' followed by inactive ones
  27353. this._nActiveBindings = 0;
  27354. this._bindingsByRootAndName = {}; // inside: Map< name, PropertyMixer >
  27355. this._controlInterpolants = []; // same game as above
  27356. this._nActiveControlInterpolants = 0;
  27357. var scope = this;
  27358. this.stats = {
  27359. actions: {
  27360. get total() { return scope._actions.length; },
  27361. get inUse() { return scope._nActiveActions; }
  27362. },
  27363. bindings: {
  27364. get total() { return scope._bindings.length; },
  27365. get inUse() { return scope._nActiveBindings; }
  27366. },
  27367. controlInterpolants: {
  27368. get total() { return scope._controlInterpolants.length; },
  27369. get inUse() { return scope._nActiveControlInterpolants; }
  27370. }
  27371. };
  27372. },
  27373. // Memory management for AnimationAction objects
  27374. _isActiveAction: function( action ) {
  27375. var index = action._cacheIndex;
  27376. return index !== null && index < this._nActiveActions;
  27377. },
  27378. _addInactiveAction: function( action, clipUuid, rootUuid ) {
  27379. var actions = this._actions,
  27380. actionsByClip = this._actionsByClip,
  27381. actionsForClip = actionsByClip[ clipUuid ];
  27382. if ( actionsForClip === undefined ) {
  27383. actionsForClip = {
  27384. knownActions: [ action ],
  27385. actionByRoot: {}
  27386. };
  27387. action._byClipCacheIndex = 0;
  27388. actionsByClip[ clipUuid ] = actionsForClip;
  27389. } else {
  27390. var knownActions = actionsForClip.knownActions;
  27391. action._byClipCacheIndex = knownActions.length;
  27392. knownActions.push( action );
  27393. }
  27394. action._cacheIndex = actions.length;
  27395. actions.push( action );
  27396. actionsForClip.actionByRoot[ rootUuid ] = action;
  27397. },
  27398. _removeInactiveAction: function( action ) {
  27399. var actions = this._actions,
  27400. lastInactiveAction = actions[ actions.length - 1 ],
  27401. cacheIndex = action._cacheIndex;
  27402. lastInactiveAction._cacheIndex = cacheIndex;
  27403. actions[ cacheIndex ] = lastInactiveAction;
  27404. actions.pop();
  27405. action._cacheIndex = null;
  27406. var clipUuid = action._clip.uuid,
  27407. actionsByClip = this._actionsByClip,
  27408. actionsForClip = actionsByClip[ clipUuid ],
  27409. knownActionsForClip = actionsForClip.knownActions,
  27410. lastKnownAction =
  27411. knownActionsForClip[ knownActionsForClip.length - 1 ],
  27412. byClipCacheIndex = action._byClipCacheIndex;
  27413. lastKnownAction._byClipCacheIndex = byClipCacheIndex;
  27414. knownActionsForClip[ byClipCacheIndex ] = lastKnownAction;
  27415. knownActionsForClip.pop();
  27416. action._byClipCacheIndex = null;
  27417. var actionByRoot = actionsForClip.actionByRoot,
  27418. rootUuid = ( actions._localRoot || this._root ).uuid;
  27419. delete actionByRoot[ rootUuid ];
  27420. if ( knownActionsForClip.length === 0 ) {
  27421. delete actionsByClip[ clipUuid ];
  27422. }
  27423. this._removeInactiveBindingsForAction( action );
  27424. },
  27425. _removeInactiveBindingsForAction: function( action ) {
  27426. var bindings = action._propertyBindings;
  27427. for ( var i = 0, n = bindings.length; i !== n; ++ i ) {
  27428. var binding = bindings[ i ];
  27429. if ( -- binding.referenceCount === 0 ) {
  27430. this._removeInactiveBinding( binding );
  27431. }
  27432. }
  27433. },
  27434. _lendAction: function( action ) {
  27435. // [ active actions | inactive actions ]
  27436. // [ active actions >| inactive actions ]
  27437. // s a
  27438. // <-swap->
  27439. // a s
  27440. var actions = this._actions,
  27441. prevIndex = action._cacheIndex,
  27442. lastActiveIndex = this._nActiveActions ++,
  27443. firstInactiveAction = actions[ lastActiveIndex ];
  27444. action._cacheIndex = lastActiveIndex;
  27445. actions[ lastActiveIndex ] = action;
  27446. firstInactiveAction._cacheIndex = prevIndex;
  27447. actions[ prevIndex ] = firstInactiveAction;
  27448. },
  27449. _takeBackAction: function( action ) {
  27450. // [ active actions | inactive actions ]
  27451. // [ active actions |< inactive actions ]
  27452. // a s
  27453. // <-swap->
  27454. // s a
  27455. var actions = this._actions,
  27456. prevIndex = action._cacheIndex,
  27457. firstInactiveIndex = -- this._nActiveActions,
  27458. lastActiveAction = actions[ firstInactiveIndex ];
  27459. action._cacheIndex = firstInactiveIndex;
  27460. actions[ firstInactiveIndex ] = action;
  27461. lastActiveAction._cacheIndex = prevIndex;
  27462. actions[ prevIndex ] = lastActiveAction;
  27463. },
  27464. // Memory management for PropertyMixer objects
  27465. _addInactiveBinding: function( binding, rootUuid, trackName ) {
  27466. var bindingsByRoot = this._bindingsByRootAndName,
  27467. bindingByName = bindingsByRoot[ rootUuid ],
  27468. bindings = this._bindings;
  27469. if ( bindingByName === undefined ) {
  27470. bindingByName = {};
  27471. bindingsByRoot[ rootUuid ] = bindingByName;
  27472. }
  27473. bindingByName[ trackName ] = binding;
  27474. binding._cacheIndex = bindings.length;
  27475. bindings.push( binding );
  27476. },
  27477. _removeInactiveBinding: function( binding ) {
  27478. var bindings = this._bindings,
  27479. propBinding = binding.binding,
  27480. rootUuid = propBinding.rootNode.uuid,
  27481. trackName = propBinding.path,
  27482. bindingsByRoot = this._bindingsByRootAndName,
  27483. bindingByName = bindingsByRoot[ rootUuid ],
  27484. lastInactiveBinding = bindings[ bindings.length - 1 ],
  27485. cacheIndex = binding._cacheIndex;
  27486. lastInactiveBinding._cacheIndex = cacheIndex;
  27487. bindings[ cacheIndex ] = lastInactiveBinding;
  27488. bindings.pop();
  27489. delete bindingByName[ trackName ];
  27490. remove_empty_map: {
  27491. for ( var _ in bindingByName ) break remove_empty_map;
  27492. delete bindingsByRoot[ rootUuid ];
  27493. }
  27494. },
  27495. _lendBinding: function( binding ) {
  27496. var bindings = this._bindings,
  27497. prevIndex = binding._cacheIndex,
  27498. lastActiveIndex = this._nActiveBindings ++,
  27499. firstInactiveBinding = bindings[ lastActiveIndex ];
  27500. binding._cacheIndex = lastActiveIndex;
  27501. bindings[ lastActiveIndex ] = binding;
  27502. firstInactiveBinding._cacheIndex = prevIndex;
  27503. bindings[ prevIndex ] = firstInactiveBinding;
  27504. },
  27505. _takeBackBinding: function( binding ) {
  27506. var bindings = this._bindings,
  27507. prevIndex = binding._cacheIndex,
  27508. firstInactiveIndex = -- this._nActiveBindings,
  27509. lastActiveBinding = bindings[ firstInactiveIndex ];
  27510. binding._cacheIndex = firstInactiveIndex;
  27511. bindings[ firstInactiveIndex ] = binding;
  27512. lastActiveBinding._cacheIndex = prevIndex;
  27513. bindings[ prevIndex ] = lastActiveBinding;
  27514. },
  27515. // Memory management of Interpolants for weight and time scale
  27516. _lendControlInterpolant: function() {
  27517. var interpolants = this._controlInterpolants,
  27518. lastActiveIndex = this._nActiveControlInterpolants ++,
  27519. interpolant = interpolants[ lastActiveIndex ];
  27520. if ( interpolant === undefined ) {
  27521. interpolant = new LinearInterpolant(
  27522. new Float32Array( 2 ), new Float32Array( 2 ),
  27523. 1, this._controlInterpolantsResultBuffer );
  27524. interpolant.__cacheIndex = lastActiveIndex;
  27525. interpolants[ lastActiveIndex ] = interpolant;
  27526. }
  27527. return interpolant;
  27528. },
  27529. _takeBackControlInterpolant: function( interpolant ) {
  27530. var interpolants = this._controlInterpolants,
  27531. prevIndex = interpolant.__cacheIndex,
  27532. firstInactiveIndex = -- this._nActiveControlInterpolants,
  27533. lastActiveInterpolant = interpolants[ firstInactiveIndex ];
  27534. interpolant.__cacheIndex = firstInactiveIndex;
  27535. interpolants[ firstInactiveIndex ] = interpolant;
  27536. lastActiveInterpolant.__cacheIndex = prevIndex;
  27537. interpolants[ prevIndex ] = lastActiveInterpolant;
  27538. },
  27539. _controlInterpolantsResultBuffer: new Float32Array( 1 )
  27540. } );
  27541. /**
  27542. * @author mrdoob / http://mrdoob.com/
  27543. */
  27544. function Uniform( value ) {
  27545. if ( typeof value === 'string' ) {
  27546. console.warn( 'THREE.Uniform: Type parameter is no longer needed.' );
  27547. value = arguments[ 1 ];
  27548. }
  27549. this.value = value;
  27550. }
  27551. Uniform.prototype.clone = function () {
  27552. return new Uniform( this.value.clone === undefined ? this.value : this.value.clone() );
  27553. };
  27554. /**
  27555. * @author benaadams / https://twitter.com/ben_a_adams
  27556. */
  27557. function InstancedBufferGeometry() {
  27558. BufferGeometry.call( this );
  27559. this.type = 'InstancedBufferGeometry';
  27560. this.maxInstancedCount = undefined;
  27561. }
  27562. InstancedBufferGeometry.prototype = Object.create( BufferGeometry.prototype );
  27563. InstancedBufferGeometry.prototype.constructor = InstancedBufferGeometry;
  27564. InstancedBufferGeometry.prototype.isInstancedBufferGeometry = true;
  27565. InstancedBufferGeometry.prototype.addGroup = function ( start, count, materialIndex ) {
  27566. this.groups.push( {
  27567. start: start,
  27568. count: count,
  27569. materialIndex: materialIndex
  27570. } );
  27571. };
  27572. InstancedBufferGeometry.prototype.copy = function ( source ) {
  27573. var index = source.index;
  27574. if ( index !== null ) {
  27575. this.setIndex( index.clone() );
  27576. }
  27577. var attributes = source.attributes;
  27578. for ( var name in attributes ) {
  27579. var attribute = attributes[ name ];
  27580. this.addAttribute( name, attribute.clone() );
  27581. }
  27582. var groups = source.groups;
  27583. for ( var i = 0, l = groups.length; i < l; i ++ ) {
  27584. var group = groups[ i ];
  27585. this.addGroup( group.start, group.count, group.materialIndex );
  27586. }
  27587. return this;
  27588. };
  27589. /**
  27590. * @author benaadams / https://twitter.com/ben_a_adams
  27591. */
  27592. function InterleavedBufferAttribute( interleavedBuffer, itemSize, offset, normalized ) {
  27593. this.uuid = _Math.generateUUID();
  27594. this.data = interleavedBuffer;
  27595. this.itemSize = itemSize;
  27596. this.offset = offset;
  27597. this.normalized = normalized === true;
  27598. }
  27599. InterleavedBufferAttribute.prototype = {
  27600. constructor: InterleavedBufferAttribute,
  27601. isInterleavedBufferAttribute: true,
  27602. get count() {
  27603. return this.data.count;
  27604. },
  27605. get array() {
  27606. return this.data.array;
  27607. },
  27608. setX: function ( index, x ) {
  27609. this.data.array[ index * this.data.stride + this.offset ] = x;
  27610. return this;
  27611. },
  27612. setY: function ( index, y ) {
  27613. this.data.array[ index * this.data.stride + this.offset + 1 ] = y;
  27614. return this;
  27615. },
  27616. setZ: function ( index, z ) {
  27617. this.data.array[ index * this.data.stride + this.offset + 2 ] = z;
  27618. return this;
  27619. },
  27620. setW: function ( index, w ) {
  27621. this.data.array[ index * this.data.stride + this.offset + 3 ] = w;
  27622. return this;
  27623. },
  27624. getX: function ( index ) {
  27625. return this.data.array[ index * this.data.stride + this.offset ];
  27626. },
  27627. getY: function ( index ) {
  27628. return this.data.array[ index * this.data.stride + this.offset + 1 ];
  27629. },
  27630. getZ: function ( index ) {
  27631. return this.data.array[ index * this.data.stride + this.offset + 2 ];
  27632. },
  27633. getW: function ( index ) {
  27634. return this.data.array[ index * this.data.stride + this.offset + 3 ];
  27635. },
  27636. setXY: function ( index, x, y ) {
  27637. index = index * this.data.stride + this.offset;
  27638. this.data.array[ index + 0 ] = x;
  27639. this.data.array[ index + 1 ] = y;
  27640. return this;
  27641. },
  27642. setXYZ: function ( index, x, y, z ) {
  27643. index = index * this.data.stride + this.offset;
  27644. this.data.array[ index + 0 ] = x;
  27645. this.data.array[ index + 1 ] = y;
  27646. this.data.array[ index + 2 ] = z;
  27647. return this;
  27648. },
  27649. setXYZW: function ( index, x, y, z, w ) {
  27650. index = index * this.data.stride + this.offset;
  27651. this.data.array[ index + 0 ] = x;
  27652. this.data.array[ index + 1 ] = y;
  27653. this.data.array[ index + 2 ] = z;
  27654. this.data.array[ index + 3 ] = w;
  27655. return this;
  27656. }
  27657. };
  27658. /**
  27659. * @author benaadams / https://twitter.com/ben_a_adams
  27660. */
  27661. function InterleavedBuffer( array, stride ) {
  27662. this.uuid = _Math.generateUUID();
  27663. this.array = array;
  27664. this.stride = stride;
  27665. this.count = array !== undefined ? array.length / stride : 0;
  27666. this.dynamic = false;
  27667. this.updateRange = { offset: 0, count: - 1 };
  27668. this.onUploadCallback = function () {};
  27669. this.version = 0;
  27670. }
  27671. InterleavedBuffer.prototype = {
  27672. constructor: InterleavedBuffer,
  27673. isInterleavedBuffer: true,
  27674. set needsUpdate( value ) {
  27675. if ( value === true ) this.version ++;
  27676. },
  27677. setArray: function ( array ) {
  27678. if ( Array.isArray( array ) ) {
  27679. throw new TypeError( 'THREE.BufferAttribute: array should be a Typed Array.' );
  27680. }
  27681. this.count = array !== undefined ? array.length / this.stride : 0;
  27682. this.array = array;
  27683. },
  27684. setDynamic: function ( value ) {
  27685. this.dynamic = value;
  27686. return this;
  27687. },
  27688. copy: function ( source ) {
  27689. this.array = new source.array.constructor( source.array );
  27690. this.count = source.count;
  27691. this.stride = source.stride;
  27692. this.dynamic = source.dynamic;
  27693. return this;
  27694. },
  27695. copyAt: function ( index1, attribute, index2 ) {
  27696. index1 *= this.stride;
  27697. index2 *= attribute.stride;
  27698. for ( var i = 0, l = this.stride; i < l; i ++ ) {
  27699. this.array[ index1 + i ] = attribute.array[ index2 + i ];
  27700. }
  27701. return this;
  27702. },
  27703. set: function ( value, offset ) {
  27704. if ( offset === undefined ) offset = 0;
  27705. this.array.set( value, offset );
  27706. return this;
  27707. },
  27708. clone: function () {
  27709. return new this.constructor().copy( this );
  27710. },
  27711. onUpload: function ( callback ) {
  27712. this.onUploadCallback = callback;
  27713. return this;
  27714. }
  27715. };
  27716. /**
  27717. * @author benaadams / https://twitter.com/ben_a_adams
  27718. */
  27719. function InstancedInterleavedBuffer( array, stride, meshPerAttribute ) {
  27720. InterleavedBuffer.call( this, array, stride );
  27721. this.meshPerAttribute = meshPerAttribute || 1;
  27722. }
  27723. InstancedInterleavedBuffer.prototype = Object.create( InterleavedBuffer.prototype );
  27724. InstancedInterleavedBuffer.prototype.constructor = InstancedInterleavedBuffer;
  27725. InstancedInterleavedBuffer.prototype.isInstancedInterleavedBuffer = true;
  27726. InstancedInterleavedBuffer.prototype.copy = function ( source ) {
  27727. InterleavedBuffer.prototype.copy.call( this, source );
  27728. this.meshPerAttribute = source.meshPerAttribute;
  27729. return this;
  27730. };
  27731. /**
  27732. * @author benaadams / https://twitter.com/ben_a_adams
  27733. */
  27734. function InstancedBufferAttribute( array, itemSize, meshPerAttribute ) {
  27735. BufferAttribute.call( this, array, itemSize );
  27736. this.meshPerAttribute = meshPerAttribute || 1;
  27737. }
  27738. InstancedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  27739. InstancedBufferAttribute.prototype.constructor = InstancedBufferAttribute;
  27740. InstancedBufferAttribute.prototype.isInstancedBufferAttribute = true;
  27741. InstancedBufferAttribute.prototype.copy = function ( source ) {
  27742. BufferAttribute.prototype.copy.call( this, source );
  27743. this.meshPerAttribute = source.meshPerAttribute;
  27744. return this;
  27745. };
  27746. /**
  27747. * @author mrdoob / http://mrdoob.com/
  27748. * @author bhouston / http://clara.io/
  27749. * @author stephomi / http://stephaneginier.com/
  27750. */
  27751. function Raycaster( origin, direction, near, far ) {
  27752. this.ray = new Ray( origin, direction );
  27753. // direction is assumed to be normalized (for accurate distance calculations)
  27754. this.near = near || 0;
  27755. this.far = far || Infinity;
  27756. this.params = {
  27757. Mesh: {},
  27758. Line: {},
  27759. LOD: {},
  27760. Points: { threshold: 1 },
  27761. Sprite: {}
  27762. };
  27763. Object.defineProperties( this.params, {
  27764. PointCloud: {
  27765. get: function () {
  27766. console.warn( 'THREE.Raycaster: params.PointCloud has been renamed to params.Points.' );
  27767. return this.Points;
  27768. }
  27769. }
  27770. } );
  27771. }
  27772. function ascSort( a, b ) {
  27773. return a.distance - b.distance;
  27774. }
  27775. function intersectObject( object, raycaster, intersects, recursive ) {
  27776. if ( object.visible === false ) return;
  27777. object.raycast( raycaster, intersects );
  27778. if ( recursive === true ) {
  27779. var children = object.children;
  27780. for ( var i = 0, l = children.length; i < l; i ++ ) {
  27781. intersectObject( children[ i ], raycaster, intersects, true );
  27782. }
  27783. }
  27784. }
  27785. //
  27786. Raycaster.prototype = {
  27787. constructor: Raycaster,
  27788. linePrecision: 1,
  27789. set: function ( origin, direction ) {
  27790. // direction is assumed to be normalized (for accurate distance calculations)
  27791. this.ray.set( origin, direction );
  27792. },
  27793. setFromCamera: function ( coords, camera ) {
  27794. if ( (camera && camera.isPerspectiveCamera) ) {
  27795. this.ray.origin.setFromMatrixPosition( camera.matrixWorld );
  27796. this.ray.direction.set( coords.x, coords.y, 0.5 ).unproject( camera ).sub( this.ray.origin ).normalize();
  27797. } else if ( (camera && camera.isOrthographicCamera) ) {
  27798. this.ray.origin.set( coords.x, coords.y, ( camera.near + camera.far ) / ( camera.near - camera.far ) ).unproject( camera ); // set origin in plane of camera
  27799. this.ray.direction.set( 0, 0, - 1 ).transformDirection( camera.matrixWorld );
  27800. } else {
  27801. console.error( 'THREE.Raycaster: Unsupported camera type.' );
  27802. }
  27803. },
  27804. intersectObject: function ( object, recursive ) {
  27805. var intersects = [];
  27806. intersectObject( object, this, intersects, recursive );
  27807. intersects.sort( ascSort );
  27808. return intersects;
  27809. },
  27810. intersectObjects: function ( objects, recursive ) {
  27811. var intersects = [];
  27812. if ( Array.isArray( objects ) === false ) {
  27813. console.warn( 'THREE.Raycaster.intersectObjects: objects is not an Array.' );
  27814. return intersects;
  27815. }
  27816. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  27817. intersectObject( objects[ i ], this, intersects, recursive );
  27818. }
  27819. intersects.sort( ascSort );
  27820. return intersects;
  27821. }
  27822. };
  27823. /**
  27824. * @author alteredq / http://alteredqualia.com/
  27825. */
  27826. function Clock( autoStart ) {
  27827. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  27828. this.startTime = 0;
  27829. this.oldTime = 0;
  27830. this.elapsedTime = 0;
  27831. this.running = false;
  27832. }
  27833. Clock.prototype = {
  27834. constructor: Clock,
  27835. start: function () {
  27836. this.startTime = ( performance || Date ).now();
  27837. this.oldTime = this.startTime;
  27838. this.elapsedTime = 0;
  27839. this.running = true;
  27840. },
  27841. stop: function () {
  27842. this.getElapsedTime();
  27843. this.running = false;
  27844. },
  27845. getElapsedTime: function () {
  27846. this.getDelta();
  27847. return this.elapsedTime;
  27848. },
  27849. getDelta: function () {
  27850. var diff = 0;
  27851. if ( this.autoStart && ! this.running ) {
  27852. this.start();
  27853. }
  27854. if ( this.running ) {
  27855. var newTime = ( performance || Date ).now();
  27856. diff = ( newTime - this.oldTime ) / 1000;
  27857. this.oldTime = newTime;
  27858. this.elapsedTime += diff;
  27859. }
  27860. return diff;
  27861. }
  27862. };
  27863. /**
  27864. * Spline from Tween.js, slightly optimized (and trashed)
  27865. * http://sole.github.com/tween.js/examples/05_spline.html
  27866. *
  27867. * @author mrdoob / http://mrdoob.com/
  27868. * @author alteredq / http://alteredqualia.com/
  27869. */
  27870. function Spline( points ) {
  27871. this.points = points;
  27872. var c = [], v3 = { x: 0, y: 0, z: 0 },
  27873. point, intPoint, weight, w2, w3,
  27874. pa, pb, pc, pd;
  27875. this.initFromArray = function ( a ) {
  27876. this.points = [];
  27877. for ( var i = 0; i < a.length; i ++ ) {
  27878. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  27879. }
  27880. };
  27881. this.getPoint = function ( k ) {
  27882. point = ( this.points.length - 1 ) * k;
  27883. intPoint = Math.floor( point );
  27884. weight = point - intPoint;
  27885. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  27886. c[ 1 ] = intPoint;
  27887. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  27888. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  27889. pa = this.points[ c[ 0 ] ];
  27890. pb = this.points[ c[ 1 ] ];
  27891. pc = this.points[ c[ 2 ] ];
  27892. pd = this.points[ c[ 3 ] ];
  27893. w2 = weight * weight;
  27894. w3 = weight * w2;
  27895. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  27896. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  27897. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  27898. return v3;
  27899. };
  27900. this.getControlPointsArray = function () {
  27901. var i, p, l = this.points.length,
  27902. coords = [];
  27903. for ( i = 0; i < l; i ++ ) {
  27904. p = this.points[ i ];
  27905. coords[ i ] = [ p.x, p.y, p.z ];
  27906. }
  27907. return coords;
  27908. };
  27909. // approximate length by summing linear segments
  27910. this.getLength = function ( nSubDivisions ) {
  27911. var i, index, nSamples, position,
  27912. point = 0, intPoint = 0, oldIntPoint = 0,
  27913. oldPosition = new Vector3(),
  27914. tmpVec = new Vector3(),
  27915. chunkLengths = [],
  27916. totalLength = 0;
  27917. // first point has 0 length
  27918. chunkLengths[ 0 ] = 0;
  27919. if ( ! nSubDivisions ) nSubDivisions = 100;
  27920. nSamples = this.points.length * nSubDivisions;
  27921. oldPosition.copy( this.points[ 0 ] );
  27922. for ( i = 1; i < nSamples; i ++ ) {
  27923. index = i / nSamples;
  27924. position = this.getPoint( index );
  27925. tmpVec.copy( position );
  27926. totalLength += tmpVec.distanceTo( oldPosition );
  27927. oldPosition.copy( position );
  27928. point = ( this.points.length - 1 ) * index;
  27929. intPoint = Math.floor( point );
  27930. if ( intPoint !== oldIntPoint ) {
  27931. chunkLengths[ intPoint ] = totalLength;
  27932. oldIntPoint = intPoint;
  27933. }
  27934. }
  27935. // last point ends with total length
  27936. chunkLengths[ chunkLengths.length ] = totalLength;
  27937. return { chunks: chunkLengths, total: totalLength };
  27938. };
  27939. this.reparametrizeByArcLength = function ( samplingCoef ) {
  27940. var i, j,
  27941. index, indexCurrent, indexNext,
  27942. realDistance,
  27943. sampling, position,
  27944. newpoints = [],
  27945. tmpVec = new Vector3(),
  27946. sl = this.getLength();
  27947. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  27948. for ( i = 1; i < this.points.length; i ++ ) {
  27949. //tmpVec.copy( this.points[ i - 1 ] );
  27950. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  27951. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  27952. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  27953. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  27954. indexNext = i / ( this.points.length - 1 );
  27955. for ( j = 1; j < sampling - 1; j ++ ) {
  27956. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  27957. position = this.getPoint( index );
  27958. newpoints.push( tmpVec.copy( position ).clone() );
  27959. }
  27960. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  27961. }
  27962. this.points = newpoints;
  27963. };
  27964. // Catmull-Rom
  27965. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  27966. var v0 = ( p2 - p0 ) * 0.5,
  27967. v1 = ( p3 - p1 ) * 0.5;
  27968. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  27969. }
  27970. }
  27971. /**
  27972. * @author bhouston / http://clara.io
  27973. * @author WestLangley / http://github.com/WestLangley
  27974. *
  27975. * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
  27976. *
  27977. * The poles (phi) are at the positive and negative y axis.
  27978. * The equator starts at positive z.
  27979. */
  27980. function Spherical( radius, phi, theta ) {
  27981. this.radius = ( radius !== undefined ) ? radius : 1.0;
  27982. this.phi = ( phi !== undefined ) ? phi : 0; // up / down towards top and bottom pole
  27983. this.theta = ( theta !== undefined ) ? theta : 0; // around the equator of the sphere
  27984. return this;
  27985. }
  27986. Spherical.prototype = {
  27987. constructor: Spherical,
  27988. set: function ( radius, phi, theta ) {
  27989. this.radius = radius;
  27990. this.phi = phi;
  27991. this.theta = theta;
  27992. return this;
  27993. },
  27994. clone: function () {
  27995. return new this.constructor().copy( this );
  27996. },
  27997. copy: function ( other ) {
  27998. this.radius = other.radius;
  27999. this.phi = other.phi;
  28000. this.theta = other.theta;
  28001. return this;
  28002. },
  28003. // restrict phi to be betwee EPS and PI-EPS
  28004. makeSafe: function() {
  28005. var EPS = 0.000001;
  28006. this.phi = Math.max( EPS, Math.min( Math.PI - EPS, this.phi ) );
  28007. return this;
  28008. },
  28009. setFromVector3: function( vec3 ) {
  28010. this.radius = vec3.length();
  28011. if ( this.radius === 0 ) {
  28012. this.theta = 0;
  28013. this.phi = 0;
  28014. } else {
  28015. this.theta = Math.atan2( vec3.x, vec3.z ); // equator angle around y-up axis
  28016. this.phi = Math.acos( _Math.clamp( vec3.y / this.radius, - 1, 1 ) ); // polar angle
  28017. }
  28018. return this;
  28019. }
  28020. };
  28021. /**
  28022. * @author Mugen87 / https://github.com/Mugen87
  28023. *
  28024. * Ref: https://en.wikipedia.org/wiki/Cylindrical_coordinate_system
  28025. *
  28026. */
  28027. function Cylindrical( radius, theta, y ) {
  28028. this.radius = ( radius !== undefined ) ? radius : 1.0; // distance from the origin to a point in the x-z plane
  28029. this.theta = ( theta !== undefined ) ? theta : 0; // counterclockwise angle in the x-z plane measured in radians from the positive z-axis
  28030. this.y = ( y !== undefined ) ? y : 0; // height above the x-z plane
  28031. return this;
  28032. }
  28033. Cylindrical.prototype = {
  28034. constructor: Cylindrical,
  28035. set: function ( radius, theta, y ) {
  28036. this.radius = radius;
  28037. this.theta = theta;
  28038. this.y = y;
  28039. return this;
  28040. },
  28041. clone: function () {
  28042. return new this.constructor().copy( this );
  28043. },
  28044. copy: function ( other ) {
  28045. this.radius = other.radius;
  28046. this.theta = other.theta;
  28047. this.y = other.y;
  28048. return this;
  28049. },
  28050. setFromVector3: function( vec3 ) {
  28051. this.radius = Math.sqrt( vec3.x * vec3.x + vec3.z * vec3.z );
  28052. this.theta = Math.atan2( vec3.x, vec3.z );
  28053. this.y = vec3.y;
  28054. return this;
  28055. }
  28056. };
  28057. /**
  28058. * @author alteredq / http://alteredqualia.com/
  28059. */
  28060. function MorphBlendMesh( geometry, material ) {
  28061. Mesh.call( this, geometry, material );
  28062. this.animationsMap = {};
  28063. this.animationsList = [];
  28064. // prepare default animation
  28065. // (all frames played together in 1 second)
  28066. var numFrames = this.geometry.morphTargets.length;
  28067. var name = "__default";
  28068. var startFrame = 0;
  28069. var endFrame = numFrames - 1;
  28070. var fps = numFrames / 1;
  28071. this.createAnimation( name, startFrame, endFrame, fps );
  28072. this.setAnimationWeight( name, 1 );
  28073. }
  28074. MorphBlendMesh.prototype = Object.create( Mesh.prototype );
  28075. MorphBlendMesh.prototype.constructor = MorphBlendMesh;
  28076. MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  28077. var animation = {
  28078. start: start,
  28079. end: end,
  28080. length: end - start + 1,
  28081. fps: fps,
  28082. duration: ( end - start ) / fps,
  28083. lastFrame: 0,
  28084. currentFrame: 0,
  28085. active: false,
  28086. time: 0,
  28087. direction: 1,
  28088. weight: 1,
  28089. directionBackwards: false,
  28090. mirroredLoop: false
  28091. };
  28092. this.animationsMap[ name ] = animation;
  28093. this.animationsList.push( animation );
  28094. };
  28095. MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  28096. var pattern = /([a-z]+)_?(\d+)/i;
  28097. var firstAnimation, frameRanges = {};
  28098. var geometry = this.geometry;
  28099. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  28100. var morph = geometry.morphTargets[ i ];
  28101. var chunks = morph.name.match( pattern );
  28102. if ( chunks && chunks.length > 1 ) {
  28103. var name = chunks[ 1 ];
  28104. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: - Infinity };
  28105. var range = frameRanges[ name ];
  28106. if ( i < range.start ) range.start = i;
  28107. if ( i > range.end ) range.end = i;
  28108. if ( ! firstAnimation ) firstAnimation = name;
  28109. }
  28110. }
  28111. for ( var name in frameRanges ) {
  28112. var range = frameRanges[ name ];
  28113. this.createAnimation( name, range.start, range.end, fps );
  28114. }
  28115. this.firstAnimation = firstAnimation;
  28116. };
  28117. MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  28118. var animation = this.animationsMap[ name ];
  28119. if ( animation ) {
  28120. animation.direction = 1;
  28121. animation.directionBackwards = false;
  28122. }
  28123. };
  28124. MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  28125. var animation = this.animationsMap[ name ];
  28126. if ( animation ) {
  28127. animation.direction = - 1;
  28128. animation.directionBackwards = true;
  28129. }
  28130. };
  28131. MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  28132. var animation = this.animationsMap[ name ];
  28133. if ( animation ) {
  28134. animation.fps = fps;
  28135. animation.duration = ( animation.end - animation.start ) / animation.fps;
  28136. }
  28137. };
  28138. MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  28139. var animation = this.animationsMap[ name ];
  28140. if ( animation ) {
  28141. animation.duration = duration;
  28142. animation.fps = ( animation.end - animation.start ) / animation.duration;
  28143. }
  28144. };
  28145. MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  28146. var animation = this.animationsMap[ name ];
  28147. if ( animation ) {
  28148. animation.weight = weight;
  28149. }
  28150. };
  28151. MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  28152. var animation = this.animationsMap[ name ];
  28153. if ( animation ) {
  28154. animation.time = time;
  28155. }
  28156. };
  28157. MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  28158. var time = 0;
  28159. var animation = this.animationsMap[ name ];
  28160. if ( animation ) {
  28161. time = animation.time;
  28162. }
  28163. return time;
  28164. };
  28165. MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  28166. var duration = - 1;
  28167. var animation = this.animationsMap[ name ];
  28168. if ( animation ) {
  28169. duration = animation.duration;
  28170. }
  28171. return duration;
  28172. };
  28173. MorphBlendMesh.prototype.playAnimation = function ( name ) {
  28174. var animation = this.animationsMap[ name ];
  28175. if ( animation ) {
  28176. animation.time = 0;
  28177. animation.active = true;
  28178. } else {
  28179. console.warn( "THREE.MorphBlendMesh: animation[" + name + "] undefined in .playAnimation()" );
  28180. }
  28181. };
  28182. MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  28183. var animation = this.animationsMap[ name ];
  28184. if ( animation ) {
  28185. animation.active = false;
  28186. }
  28187. };
  28188. MorphBlendMesh.prototype.update = function ( delta ) {
  28189. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  28190. var animation = this.animationsList[ i ];
  28191. if ( ! animation.active ) continue;
  28192. var frameTime = animation.duration / animation.length;
  28193. animation.time += animation.direction * delta;
  28194. if ( animation.mirroredLoop ) {
  28195. if ( animation.time > animation.duration || animation.time < 0 ) {
  28196. animation.direction *= - 1;
  28197. if ( animation.time > animation.duration ) {
  28198. animation.time = animation.duration;
  28199. animation.directionBackwards = true;
  28200. }
  28201. if ( animation.time < 0 ) {
  28202. animation.time = 0;
  28203. animation.directionBackwards = false;
  28204. }
  28205. }
  28206. } else {
  28207. animation.time = animation.time % animation.duration;
  28208. if ( animation.time < 0 ) animation.time += animation.duration;
  28209. }
  28210. var keyframe = animation.start + _Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  28211. var weight = animation.weight;
  28212. if ( keyframe !== animation.currentFrame ) {
  28213. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  28214. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  28215. this.morphTargetInfluences[ keyframe ] = 0;
  28216. animation.lastFrame = animation.currentFrame;
  28217. animation.currentFrame = keyframe;
  28218. }
  28219. var mix = ( animation.time % frameTime ) / frameTime;
  28220. if ( animation.directionBackwards ) mix = 1 - mix;
  28221. if ( animation.currentFrame !== animation.lastFrame ) {
  28222. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  28223. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  28224. } else {
  28225. this.morphTargetInfluences[ animation.currentFrame ] = weight;
  28226. }
  28227. }
  28228. };
  28229. /**
  28230. * @author alteredq / http://alteredqualia.com/
  28231. */
  28232. function ImmediateRenderObject( material ) {
  28233. Object3D.call( this );
  28234. this.material = material;
  28235. this.render = function ( renderCallback ) {};
  28236. }
  28237. ImmediateRenderObject.prototype = Object.create( Object3D.prototype );
  28238. ImmediateRenderObject.prototype.constructor = ImmediateRenderObject;
  28239. ImmediateRenderObject.prototype.isImmediateRenderObject = true;
  28240. /**
  28241. * @author mrdoob / http://mrdoob.com/
  28242. * @author WestLangley / http://github.com/WestLangley
  28243. */
  28244. function VertexNormalsHelper( object, size, hex, linewidth ) {
  28245. this.object = object;
  28246. this.size = ( size !== undefined ) ? size : 1;
  28247. var color = ( hex !== undefined ) ? hex : 0xff0000;
  28248. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28249. //
  28250. var nNormals = 0;
  28251. var objGeometry = this.object.geometry;
  28252. if ( objGeometry && objGeometry.isGeometry ) {
  28253. nNormals = objGeometry.faces.length * 3;
  28254. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28255. nNormals = objGeometry.attributes.normal.count;
  28256. }
  28257. //
  28258. var geometry = new BufferGeometry();
  28259. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28260. geometry.addAttribute( 'position', positions );
  28261. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28262. //
  28263. this.matrixAutoUpdate = false;
  28264. this.update();
  28265. }
  28266. VertexNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28267. VertexNormalsHelper.prototype.constructor = VertexNormalsHelper;
  28268. VertexNormalsHelper.prototype.update = ( function () {
  28269. var v1 = new Vector3();
  28270. var v2 = new Vector3();
  28271. var normalMatrix = new Matrix3();
  28272. return function update() {
  28273. var keys = [ 'a', 'b', 'c' ];
  28274. this.object.updateMatrixWorld( true );
  28275. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28276. var matrixWorld = this.object.matrixWorld;
  28277. var position = this.geometry.attributes.position;
  28278. //
  28279. var objGeometry = this.object.geometry;
  28280. if ( objGeometry && objGeometry.isGeometry ) {
  28281. var vertices = objGeometry.vertices;
  28282. var faces = objGeometry.faces;
  28283. var idx = 0;
  28284. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28285. var face = faces[ i ];
  28286. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  28287. var vertex = vertices[ face[ keys[ j ] ] ];
  28288. var normal = face.vertexNormals[ j ];
  28289. v1.copy( vertex ).applyMatrix4( matrixWorld );
  28290. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28291. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28292. idx = idx + 1;
  28293. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28294. idx = idx + 1;
  28295. }
  28296. }
  28297. } else if ( objGeometry && objGeometry.isBufferGeometry ) {
  28298. var objPos = objGeometry.attributes.position;
  28299. var objNorm = objGeometry.attributes.normal;
  28300. var idx = 0;
  28301. // for simplicity, ignore index and drawcalls, and render every normal
  28302. for ( var j = 0, jl = objPos.count; j < jl; j ++ ) {
  28303. v1.set( objPos.getX( j ), objPos.getY( j ), objPos.getZ( j ) ).applyMatrix4( matrixWorld );
  28304. v2.set( objNorm.getX( j ), objNorm.getY( j ), objNorm.getZ( j ) );
  28305. v2.applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28306. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28307. idx = idx + 1;
  28308. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28309. idx = idx + 1;
  28310. }
  28311. }
  28312. position.needsUpdate = true;
  28313. return this;
  28314. };
  28315. }() );
  28316. /**
  28317. * @author alteredq / http://alteredqualia.com/
  28318. * @author mrdoob / http://mrdoob.com/
  28319. * @author WestLangley / http://github.com/WestLangley
  28320. */
  28321. function SpotLightHelper( light ) {
  28322. Object3D.call( this );
  28323. this.light = light;
  28324. this.light.updateMatrixWorld();
  28325. this.matrix = light.matrixWorld;
  28326. this.matrixAutoUpdate = false;
  28327. var geometry = new BufferGeometry();
  28328. var positions = [
  28329. 0, 0, 0, 0, 0, 1,
  28330. 0, 0, 0, 1, 0, 1,
  28331. 0, 0, 0, - 1, 0, 1,
  28332. 0, 0, 0, 0, 1, 1,
  28333. 0, 0, 0, 0, - 1, 1
  28334. ];
  28335. for ( var i = 0, j = 1, l = 32; i < l; i ++, j ++ ) {
  28336. var p1 = ( i / l ) * Math.PI * 2;
  28337. var p2 = ( j / l ) * Math.PI * 2;
  28338. positions.push(
  28339. Math.cos( p1 ), Math.sin( p1 ), 1,
  28340. Math.cos( p2 ), Math.sin( p2 ), 1
  28341. );
  28342. }
  28343. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  28344. var material = new LineBasicMaterial( { fog: false } );
  28345. this.cone = new LineSegments( geometry, material );
  28346. this.add( this.cone );
  28347. this.update();
  28348. }
  28349. SpotLightHelper.prototype = Object.create( Object3D.prototype );
  28350. SpotLightHelper.prototype.constructor = SpotLightHelper;
  28351. SpotLightHelper.prototype.dispose = function () {
  28352. this.cone.geometry.dispose();
  28353. this.cone.material.dispose();
  28354. };
  28355. SpotLightHelper.prototype.update = function () {
  28356. var vector = new Vector3();
  28357. var vector2 = new Vector3();
  28358. return function update() {
  28359. var coneLength = this.light.distance ? this.light.distance : 1000;
  28360. var coneWidth = coneLength * Math.tan( this.light.angle );
  28361. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  28362. vector.setFromMatrixPosition( this.light.matrixWorld );
  28363. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28364. this.cone.lookAt( vector2.sub( vector ) );
  28365. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28366. };
  28367. }();
  28368. /**
  28369. * @author Sean Griffin / http://twitter.com/sgrif
  28370. * @author Michael Guerrero / http://realitymeltdown.com
  28371. * @author mrdoob / http://mrdoob.com/
  28372. * @author ikerr / http://verold.com
  28373. * @author Mugen87 / https://github.com/Mugen87
  28374. */
  28375. function SkeletonHelper( object ) {
  28376. this.bones = this.getBoneList( object );
  28377. var geometry = new BufferGeometry();
  28378. var vertices = [];
  28379. var colors = [];
  28380. var color1 = new Color( 0, 0, 1 );
  28381. var color2 = new Color( 0, 1, 0 );
  28382. for ( var i = 0; i < this.bones.length; i ++ ) {
  28383. var bone = this.bones[ i ];
  28384. if ( bone.parent && bone.parent.isBone ) {
  28385. vertices.push( 0, 0, 0 );
  28386. vertices.push( 0, 0, 0 );
  28387. colors.push( color1.r, color1.g, color1.b );
  28388. colors.push( color2.r, color2.g, color2.b );
  28389. }
  28390. }
  28391. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28392. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28393. var material = new LineBasicMaterial( { vertexColors: VertexColors, depthTest: false, depthWrite: false, transparent: true } );
  28394. LineSegments.call( this, geometry, material );
  28395. this.root = object;
  28396. this.matrix = object.matrixWorld;
  28397. this.matrixAutoUpdate = false;
  28398. this.update();
  28399. }
  28400. SkeletonHelper.prototype = Object.create( LineSegments.prototype );
  28401. SkeletonHelper.prototype.constructor = SkeletonHelper;
  28402. SkeletonHelper.prototype.getBoneList = function( object ) {
  28403. var boneList = [];
  28404. if ( object && object.isBone ) {
  28405. boneList.push( object );
  28406. }
  28407. for ( var i = 0; i < object.children.length; i ++ ) {
  28408. boneList.push.apply( boneList, this.getBoneList( object.children[ i ] ) );
  28409. }
  28410. return boneList;
  28411. };
  28412. SkeletonHelper.prototype.update = function () {
  28413. var vector = new Vector3();
  28414. var boneMatrix = new Matrix4();
  28415. var matrixWorldInv = new Matrix4();
  28416. return function update() {
  28417. var geometry = this.geometry;
  28418. var position = geometry.getAttribute( 'position' );
  28419. matrixWorldInv.getInverse( this.root.matrixWorld );
  28420. for ( var i = 0, j = 0; i < this.bones.length; i ++ ) {
  28421. var bone = this.bones[ i ];
  28422. if ( bone.parent && bone.parent.isBone ) {
  28423. boneMatrix.multiplyMatrices( matrixWorldInv, bone.matrixWorld );
  28424. vector.setFromMatrixPosition( boneMatrix );
  28425. position.setXYZ( j, vector.x, vector.y, vector.z );
  28426. boneMatrix.multiplyMatrices( matrixWorldInv, bone.parent.matrixWorld );
  28427. vector.setFromMatrixPosition( boneMatrix );
  28428. position.setXYZ( j + 1, vector.x, vector.y, vector.z );
  28429. j += 2;
  28430. }
  28431. }
  28432. geometry.getAttribute( 'position' ).needsUpdate = true;
  28433. };
  28434. }();
  28435. /**
  28436. * @author alteredq / http://alteredqualia.com/
  28437. * @author mrdoob / http://mrdoob.com/
  28438. */
  28439. function PointLightHelper( light, sphereSize ) {
  28440. this.light = light;
  28441. this.light.updateMatrixWorld();
  28442. var geometry = new SphereBufferGeometry( sphereSize, 4, 2 );
  28443. var material = new MeshBasicMaterial( { wireframe: true, fog: false } );
  28444. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28445. Mesh.call( this, geometry, material );
  28446. this.matrix = this.light.matrixWorld;
  28447. this.matrixAutoUpdate = false;
  28448. /*
  28449. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  28450. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  28451. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  28452. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  28453. var d = light.distance;
  28454. if ( d === 0.0 ) {
  28455. this.lightDistance.visible = false;
  28456. } else {
  28457. this.lightDistance.scale.set( d, d, d );
  28458. }
  28459. this.add( this.lightDistance );
  28460. */
  28461. }
  28462. PointLightHelper.prototype = Object.create( Mesh.prototype );
  28463. PointLightHelper.prototype.constructor = PointLightHelper;
  28464. PointLightHelper.prototype.dispose = function () {
  28465. this.geometry.dispose();
  28466. this.material.dispose();
  28467. };
  28468. PointLightHelper.prototype.update = function () {
  28469. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28470. /*
  28471. var d = this.light.distance;
  28472. if ( d === 0.0 ) {
  28473. this.lightDistance.visible = false;
  28474. } else {
  28475. this.lightDistance.visible = true;
  28476. this.lightDistance.scale.set( d, d, d );
  28477. }
  28478. */
  28479. };
  28480. /**
  28481. * @author abelnation / http://github.com/abelnation
  28482. * @author Mugen87 / http://github.com/Mugen87
  28483. */
  28484. function RectAreaLightHelper( light ) {
  28485. Object3D.call( this );
  28486. this.light = light;
  28487. this.light.updateMatrixWorld();
  28488. var materialFront = new MeshBasicMaterial( {
  28489. color: light.color,
  28490. fog: false
  28491. } );
  28492. var materialBack = new MeshBasicMaterial( {
  28493. color: light.color,
  28494. fog: false,
  28495. wireframe: true
  28496. } );
  28497. var geometry = new BufferGeometry();
  28498. geometry.addAttribute( 'position', new BufferAttribute( new Float32Array( 6 * 3 ), 3 ) );
  28499. // shows the "front" of the light, e.g. where light comes from
  28500. this.add( new Mesh( geometry, materialFront ) );
  28501. // shows the "back" of the light, which does not emit light
  28502. this.add( new Mesh( geometry, materialBack ) );
  28503. this.update();
  28504. }
  28505. RectAreaLightHelper.prototype = Object.create( Object3D.prototype );
  28506. RectAreaLightHelper.prototype.constructor = RectAreaLightHelper;
  28507. RectAreaLightHelper.prototype.dispose = function () {
  28508. this.children[ 0 ].geometry.dispose();
  28509. this.children[ 0 ].material.dispose();
  28510. this.children[ 1 ].geometry.dispose();
  28511. this.children[ 1 ].material.dispose();
  28512. };
  28513. RectAreaLightHelper.prototype.update = function () {
  28514. var vector1 = new Vector3();
  28515. var vector2 = new Vector3();
  28516. return function update() {
  28517. var mesh1 = this.children[ 0 ];
  28518. var mesh2 = this.children[ 1 ];
  28519. if ( this.light.target ) {
  28520. vector1.setFromMatrixPosition( this.light.matrixWorld );
  28521. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  28522. var lookVec = vector2.clone().sub( vector1 );
  28523. mesh1.lookAt( lookVec );
  28524. mesh2.lookAt( lookVec );
  28525. }
  28526. // update materials
  28527. mesh1.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28528. mesh2.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28529. // calculate new dimensions of the helper
  28530. var hx = this.light.width * 0.5;
  28531. var hy = this.light.height * 0.5;
  28532. // because the buffer attribute is shared over both geometries, we only have to update once
  28533. var position = mesh1.geometry.getAttribute( 'position' );
  28534. var array = position.array;
  28535. // first face
  28536. array[ 0 ] = hx; array[ 1 ] = - hy; array[ 2 ] = 0;
  28537. array[ 3 ] = hx; array[ 4 ] = hy; array[ 5 ] = 0;
  28538. array[ 6 ] = - hx; array[ 7 ] = hy; array[ 8 ] = 0;
  28539. // second face
  28540. array[ 9 ] = - hx; array[ 10 ] = hy; array[ 11 ] = 0;
  28541. array[ 12 ] = - hx; array[ 13 ] = - hy; array[ 14 ] = 0;
  28542. array[ 15 ] = hx; array[ 16 ] = - hy; array[ 17 ] = 0;
  28543. position.needsUpdate = true;
  28544. };
  28545. }();
  28546. /**
  28547. * @author alteredq / http://alteredqualia.com/
  28548. * @author mrdoob / http://mrdoob.com/
  28549. * @author Mugen87 / https://github.com/Mugen87
  28550. */
  28551. function HemisphereLightHelper( light, size ) {
  28552. Object3D.call( this );
  28553. this.light = light;
  28554. this.light.updateMatrixWorld();
  28555. this.matrix = light.matrixWorld;
  28556. this.matrixAutoUpdate = false;
  28557. var geometry = new OctahedronBufferGeometry( size );
  28558. geometry.rotateY( Math.PI * 0.5 );
  28559. var material = new MeshBasicMaterial( { vertexColors: VertexColors, wireframe: true } );
  28560. var position = geometry.getAttribute( 'position' );
  28561. var colors = new Float32Array( position.count * 3 );
  28562. geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
  28563. this.add( new Mesh( geometry, material ) );
  28564. this.update();
  28565. }
  28566. HemisphereLightHelper.prototype = Object.create( Object3D.prototype );
  28567. HemisphereLightHelper.prototype.constructor = HemisphereLightHelper;
  28568. HemisphereLightHelper.prototype.dispose = function () {
  28569. this.children[ 0 ].geometry.dispose();
  28570. this.children[ 0 ].material.dispose();
  28571. };
  28572. HemisphereLightHelper.prototype.update = function () {
  28573. var vector = new Vector3();
  28574. var color1 = new Color();
  28575. var color2 = new Color();
  28576. return function update() {
  28577. var mesh = this.children[ 0 ];
  28578. var colors = mesh.geometry.getAttribute( 'color' );
  28579. color1.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28580. color2.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  28581. for ( var i = 0, l = colors.count; i < l; i ++ ) {
  28582. var color = ( i < ( l / 2 ) ) ? color1 : color2;
  28583. colors.setXYZ( i, color.r, color.g, color.b );
  28584. }
  28585. mesh.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  28586. colors.needsUpdate = true;
  28587. };
  28588. }();
  28589. /**
  28590. * @author mrdoob / http://mrdoob.com/
  28591. */
  28592. function GridHelper( size, divisions, color1, color2 ) {
  28593. size = size || 10;
  28594. divisions = divisions || 10;
  28595. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28596. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28597. var center = divisions / 2;
  28598. var step = ( size * 2 ) / divisions;
  28599. var vertices = [], colors = [];
  28600. for ( var i = 0, j = 0, k = - size; i <= divisions; i ++, k += step ) {
  28601. vertices.push( - size, 0, k, size, 0, k );
  28602. vertices.push( k, 0, - size, k, 0, size );
  28603. var color = i === center ? color1 : color2;
  28604. color.toArray( colors, j ); j += 3;
  28605. color.toArray( colors, j ); j += 3;
  28606. color.toArray( colors, j ); j += 3;
  28607. color.toArray( colors, j ); j += 3;
  28608. }
  28609. var geometry = new BufferGeometry();
  28610. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28611. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28612. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28613. LineSegments.call( this, geometry, material );
  28614. }
  28615. GridHelper.prototype = Object.create( LineSegments.prototype );
  28616. GridHelper.prototype.constructor = GridHelper;
  28617. /**
  28618. * @author mrdoob / http://mrdoob.com/
  28619. * @author Mugen87 / http://github.com/Mugen87
  28620. * @author Hectate / http://www.github.com/Hectate
  28621. */
  28622. function PolarGridHelper( radius, radials, circles, divisions, color1, color2 ) {
  28623. radius = radius || 10;
  28624. radials = radials || 16;
  28625. circles = circles || 8;
  28626. divisions = divisions || 64;
  28627. color1 = new Color( color1 !== undefined ? color1 : 0x444444 );
  28628. color2 = new Color( color2 !== undefined ? color2 : 0x888888 );
  28629. var vertices = [];
  28630. var colors = [];
  28631. var x, z;
  28632. var v, i, j, r, color;
  28633. // create the radials
  28634. for ( i = 0; i <= radials; i ++ ) {
  28635. v = ( i / radials ) * ( Math.PI * 2 );
  28636. x = Math.sin( v ) * radius;
  28637. z = Math.cos( v ) * radius;
  28638. vertices.push( 0, 0, 0 );
  28639. vertices.push( x, 0, z );
  28640. color = ( i & 1 ) ? color1 : color2;
  28641. colors.push( color.r, color.g, color.b );
  28642. colors.push( color.r, color.g, color.b );
  28643. }
  28644. // create the circles
  28645. for ( i = 0; i <= circles; i ++ ) {
  28646. color = ( i & 1 ) ? color1 : color2;
  28647. r = radius - ( radius / circles * i );
  28648. for ( j = 0; j < divisions; j ++ ) {
  28649. // first vertex
  28650. v = ( j / divisions ) * ( Math.PI * 2 );
  28651. x = Math.sin( v ) * r;
  28652. z = Math.cos( v ) * r;
  28653. vertices.push( x, 0, z );
  28654. colors.push( color.r, color.g, color.b );
  28655. // second vertex
  28656. v = ( ( j + 1 ) / divisions ) * ( Math.PI * 2 );
  28657. x = Math.sin( v ) * r;
  28658. z = Math.cos( v ) * r;
  28659. vertices.push( x, 0, z );
  28660. colors.push( color.r, color.g, color.b );
  28661. }
  28662. }
  28663. var geometry = new BufferGeometry();
  28664. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28665. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28666. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  28667. LineSegments.call( this, geometry, material );
  28668. }
  28669. PolarGridHelper.prototype = Object.create( LineSegments.prototype );
  28670. PolarGridHelper.prototype.constructor = PolarGridHelper;
  28671. /**
  28672. * @author mrdoob / http://mrdoob.com/
  28673. * @author WestLangley / http://github.com/WestLangley
  28674. */
  28675. function FaceNormalsHelper( object, size, hex, linewidth ) {
  28676. // FaceNormalsHelper only supports THREE.Geometry
  28677. this.object = object;
  28678. this.size = ( size !== undefined ) ? size : 1;
  28679. var color = ( hex !== undefined ) ? hex : 0xffff00;
  28680. var width = ( linewidth !== undefined ) ? linewidth : 1;
  28681. //
  28682. var nNormals = 0;
  28683. var objGeometry = this.object.geometry;
  28684. if ( objGeometry && objGeometry.isGeometry ) {
  28685. nNormals = objGeometry.faces.length;
  28686. } else {
  28687. console.warn( 'THREE.FaceNormalsHelper: only THREE.Geometry is supported. Use THREE.VertexNormalsHelper, instead.' );
  28688. }
  28689. //
  28690. var geometry = new BufferGeometry();
  28691. var positions = new Float32BufferAttribute( nNormals * 2 * 3, 3 );
  28692. geometry.addAttribute( 'position', positions );
  28693. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color, linewidth: width } ) );
  28694. //
  28695. this.matrixAutoUpdate = false;
  28696. this.update();
  28697. }
  28698. FaceNormalsHelper.prototype = Object.create( LineSegments.prototype );
  28699. FaceNormalsHelper.prototype.constructor = FaceNormalsHelper;
  28700. FaceNormalsHelper.prototype.update = ( function () {
  28701. var v1 = new Vector3();
  28702. var v2 = new Vector3();
  28703. var normalMatrix = new Matrix3();
  28704. return function update() {
  28705. this.object.updateMatrixWorld( true );
  28706. normalMatrix.getNormalMatrix( this.object.matrixWorld );
  28707. var matrixWorld = this.object.matrixWorld;
  28708. var position = this.geometry.attributes.position;
  28709. //
  28710. var objGeometry = this.object.geometry;
  28711. var vertices = objGeometry.vertices;
  28712. var faces = objGeometry.faces;
  28713. var idx = 0;
  28714. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  28715. var face = faces[ i ];
  28716. var normal = face.normal;
  28717. v1.copy( vertices[ face.a ] )
  28718. .add( vertices[ face.b ] )
  28719. .add( vertices[ face.c ] )
  28720. .divideScalar( 3 )
  28721. .applyMatrix4( matrixWorld );
  28722. v2.copy( normal ).applyMatrix3( normalMatrix ).normalize().multiplyScalar( this.size ).add( v1 );
  28723. position.setXYZ( idx, v1.x, v1.y, v1.z );
  28724. idx = idx + 1;
  28725. position.setXYZ( idx, v2.x, v2.y, v2.z );
  28726. idx = idx + 1;
  28727. }
  28728. position.needsUpdate = true;
  28729. return this;
  28730. };
  28731. }() );
  28732. /**
  28733. * @author alteredq / http://alteredqualia.com/
  28734. * @author mrdoob / http://mrdoob.com/
  28735. * @author WestLangley / http://github.com/WestLangley
  28736. */
  28737. function DirectionalLightHelper( light, size ) {
  28738. Object3D.call( this );
  28739. this.light = light;
  28740. this.light.updateMatrixWorld();
  28741. this.matrix = light.matrixWorld;
  28742. this.matrixAutoUpdate = false;
  28743. if ( size === undefined ) size = 1;
  28744. var geometry = new BufferGeometry();
  28745. geometry.addAttribute( 'position', new Float32BufferAttribute( [
  28746. - size, size, 0,
  28747. size, size, 0,
  28748. size, - size, 0,
  28749. - size, - size, 0,
  28750. - size, size, 0
  28751. ], 3 ) );
  28752. var material = new LineBasicMaterial( { fog: false } );
  28753. this.add( new Line( geometry, material ) );
  28754. geometry = new BufferGeometry();
  28755. geometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 0, 1 ], 3 ) );
  28756. this.add( new Line( geometry, material ));
  28757. this.update();
  28758. }
  28759. DirectionalLightHelper.prototype = Object.create( Object3D.prototype );
  28760. DirectionalLightHelper.prototype.constructor = DirectionalLightHelper;
  28761. DirectionalLightHelper.prototype.dispose = function () {
  28762. var lightPlane = this.children[ 0 ];
  28763. var targetLine = this.children[ 1 ];
  28764. lightPlane.geometry.dispose();
  28765. lightPlane.material.dispose();
  28766. targetLine.geometry.dispose();
  28767. targetLine.material.dispose();
  28768. };
  28769. DirectionalLightHelper.prototype.update = function () {
  28770. var v1 = new Vector3();
  28771. var v2 = new Vector3();
  28772. var v3 = new Vector3();
  28773. return function update() {
  28774. v1.setFromMatrixPosition( this.light.matrixWorld );
  28775. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  28776. v3.subVectors( v2, v1 );
  28777. var lightPlane = this.children[ 0 ];
  28778. var targetLine = this.children[ 1 ];
  28779. lightPlane.lookAt( v3 );
  28780. lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  28781. targetLine.lookAt( v3 );
  28782. targetLine.scale.z = v3.length();
  28783. };
  28784. }();
  28785. /**
  28786. * @author alteredq / http://alteredqualia.com/
  28787. * @author Mugen87 / https://github.com/Mugen87
  28788. *
  28789. * - shows frustum, line of sight and up of the camera
  28790. * - suitable for fast updates
  28791. * - based on frustum visualization in lightgl.js shadowmap example
  28792. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  28793. */
  28794. function CameraHelper( camera ) {
  28795. var geometry = new BufferGeometry();
  28796. var material = new LineBasicMaterial( { color: 0xffffff, vertexColors: FaceColors } );
  28797. var vertices = [];
  28798. var colors = [];
  28799. var pointMap = {};
  28800. // colors
  28801. var colorFrustum = new Color( 0xffaa00 );
  28802. var colorCone = new Color( 0xff0000 );
  28803. var colorUp = new Color( 0x00aaff );
  28804. var colorTarget = new Color( 0xffffff );
  28805. var colorCross = new Color( 0x333333 );
  28806. // near
  28807. addLine( "n1", "n2", colorFrustum );
  28808. addLine( "n2", "n4", colorFrustum );
  28809. addLine( "n4", "n3", colorFrustum );
  28810. addLine( "n3", "n1", colorFrustum );
  28811. // far
  28812. addLine( "f1", "f2", colorFrustum );
  28813. addLine( "f2", "f4", colorFrustum );
  28814. addLine( "f4", "f3", colorFrustum );
  28815. addLine( "f3", "f1", colorFrustum );
  28816. // sides
  28817. addLine( "n1", "f1", colorFrustum );
  28818. addLine( "n2", "f2", colorFrustum );
  28819. addLine( "n3", "f3", colorFrustum );
  28820. addLine( "n4", "f4", colorFrustum );
  28821. // cone
  28822. addLine( "p", "n1", colorCone );
  28823. addLine( "p", "n2", colorCone );
  28824. addLine( "p", "n3", colorCone );
  28825. addLine( "p", "n4", colorCone );
  28826. // up
  28827. addLine( "u1", "u2", colorUp );
  28828. addLine( "u2", "u3", colorUp );
  28829. addLine( "u3", "u1", colorUp );
  28830. // target
  28831. addLine( "c", "t", colorTarget );
  28832. addLine( "p", "c", colorCross );
  28833. // cross
  28834. addLine( "cn1", "cn2", colorCross );
  28835. addLine( "cn3", "cn4", colorCross );
  28836. addLine( "cf1", "cf2", colorCross );
  28837. addLine( "cf3", "cf4", colorCross );
  28838. function addLine( a, b, color ) {
  28839. addPoint( a, color );
  28840. addPoint( b, color );
  28841. }
  28842. function addPoint( id, color ) {
  28843. vertices.push( 0, 0, 0 );
  28844. colors.push( color.r, color.g, color.b );
  28845. if ( pointMap[ id ] === undefined ) {
  28846. pointMap[ id ] = [];
  28847. }
  28848. pointMap[ id ].push( ( vertices.length / 3 ) - 1 );
  28849. }
  28850. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  28851. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  28852. LineSegments.call( this, geometry, material );
  28853. this.camera = camera;
  28854. if ( this.camera.updateProjectionMatrix ) this.camera.updateProjectionMatrix();
  28855. this.matrix = camera.matrixWorld;
  28856. this.matrixAutoUpdate = false;
  28857. this.pointMap = pointMap;
  28858. this.update();
  28859. }
  28860. CameraHelper.prototype = Object.create( LineSegments.prototype );
  28861. CameraHelper.prototype.constructor = CameraHelper;
  28862. CameraHelper.prototype.update = function () {
  28863. var geometry, pointMap;
  28864. var vector = new Vector3();
  28865. var camera = new Camera();
  28866. function setPoint( point, x, y, z ) {
  28867. vector.set( x, y, z ).unproject( camera );
  28868. var points = pointMap[ point ];
  28869. if ( points !== undefined ) {
  28870. var position = geometry.getAttribute( 'position' );
  28871. for ( var i = 0, l = points.length; i < l; i ++ ) {
  28872. position.setXYZ( points[ i ], vector.x, vector.y, vector.z );
  28873. }
  28874. }
  28875. }
  28876. return function update() {
  28877. geometry = this.geometry;
  28878. pointMap = this.pointMap;
  28879. var w = 1, h = 1;
  28880. // we need just camera projection matrix
  28881. // world matrix must be identity
  28882. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  28883. // center / target
  28884. setPoint( "c", 0, 0, - 1 );
  28885. setPoint( "t", 0, 0, 1 );
  28886. // near
  28887. setPoint( "n1", - w, - h, - 1 );
  28888. setPoint( "n2", w, - h, - 1 );
  28889. setPoint( "n3", - w, h, - 1 );
  28890. setPoint( "n4", w, h, - 1 );
  28891. // far
  28892. setPoint( "f1", - w, - h, 1 );
  28893. setPoint( "f2", w, - h, 1 );
  28894. setPoint( "f3", - w, h, 1 );
  28895. setPoint( "f4", w, h, 1 );
  28896. // up
  28897. setPoint( "u1", w * 0.7, h * 1.1, - 1 );
  28898. setPoint( "u2", - w * 0.7, h * 1.1, - 1 );
  28899. setPoint( "u3", 0, h * 2, - 1 );
  28900. // cross
  28901. setPoint( "cf1", - w, 0, 1 );
  28902. setPoint( "cf2", w, 0, 1 );
  28903. setPoint( "cf3", 0, - h, 1 );
  28904. setPoint( "cf4", 0, h, 1 );
  28905. setPoint( "cn1", - w, 0, - 1 );
  28906. setPoint( "cn2", w, 0, - 1 );
  28907. setPoint( "cn3", 0, - h, - 1 );
  28908. setPoint( "cn4", 0, h, - 1 );
  28909. geometry.getAttribute( 'position' ).needsUpdate = true;
  28910. };
  28911. }();
  28912. /**
  28913. * @author mrdoob / http://mrdoob.com/
  28914. */
  28915. function BoxHelper( object, color ) {
  28916. if ( color === undefined ) color = 0xffff00;
  28917. 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 ] );
  28918. var positions = new Float32Array( 8 * 3 );
  28919. var geometry = new BufferGeometry();
  28920. geometry.setIndex( new BufferAttribute( indices, 1 ) );
  28921. geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );
  28922. LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );
  28923. if ( object !== undefined ) {
  28924. this.update( object );
  28925. }
  28926. }
  28927. BoxHelper.prototype = Object.create( LineSegments.prototype );
  28928. BoxHelper.prototype.constructor = BoxHelper;
  28929. BoxHelper.prototype.update = ( function () {
  28930. var box = new Box3();
  28931. return function update( object ) {
  28932. if ( object && object.isBox3 ) {
  28933. box.copy( object );
  28934. } else {
  28935. box.setFromObject( object );
  28936. }
  28937. if ( box.isEmpty() ) return;
  28938. var min = box.min;
  28939. var max = box.max;
  28940. /*
  28941. 5____4
  28942. 1/___0/|
  28943. | 6__|_7
  28944. 2/___3/
  28945. 0: max.x, max.y, max.z
  28946. 1: min.x, max.y, max.z
  28947. 2: min.x, min.y, max.z
  28948. 3: max.x, min.y, max.z
  28949. 4: max.x, max.y, min.z
  28950. 5: min.x, max.y, min.z
  28951. 6: min.x, min.y, min.z
  28952. 7: max.x, min.y, min.z
  28953. */
  28954. var position = this.geometry.attributes.position;
  28955. var array = position.array;
  28956. array[ 0 ] = max.x; array[ 1 ] = max.y; array[ 2 ] = max.z;
  28957. array[ 3 ] = min.x; array[ 4 ] = max.y; array[ 5 ] = max.z;
  28958. array[ 6 ] = min.x; array[ 7 ] = min.y; array[ 8 ] = max.z;
  28959. array[ 9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
  28960. array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
  28961. array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
  28962. array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
  28963. array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;
  28964. position.needsUpdate = true;
  28965. this.geometry.computeBoundingSphere();
  28966. };
  28967. } )();
  28968. /**
  28969. * @author WestLangley / http://github.com/WestLangley
  28970. * @author zz85 / http://github.com/zz85
  28971. * @author bhouston / http://clara.io
  28972. *
  28973. * Creates an arrow for visualizing directions
  28974. *
  28975. * Parameters:
  28976. * dir - Vector3
  28977. * origin - Vector3
  28978. * length - Number
  28979. * color - color in hex value
  28980. * headLength - Number
  28981. * headWidth - Number
  28982. */
  28983. var lineGeometry = new BufferGeometry();
  28984. lineGeometry.addAttribute( 'position', new Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
  28985. var coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
  28986. coneGeometry.translate( 0, - 0.5, 0 );
  28987. function ArrowHelper( dir, origin, length, color, headLength, headWidth ) {
  28988. // dir is assumed to be normalized
  28989. Object3D.call( this );
  28990. if ( color === undefined ) color = 0xffff00;
  28991. if ( length === undefined ) length = 1;
  28992. if ( headLength === undefined ) headLength = 0.2 * length;
  28993. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  28994. this.position.copy( origin );
  28995. this.line = new Line( lineGeometry, new LineBasicMaterial( { color: color } ) );
  28996. this.line.matrixAutoUpdate = false;
  28997. this.add( this.line );
  28998. this.cone = new Mesh( coneGeometry, new MeshBasicMaterial( { color: color } ) );
  28999. this.cone.matrixAutoUpdate = false;
  29000. this.add( this.cone );
  29001. this.setDirection( dir );
  29002. this.setLength( length, headLength, headWidth );
  29003. }
  29004. ArrowHelper.prototype = Object.create( Object3D.prototype );
  29005. ArrowHelper.prototype.constructor = ArrowHelper;
  29006. ArrowHelper.prototype.setDirection = ( function () {
  29007. var axis = new Vector3();
  29008. var radians;
  29009. return function setDirection( dir ) {
  29010. // dir is assumed to be normalized
  29011. if ( dir.y > 0.99999 ) {
  29012. this.quaternion.set( 0, 0, 0, 1 );
  29013. } else if ( dir.y < - 0.99999 ) {
  29014. this.quaternion.set( 1, 0, 0, 0 );
  29015. } else {
  29016. axis.set( dir.z, 0, - dir.x ).normalize();
  29017. radians = Math.acos( dir.y );
  29018. this.quaternion.setFromAxisAngle( axis, radians );
  29019. }
  29020. };
  29021. }() );
  29022. ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  29023. if ( headLength === undefined ) headLength = 0.2 * length;
  29024. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  29025. this.line.scale.set( 1, Math.max( 0, length - headLength ), 1 );
  29026. this.line.updateMatrix();
  29027. this.cone.scale.set( headWidth, headLength, headWidth );
  29028. this.cone.position.y = length;
  29029. this.cone.updateMatrix();
  29030. };
  29031. ArrowHelper.prototype.setColor = function ( color ) {
  29032. this.line.material.color.copy( color );
  29033. this.cone.material.color.copy( color );
  29034. };
  29035. /**
  29036. * @author sroucheray / http://sroucheray.org/
  29037. * @author mrdoob / http://mrdoob.com/
  29038. */
  29039. function AxisHelper( size ) {
  29040. size = size || 1;
  29041. var vertices = [
  29042. 0, 0, 0, size, 0, 0,
  29043. 0, 0, 0, 0, size, 0,
  29044. 0, 0, 0, 0, 0, size
  29045. ];
  29046. var colors = [
  29047. 1, 0, 0, 1, 0.6, 0,
  29048. 0, 1, 0, 0.6, 1, 0,
  29049. 0, 0, 1, 0, 0.6, 1
  29050. ];
  29051. var geometry = new BufferGeometry();
  29052. geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
  29053. geometry.addAttribute( 'color', new Float32BufferAttribute( colors, 3 ) );
  29054. var material = new LineBasicMaterial( { vertexColors: VertexColors } );
  29055. LineSegments.call( this, geometry, material );
  29056. }
  29057. AxisHelper.prototype = Object.create( LineSegments.prototype );
  29058. AxisHelper.prototype.constructor = AxisHelper;
  29059. /**
  29060. * @author zz85 https://github.com/zz85
  29061. *
  29062. * Centripetal CatmullRom Curve - which is useful for avoiding
  29063. * cusps and self-intersections in non-uniform catmull rom curves.
  29064. * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  29065. *
  29066. * curve.type accepts centripetal(default), chordal and catmullrom
  29067. * curve.tension is used for catmullrom which defaults to 0.5
  29068. */
  29069. var CatmullRomCurve3 = ( function() {
  29070. var
  29071. tmp = new Vector3(),
  29072. px = new CubicPoly(),
  29073. py = new CubicPoly(),
  29074. pz = new CubicPoly();
  29075. /*
  29076. Based on an optimized c++ solution in
  29077. - http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/
  29078. - http://ideone.com/NoEbVM
  29079. This CubicPoly class could be used for reusing some variables and calculations,
  29080. but for three.js curve use, it could be possible inlined and flatten into a single function call
  29081. which can be placed in CurveUtils.
  29082. */
  29083. function CubicPoly() {}
  29084. /*
  29085. * Compute coefficients for a cubic polynomial
  29086. * p(s) = c0 + c1*s + c2*s^2 + c3*s^3
  29087. * such that
  29088. * p(0) = x0, p(1) = x1
  29089. * and
  29090. * p'(0) = t0, p'(1) = t1.
  29091. */
  29092. CubicPoly.prototype.init = function( x0, x1, t0, t1 ) {
  29093. this.c0 = x0;
  29094. this.c1 = t0;
  29095. this.c2 = - 3 * x0 + 3 * x1 - 2 * t0 - t1;
  29096. this.c3 = 2 * x0 - 2 * x1 + t0 + t1;
  29097. };
  29098. CubicPoly.prototype.initNonuniformCatmullRom = function( x0, x1, x2, x3, dt0, dt1, dt2 ) {
  29099. // compute tangents when parameterized in [t1,t2]
  29100. var t1 = ( x1 - x0 ) / dt0 - ( x2 - x0 ) / ( dt0 + dt1 ) + ( x2 - x1 ) / dt1;
  29101. var t2 = ( x2 - x1 ) / dt1 - ( x3 - x1 ) / ( dt1 + dt2 ) + ( x3 - x2 ) / dt2;
  29102. // rescale tangents for parametrization in [0,1]
  29103. t1 *= dt1;
  29104. t2 *= dt1;
  29105. // initCubicPoly
  29106. this.init( x1, x2, t1, t2 );
  29107. };
  29108. // standard Catmull-Rom spline: interpolate between x1 and x2 with previous/following points x1/x4
  29109. CubicPoly.prototype.initCatmullRom = function( x0, x1, x2, x3, tension ) {
  29110. this.init( x1, x2, tension * ( x2 - x0 ), tension * ( x3 - x1 ) );
  29111. };
  29112. CubicPoly.prototype.calc = function( t ) {
  29113. var t2 = t * t;
  29114. var t3 = t2 * t;
  29115. return this.c0 + this.c1 * t + this.c2 * t2 + this.c3 * t3;
  29116. };
  29117. // Subclass Three.js curve
  29118. return Curve.create(
  29119. function ( p /* array of Vector3 */ ) {
  29120. this.points = p || [];
  29121. this.closed = false;
  29122. },
  29123. function ( t ) {
  29124. var points = this.points,
  29125. point, intPoint, weight, l;
  29126. l = points.length;
  29127. if ( l < 2 ) console.log( 'duh, you need at least 2 points' );
  29128. point = ( l - ( this.closed ? 0 : 1 ) ) * t;
  29129. intPoint = Math.floor( point );
  29130. weight = point - intPoint;
  29131. if ( this.closed ) {
  29132. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  29133. } else if ( weight === 0 && intPoint === l - 1 ) {
  29134. intPoint = l - 2;
  29135. weight = 1;
  29136. }
  29137. var p0, p1, p2, p3; // 4 points
  29138. if ( this.closed || intPoint > 0 ) {
  29139. p0 = points[ ( intPoint - 1 ) % l ];
  29140. } else {
  29141. // extrapolate first point
  29142. tmp.subVectors( points[ 0 ], points[ 1 ] ).add( points[ 0 ] );
  29143. p0 = tmp;
  29144. }
  29145. p1 = points[ intPoint % l ];
  29146. p2 = points[ ( intPoint + 1 ) % l ];
  29147. if ( this.closed || intPoint + 2 < l ) {
  29148. p3 = points[ ( intPoint + 2 ) % l ];
  29149. } else {
  29150. // extrapolate last point
  29151. tmp.subVectors( points[ l - 1 ], points[ l - 2 ] ).add( points[ l - 1 ] );
  29152. p3 = tmp;
  29153. }
  29154. if ( this.type === undefined || this.type === 'centripetal' || this.type === 'chordal' ) {
  29155. // init Centripetal / Chordal Catmull-Rom
  29156. var pow = this.type === 'chordal' ? 0.5 : 0.25;
  29157. var dt0 = Math.pow( p0.distanceToSquared( p1 ), pow );
  29158. var dt1 = Math.pow( p1.distanceToSquared( p2 ), pow );
  29159. var dt2 = Math.pow( p2.distanceToSquared( p3 ), pow );
  29160. // safety check for repeated points
  29161. if ( dt1 < 1e-4 ) dt1 = 1.0;
  29162. if ( dt0 < 1e-4 ) dt0 = dt1;
  29163. if ( dt2 < 1e-4 ) dt2 = dt1;
  29164. px.initNonuniformCatmullRom( p0.x, p1.x, p2.x, p3.x, dt0, dt1, dt2 );
  29165. py.initNonuniformCatmullRom( p0.y, p1.y, p2.y, p3.y, dt0, dt1, dt2 );
  29166. pz.initNonuniformCatmullRom( p0.z, p1.z, p2.z, p3.z, dt0, dt1, dt2 );
  29167. } else if ( this.type === 'catmullrom' ) {
  29168. var tension = this.tension !== undefined ? this.tension : 0.5;
  29169. px.initCatmullRom( p0.x, p1.x, p2.x, p3.x, tension );
  29170. py.initCatmullRom( p0.y, p1.y, p2.y, p3.y, tension );
  29171. pz.initCatmullRom( p0.z, p1.z, p2.z, p3.z, tension );
  29172. }
  29173. var v = new Vector3(
  29174. px.calc( weight ),
  29175. py.calc( weight ),
  29176. pz.calc( weight )
  29177. );
  29178. return v;
  29179. }
  29180. );
  29181. } )();
  29182. /**************************************************************
  29183. * Spline 3D curve
  29184. **************************************************************/
  29185. var SplineCurve3 = Curve.create(
  29186. function ( points /* array of Vector3 */ ) {
  29187. console.warn( 'THREE.SplineCurve3 will be deprecated. Please use THREE.CatmullRomCurve3' );
  29188. this.points = ( points === undefined ) ? [] : points;
  29189. },
  29190. function ( t ) {
  29191. var points = this.points;
  29192. var point = ( points.length - 1 ) * t;
  29193. var intPoint = Math.floor( point );
  29194. var weight = point - intPoint;
  29195. var point0 = points[ intPoint == 0 ? intPoint : intPoint - 1 ];
  29196. var point1 = points[ intPoint ];
  29197. var point2 = points[ intPoint > points.length - 2 ? points.length - 1 : intPoint + 1 ];
  29198. var point3 = points[ intPoint > points.length - 3 ? points.length - 1 : intPoint + 2 ];
  29199. var interpolate = CurveUtils.interpolate;
  29200. return new Vector3(
  29201. interpolate( point0.x, point1.x, point2.x, point3.x, weight ),
  29202. interpolate( point0.y, point1.y, point2.y, point3.y, weight ),
  29203. interpolate( point0.z, point1.z, point2.z, point3.z, weight )
  29204. );
  29205. }
  29206. );
  29207. /**************************************************************
  29208. * Cubic Bezier 3D curve
  29209. **************************************************************/
  29210. var CubicBezierCurve3 = Curve.create(
  29211. function ( v0, v1, v2, v3 ) {
  29212. this.v0 = v0;
  29213. this.v1 = v1;
  29214. this.v2 = v2;
  29215. this.v3 = v3;
  29216. },
  29217. function ( t ) {
  29218. var b3 = ShapeUtils.b3;
  29219. return new Vector3(
  29220. b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x ),
  29221. b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y ),
  29222. b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z )
  29223. );
  29224. }
  29225. );
  29226. /**************************************************************
  29227. * Quadratic Bezier 3D curve
  29228. **************************************************************/
  29229. var QuadraticBezierCurve3 = Curve.create(
  29230. function ( v0, v1, v2 ) {
  29231. this.v0 = v0;
  29232. this.v1 = v1;
  29233. this.v2 = v2;
  29234. },
  29235. function ( t ) {
  29236. var b2 = ShapeUtils.b2;
  29237. return new Vector3(
  29238. b2( t, this.v0.x, this.v1.x, this.v2.x ),
  29239. b2( t, this.v0.y, this.v1.y, this.v2.y ),
  29240. b2( t, this.v0.z, this.v1.z, this.v2.z )
  29241. );
  29242. }
  29243. );
  29244. /**************************************************************
  29245. * Line3D
  29246. **************************************************************/
  29247. var LineCurve3 = Curve.create(
  29248. function ( v1, v2 ) {
  29249. this.v1 = v1;
  29250. this.v2 = v2;
  29251. },
  29252. function ( t ) {
  29253. if ( t === 1 ) {
  29254. return this.v2.clone();
  29255. }
  29256. var vector = new Vector3();
  29257. vector.subVectors( this.v2, this.v1 ); // diff
  29258. vector.multiplyScalar( t );
  29259. vector.add( this.v1 );
  29260. return vector;
  29261. }
  29262. );
  29263. /**************************************************************
  29264. * Arc curve
  29265. **************************************************************/
  29266. function ArcCurve( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  29267. EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  29268. }
  29269. ArcCurve.prototype = Object.create( EllipseCurve.prototype );
  29270. ArcCurve.prototype.constructor = ArcCurve;
  29271. /**
  29272. * @author alteredq / http://alteredqualia.com/
  29273. */
  29274. var SceneUtils = {
  29275. createMultiMaterialObject: function ( geometry, materials ) {
  29276. var group = new Group();
  29277. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  29278. group.add( new Mesh( geometry, materials[ i ] ) );
  29279. }
  29280. return group;
  29281. },
  29282. detach: function ( child, parent, scene ) {
  29283. child.applyMatrix( parent.matrixWorld );
  29284. parent.remove( child );
  29285. scene.add( child );
  29286. },
  29287. attach: function ( child, scene, parent ) {
  29288. var matrixWorldInverse = new Matrix4();
  29289. matrixWorldInverse.getInverse( parent.matrixWorld );
  29290. child.applyMatrix( matrixWorldInverse );
  29291. scene.remove( child );
  29292. parent.add( child );
  29293. }
  29294. };
  29295. /**
  29296. * @author mrdoob / http://mrdoob.com/
  29297. */
  29298. function Face4( a, b, c, d, normal, color, materialIndex ) {
  29299. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.' );
  29300. return new Face3( a, b, c, normal, color, materialIndex );
  29301. }
  29302. var LineStrip = 0;
  29303. var LinePieces = 1;
  29304. function MeshFaceMaterial( materials ) {
  29305. console.warn( 'THREE.MeshFaceMaterial has been renamed to THREE.MultiMaterial.' );
  29306. return new MultiMaterial( materials );
  29307. }
  29308. function PointCloud( geometry, material ) {
  29309. console.warn( 'THREE.PointCloud has been renamed to THREE.Points.' );
  29310. return new Points( geometry, material );
  29311. }
  29312. function Particle( material ) {
  29313. console.warn( 'THREE.Particle has been renamed to THREE.Sprite.' );
  29314. return new Sprite( material );
  29315. }
  29316. function ParticleSystem( geometry, material ) {
  29317. console.warn( 'THREE.ParticleSystem has been renamed to THREE.Points.' );
  29318. return new Points( geometry, material );
  29319. }
  29320. function PointCloudMaterial( parameters ) {
  29321. console.warn( 'THREE.PointCloudMaterial has been renamed to THREE.PointsMaterial.' );
  29322. return new PointsMaterial( parameters );
  29323. }
  29324. function ParticleBasicMaterial( parameters ) {
  29325. console.warn( 'THREE.ParticleBasicMaterial has been renamed to THREE.PointsMaterial.' );
  29326. return new PointsMaterial( parameters );
  29327. }
  29328. function ParticleSystemMaterial( parameters ) {
  29329. console.warn( 'THREE.ParticleSystemMaterial has been renamed to THREE.PointsMaterial.' );
  29330. return new PointsMaterial( parameters );
  29331. }
  29332. function Vertex( x, y, z ) {
  29333. console.warn( 'THREE.Vertex has been removed. Use THREE.Vector3 instead.' );
  29334. return new Vector3( x, y, z );
  29335. }
  29336. //
  29337. function DynamicBufferAttribute( array, itemSize ) {
  29338. console.warn( 'THREE.DynamicBufferAttribute has been removed. Use new THREE.BufferAttribute().setDynamic( true ) instead.' );
  29339. return new BufferAttribute( array, itemSize ).setDynamic( true );
  29340. }
  29341. function Int8Attribute( array, itemSize ) {
  29342. console.warn( 'THREE.Int8Attribute has been removed. Use new THREE.Int8BufferAttribute() instead.' );
  29343. return new Int8BufferAttribute( array, itemSize );
  29344. }
  29345. function Uint8Attribute( array, itemSize ) {
  29346. console.warn( 'THREE.Uint8Attribute has been removed. Use new THREE.Uint8BufferAttribute() instead.' );
  29347. return new Uint8BufferAttribute( array, itemSize );
  29348. }
  29349. function Uint8ClampedAttribute( array, itemSize ) {
  29350. console.warn( 'THREE.Uint8ClampedAttribute has been removed. Use new THREE.Uint8ClampedBufferAttribute() instead.' );
  29351. return new Uint8ClampedBufferAttribute( array, itemSize );
  29352. }
  29353. function Int16Attribute( array, itemSize ) {
  29354. console.warn( 'THREE.Int16Attribute has been removed. Use new THREE.Int16BufferAttribute() instead.' );
  29355. return new Int16BufferAttribute( array, itemSize );
  29356. }
  29357. function Uint16Attribute( array, itemSize ) {
  29358. console.warn( 'THREE.Uint16Attribute has been removed. Use new THREE.Uint16BufferAttribute() instead.' );
  29359. return new Uint16BufferAttribute( array, itemSize );
  29360. }
  29361. function Int32Attribute( array, itemSize ) {
  29362. console.warn( 'THREE.Int32Attribute has been removed. Use new THREE.Int32BufferAttribute() instead.' );
  29363. return new Int32BufferAttribute( array, itemSize );
  29364. }
  29365. function Uint32Attribute( array, itemSize ) {
  29366. console.warn( 'THREE.Uint32Attribute has been removed. Use new THREE.Uint32BufferAttribute() instead.' );
  29367. return new Uint32BufferAttribute( array, itemSize );
  29368. }
  29369. function Float32Attribute( array, itemSize ) {
  29370. console.warn( 'THREE.Float32Attribute has been removed. Use new THREE.Float32BufferAttribute() instead.' );
  29371. return new Float32BufferAttribute( array, itemSize );
  29372. }
  29373. function Float64Attribute( array, itemSize ) {
  29374. console.warn( 'THREE.Float64Attribute has been removed. Use new THREE.Float64BufferAttribute() instead.' );
  29375. return new Float64BufferAttribute( array, itemSize );
  29376. }
  29377. //
  29378. function ClosedSplineCurve3( points ) {
  29379. console.warn( 'THREE.ClosedSplineCurve3 has been deprecated. Use THREE.CatmullRomCurve3 instead.' );
  29380. CatmullRomCurve3.call( this, points );
  29381. this.type = 'catmullrom';
  29382. this.closed = true;
  29383. }
  29384. ClosedSplineCurve3.prototype = Object.create( CatmullRomCurve3.prototype );
  29385. //
  29386. function BoundingBoxHelper( object, color ) {
  29387. console.warn( 'THREE.BoundingBoxHelper has been deprecated. Creating a THREE.BoxHelper instead.' );
  29388. return new BoxHelper( object, color );
  29389. }
  29390. function EdgesHelper( object, hex ) {
  29391. console.warn( 'THREE.EdgesHelper has been removed. Use THREE.EdgesGeometry instead.' );
  29392. return new LineSegments( new EdgesGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29393. }
  29394. GridHelper.prototype.setColors = function () {
  29395. console.error( 'THREE.GridHelper: setColors() has been deprecated, pass them in the constructor instead.' );
  29396. };
  29397. function WireframeHelper( object, hex ) {
  29398. console.warn( 'THREE.WireframeHelper has been removed. Use THREE.WireframeGeometry instead.' );
  29399. return new LineSegments( new WireframeGeometry( object.geometry ), new LineBasicMaterial( { color: hex !== undefined ? hex : 0xffffff } ) );
  29400. }
  29401. //
  29402. function XHRLoader( manager ) {
  29403. console.warn( 'THREE.XHRLoader has been renamed to THREE.FileLoader.' );
  29404. return new FileLoader( manager );
  29405. }
  29406. //
  29407. Object.assign( Box2.prototype, {
  29408. center: function ( optionalTarget ) {
  29409. console.warn( 'THREE.Box2: .center() has been renamed to .getCenter().' );
  29410. return this.getCenter( optionalTarget );
  29411. },
  29412. empty: function () {
  29413. console.warn( 'THREE.Box2: .empty() has been renamed to .isEmpty().' );
  29414. return this.isEmpty();
  29415. },
  29416. isIntersectionBox: function ( box ) {
  29417. console.warn( 'THREE.Box2: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29418. return this.intersectsBox( box );
  29419. },
  29420. size: function ( optionalTarget ) {
  29421. console.warn( 'THREE.Box2: .size() has been renamed to .getSize().' );
  29422. return this.getSize( optionalTarget );
  29423. }
  29424. } );
  29425. Object.assign( Box3.prototype, {
  29426. center: function ( optionalTarget ) {
  29427. console.warn( 'THREE.Box3: .center() has been renamed to .getCenter().' );
  29428. return this.getCenter( optionalTarget );
  29429. },
  29430. empty: function () {
  29431. console.warn( 'THREE.Box3: .empty() has been renamed to .isEmpty().' );
  29432. return this.isEmpty();
  29433. },
  29434. isIntersectionBox: function ( box ) {
  29435. console.warn( 'THREE.Box3: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29436. return this.intersectsBox( box );
  29437. },
  29438. isIntersectionSphere: function ( sphere ) {
  29439. console.warn( 'THREE.Box3: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29440. return this.intersectsSphere( sphere );
  29441. },
  29442. size: function ( optionalTarget ) {
  29443. console.warn( 'THREE.Box3: .size() has been renamed to .getSize().' );
  29444. return this.getSize( optionalTarget );
  29445. }
  29446. } );
  29447. Line3.prototype.center = function ( optionalTarget ) {
  29448. console.warn( 'THREE.Line3: .center() has been renamed to .getCenter().' );
  29449. return this.getCenter( optionalTarget );
  29450. };
  29451. _Math.random16 = function () {
  29452. console.warn( 'THREE.Math.random16() has been deprecated. Use Math.random() instead.' );
  29453. return Math.random();
  29454. };
  29455. Object.assign( Matrix3.prototype, {
  29456. flattenToArrayOffset: function ( array, offset ) {
  29457. console.warn( "THREE.Matrix3: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29458. return this.toArray( array, offset );
  29459. },
  29460. multiplyVector3: function ( vector ) {
  29461. console.warn( 'THREE.Matrix3: .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  29462. return vector.applyMatrix3( this );
  29463. },
  29464. multiplyVector3Array: function ( a ) {
  29465. console.warn( 'THREE.Matrix3: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29466. return this.applyToVector3Array( a );
  29467. },
  29468. applyToBuffer: function( buffer, offset, length ) {
  29469. console.warn( 'THREE.Matrix3: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29470. return this.applyToBufferAttribute( buffer );
  29471. }
  29472. } );
  29473. Object.assign( Matrix4.prototype, {
  29474. extractPosition: function ( m ) {
  29475. console.warn( 'THREE.Matrix4: .extractPosition() has been renamed to .copyPosition().' );
  29476. return this.copyPosition( m );
  29477. },
  29478. flattenToArrayOffset: function ( array, offset ) {
  29479. console.warn( "THREE.Matrix4: .flattenToArrayOffset() has been deprecated. Use .toArray() instead." );
  29480. return this.toArray( array, offset );
  29481. },
  29482. getPosition: function () {
  29483. var v1;
  29484. return function getPosition() {
  29485. if ( v1 === undefined ) v1 = new Vector3();
  29486. console.warn( 'THREE.Matrix4: .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  29487. return v1.setFromMatrixColumn( this, 3 );
  29488. };
  29489. }(),
  29490. setRotationFromQuaternion: function ( q ) {
  29491. console.warn( 'THREE.Matrix4: .setRotationFromQuaternion() has been renamed to .makeRotationFromQuaternion().' );
  29492. return this.makeRotationFromQuaternion( q );
  29493. },
  29494. multiplyVector3: function ( vector ) {
  29495. console.warn( 'THREE.Matrix4: .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  29496. return vector.applyProjection( this );
  29497. },
  29498. multiplyVector4: function ( vector ) {
  29499. console.warn( 'THREE.Matrix4: .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29500. return vector.applyMatrix4( this );
  29501. },
  29502. multiplyVector3Array: function ( a ) {
  29503. console.warn( 'THREE.Matrix4: .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  29504. return this.applyToVector3Array( a );
  29505. },
  29506. rotateAxis: function ( v ) {
  29507. console.warn( 'THREE.Matrix4: .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  29508. v.transformDirection( this );
  29509. },
  29510. crossVector: function ( vector ) {
  29511. console.warn( 'THREE.Matrix4: .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  29512. return vector.applyMatrix4( this );
  29513. },
  29514. translate: function () {
  29515. console.error( 'THREE.Matrix4: .translate() has been removed.' );
  29516. },
  29517. rotateX: function () {
  29518. console.error( 'THREE.Matrix4: .rotateX() has been removed.' );
  29519. },
  29520. rotateY: function () {
  29521. console.error( 'THREE.Matrix4: .rotateY() has been removed.' );
  29522. },
  29523. rotateZ: function () {
  29524. console.error( 'THREE.Matrix4: .rotateZ() has been removed.' );
  29525. },
  29526. rotateByAxis: function () {
  29527. console.error( 'THREE.Matrix4: .rotateByAxis() has been removed.' );
  29528. },
  29529. applyToBuffer: function( buffer, offset, length ) {
  29530. console.warn( 'THREE.Matrix4: .applyToBuffer() has been removed. Use matrix.applyToBufferAttribute( attribute ) instead.' );
  29531. return this.applyToBufferAttribute( buffer );
  29532. }
  29533. } );
  29534. Plane.prototype.isIntersectionLine = function ( line ) {
  29535. console.warn( 'THREE.Plane: .isIntersectionLine() has been renamed to .intersectsLine().' );
  29536. return this.intersectsLine( line );
  29537. };
  29538. Quaternion.prototype.multiplyVector3 = function ( vector ) {
  29539. console.warn( 'THREE.Quaternion: .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  29540. return vector.applyQuaternion( this );
  29541. };
  29542. Object.assign( Ray.prototype, {
  29543. isIntersectionBox: function ( box ) {
  29544. console.warn( 'THREE.Ray: .isIntersectionBox() has been renamed to .intersectsBox().' );
  29545. return this.intersectsBox( box );
  29546. },
  29547. isIntersectionPlane: function ( plane ) {
  29548. console.warn( 'THREE.Ray: .isIntersectionPlane() has been renamed to .intersectsPlane().' );
  29549. return this.intersectsPlane( plane );
  29550. },
  29551. isIntersectionSphere: function ( sphere ) {
  29552. console.warn( 'THREE.Ray: .isIntersectionSphere() has been renamed to .intersectsSphere().' );
  29553. return this.intersectsSphere( sphere );
  29554. }
  29555. } );
  29556. Object.assign( Shape.prototype, {
  29557. extrude: function ( options ) {
  29558. console.warn( 'THREE.Shape: .extrude() has been removed. Use ExtrudeGeometry() instead.' );
  29559. return new ExtrudeGeometry( this, options );
  29560. },
  29561. makeGeometry: function ( options ) {
  29562. console.warn( 'THREE.Shape: .makeGeometry() has been removed. Use ShapeGeometry() instead.' );
  29563. return new ShapeGeometry( this, options );
  29564. }
  29565. } );
  29566. Object.assign( Vector3.prototype, {
  29567. setEulerFromRotationMatrix: function () {
  29568. console.error( 'THREE.Vector3: .setEulerFromRotationMatrix() has been removed. Use Euler.setFromRotationMatrix() instead.' );
  29569. },
  29570. setEulerFromQuaternion: function () {
  29571. console.error( 'THREE.Vector3: .setEulerFromQuaternion() has been removed. Use Euler.setFromQuaternion() instead.' );
  29572. },
  29573. getPositionFromMatrix: function ( m ) {
  29574. console.warn( 'THREE.Vector3: .getPositionFromMatrix() has been renamed to .setFromMatrixPosition().' );
  29575. return this.setFromMatrixPosition( m );
  29576. },
  29577. getScaleFromMatrix: function ( m ) {
  29578. console.warn( 'THREE.Vector3: .getScaleFromMatrix() has been renamed to .setFromMatrixScale().' );
  29579. return this.setFromMatrixScale( m );
  29580. },
  29581. getColumnFromMatrix: function ( index, matrix ) {
  29582. console.warn( 'THREE.Vector3: .getColumnFromMatrix() has been renamed to .setFromMatrixColumn().' );
  29583. return this.setFromMatrixColumn( matrix, index );
  29584. }
  29585. } );
  29586. //
  29587. Geometry.prototype.computeTangents = function () {
  29588. console.warn( 'THREE.Geometry: .computeTangents() has been removed.' );
  29589. };
  29590. Object.assign( Object3D.prototype, {
  29591. getChildByName: function ( name ) {
  29592. console.warn( 'THREE.Object3D: .getChildByName() has been renamed to .getObjectByName().' );
  29593. return this.getObjectByName( name );
  29594. },
  29595. renderDepth: function () {
  29596. console.warn( 'THREE.Object3D: .renderDepth has been removed. Use .renderOrder, instead.' );
  29597. },
  29598. translate: function ( distance, axis ) {
  29599. console.warn( 'THREE.Object3D: .translate() has been removed. Use .translateOnAxis( axis, distance ) instead.' );
  29600. return this.translateOnAxis( axis, distance );
  29601. }
  29602. } );
  29603. Object.defineProperties( Object3D.prototype, {
  29604. eulerOrder: {
  29605. get: function () {
  29606. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29607. return this.rotation.order;
  29608. },
  29609. set: function ( value ) {
  29610. console.warn( 'THREE.Object3D: .eulerOrder is now .rotation.order.' );
  29611. this.rotation.order = value;
  29612. }
  29613. },
  29614. useQuaternion: {
  29615. get: function () {
  29616. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29617. },
  29618. set: function () {
  29619. console.warn( 'THREE.Object3D: .useQuaternion has been removed. The library now uses quaternions by default.' );
  29620. }
  29621. }
  29622. } );
  29623. Object.defineProperties( LOD.prototype, {
  29624. objects: {
  29625. get: function () {
  29626. console.warn( 'THREE.LOD: .objects has been renamed to .levels.' );
  29627. return this.levels;
  29628. }
  29629. }
  29630. } );
  29631. //
  29632. PerspectiveCamera.prototype.setLens = function ( focalLength, filmGauge ) {
  29633. console.warn( "THREE.PerspectiveCamera.setLens is deprecated. " +
  29634. "Use .setFocalLength and .filmGauge for a photographic setup." );
  29635. if ( filmGauge !== undefined ) this.filmGauge = filmGauge;
  29636. this.setFocalLength( focalLength );
  29637. };
  29638. //
  29639. Object.defineProperties( Light.prototype, {
  29640. onlyShadow: {
  29641. set: function () {
  29642. console.warn( 'THREE.Light: .onlyShadow has been removed.' );
  29643. }
  29644. },
  29645. shadowCameraFov: {
  29646. set: function ( value ) {
  29647. console.warn( 'THREE.Light: .shadowCameraFov is now .shadow.camera.fov.' );
  29648. this.shadow.camera.fov = value;
  29649. }
  29650. },
  29651. shadowCameraLeft: {
  29652. set: function ( value ) {
  29653. console.warn( 'THREE.Light: .shadowCameraLeft is now .shadow.camera.left.' );
  29654. this.shadow.camera.left = value;
  29655. }
  29656. },
  29657. shadowCameraRight: {
  29658. set: function ( value ) {
  29659. console.warn( 'THREE.Light: .shadowCameraRight is now .shadow.camera.right.' );
  29660. this.shadow.camera.right = value;
  29661. }
  29662. },
  29663. shadowCameraTop: {
  29664. set: function ( value ) {
  29665. console.warn( 'THREE.Light: .shadowCameraTop is now .shadow.camera.top.' );
  29666. this.shadow.camera.top = value;
  29667. }
  29668. },
  29669. shadowCameraBottom: {
  29670. set: function ( value ) {
  29671. console.warn( 'THREE.Light: .shadowCameraBottom is now .shadow.camera.bottom.' );
  29672. this.shadow.camera.bottom = value;
  29673. }
  29674. },
  29675. shadowCameraNear: {
  29676. set: function ( value ) {
  29677. console.warn( 'THREE.Light: .shadowCameraNear is now .shadow.camera.near.' );
  29678. this.shadow.camera.near = value;
  29679. }
  29680. },
  29681. shadowCameraFar: {
  29682. set: function ( value ) {
  29683. console.warn( 'THREE.Light: .shadowCameraFar is now .shadow.camera.far.' );
  29684. this.shadow.camera.far = value;
  29685. }
  29686. },
  29687. shadowCameraVisible: {
  29688. set: function () {
  29689. console.warn( 'THREE.Light: .shadowCameraVisible has been removed. Use new THREE.CameraHelper( light.shadow.camera ) instead.' );
  29690. }
  29691. },
  29692. shadowBias: {
  29693. set: function ( value ) {
  29694. console.warn( 'THREE.Light: .shadowBias is now .shadow.bias.' );
  29695. this.shadow.bias = value;
  29696. }
  29697. },
  29698. shadowDarkness: {
  29699. set: function () {
  29700. console.warn( 'THREE.Light: .shadowDarkness has been removed.' );
  29701. }
  29702. },
  29703. shadowMapWidth: {
  29704. set: function ( value ) {
  29705. console.warn( 'THREE.Light: .shadowMapWidth is now .shadow.mapSize.width.' );
  29706. this.shadow.mapSize.width = value;
  29707. }
  29708. },
  29709. shadowMapHeight: {
  29710. set: function ( value ) {
  29711. console.warn( 'THREE.Light: .shadowMapHeight is now .shadow.mapSize.height.' );
  29712. this.shadow.mapSize.height = value;
  29713. }
  29714. }
  29715. } );
  29716. //
  29717. Object.defineProperties( BufferAttribute.prototype, {
  29718. length: {
  29719. get: function () {
  29720. console.warn( 'THREE.BufferAttribute: .length has been deprecated. Use .count instead.' );
  29721. return this.array.length;
  29722. }
  29723. }
  29724. } );
  29725. Object.assign( BufferGeometry.prototype, {
  29726. addIndex: function ( index ) {
  29727. console.warn( 'THREE.BufferGeometry: .addIndex() has been renamed to .setIndex().' );
  29728. this.setIndex( index );
  29729. },
  29730. addDrawCall: function ( start, count, indexOffset ) {
  29731. if ( indexOffset !== undefined ) {
  29732. console.warn( 'THREE.BufferGeometry: .addDrawCall() no longer supports indexOffset.' );
  29733. }
  29734. console.warn( 'THREE.BufferGeometry: .addDrawCall() is now .addGroup().' );
  29735. this.addGroup( start, count );
  29736. },
  29737. clearDrawCalls: function () {
  29738. console.warn( 'THREE.BufferGeometry: .clearDrawCalls() is now .clearGroups().' );
  29739. this.clearGroups();
  29740. },
  29741. computeTangents: function () {
  29742. console.warn( 'THREE.BufferGeometry: .computeTangents() has been removed.' );
  29743. },
  29744. computeOffsets: function () {
  29745. console.warn( 'THREE.BufferGeometry: .computeOffsets() has been removed.' );
  29746. }
  29747. } );
  29748. Object.defineProperties( BufferGeometry.prototype, {
  29749. drawcalls: {
  29750. get: function () {
  29751. console.error( 'THREE.BufferGeometry: .drawcalls has been renamed to .groups.' );
  29752. return this.groups;
  29753. }
  29754. },
  29755. offsets: {
  29756. get: function () {
  29757. console.warn( 'THREE.BufferGeometry: .offsets has been renamed to .groups.' );
  29758. return this.groups;
  29759. }
  29760. }
  29761. } );
  29762. //
  29763. Object.defineProperties( Uniform.prototype, {
  29764. dynamic: {
  29765. set: function () {
  29766. console.warn( 'THREE.Uniform: .dynamic has been removed. Use object.onBeforeRender() instead.' );
  29767. }
  29768. },
  29769. onUpdate: {
  29770. value: function () {
  29771. console.warn( 'THREE.Uniform: .onUpdate() has been removed. Use object.onBeforeRender() instead.' );
  29772. return this;
  29773. }
  29774. }
  29775. } );
  29776. //
  29777. Object.defineProperties( Material.prototype, {
  29778. wrapAround: {
  29779. get: function () {
  29780. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  29781. },
  29782. set: function () {
  29783. console.warn( 'THREE.' + this.type + ': .wrapAround has been removed.' );
  29784. }
  29785. },
  29786. wrapRGB: {
  29787. get: function () {
  29788. console.warn( 'THREE.' + this.type + ': .wrapRGB has been removed.' );
  29789. return new Color();
  29790. }
  29791. }
  29792. } );
  29793. Object.defineProperties( MeshPhongMaterial.prototype, {
  29794. metal: {
  29795. get: function () {
  29796. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead.' );
  29797. return false;
  29798. },
  29799. set: function () {
  29800. console.warn( 'THREE.MeshPhongMaterial: .metal has been removed. Use THREE.MeshStandardMaterial instead' );
  29801. }
  29802. }
  29803. } );
  29804. Object.defineProperties( ShaderMaterial.prototype, {
  29805. derivatives: {
  29806. get: function () {
  29807. console.warn( 'THREE.ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29808. return this.extensions.derivatives;
  29809. },
  29810. set: function ( value ) {
  29811. console.warn( 'THREE. ShaderMaterial: .derivatives has been moved to .extensions.derivatives.' );
  29812. this.extensions.derivatives = value;
  29813. }
  29814. }
  29815. } );
  29816. //
  29817. EventDispatcher.prototype = Object.assign( Object.create( {
  29818. // Note: Extra base ensures these properties are not 'assign'ed.
  29819. constructor: EventDispatcher,
  29820. apply: function ( target ) {
  29821. console.warn( "THREE.EventDispatcher: .apply is deprecated, " +
  29822. "just inherit or Object.assign the prototype to mix-in." );
  29823. Object.assign( target, this );
  29824. }
  29825. } ), EventDispatcher.prototype );
  29826. //
  29827. Object.assign( WebGLRenderer.prototype, {
  29828. supportsFloatTextures: function () {
  29829. console.warn( 'THREE.WebGLRenderer: .supportsFloatTextures() is now .extensions.get( \'OES_texture_float\' ).' );
  29830. return this.extensions.get( 'OES_texture_float' );
  29831. },
  29832. supportsHalfFloatTextures: function () {
  29833. console.warn( 'THREE.WebGLRenderer: .supportsHalfFloatTextures() is now .extensions.get( \'OES_texture_half_float\' ).' );
  29834. return this.extensions.get( 'OES_texture_half_float' );
  29835. },
  29836. supportsStandardDerivatives: function () {
  29837. console.warn( 'THREE.WebGLRenderer: .supportsStandardDerivatives() is now .extensions.get( \'OES_standard_derivatives\' ).' );
  29838. return this.extensions.get( 'OES_standard_derivatives' );
  29839. },
  29840. supportsCompressedTextureS3TC: function () {
  29841. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTextureS3TC() is now .extensions.get( \'WEBGL_compressed_texture_s3tc\' ).' );
  29842. return this.extensions.get( 'WEBGL_compressed_texture_s3tc' );
  29843. },
  29844. supportsCompressedTexturePVRTC: function () {
  29845. console.warn( 'THREE.WebGLRenderer: .supportsCompressedTexturePVRTC() is now .extensions.get( \'WEBGL_compressed_texture_pvrtc\' ).' );
  29846. return this.extensions.get( 'WEBGL_compressed_texture_pvrtc' );
  29847. },
  29848. supportsBlendMinMax: function () {
  29849. console.warn( 'THREE.WebGLRenderer: .supportsBlendMinMax() is now .extensions.get( \'EXT_blend_minmax\' ).' );
  29850. return this.extensions.get( 'EXT_blend_minmax' );
  29851. },
  29852. supportsVertexTextures: function () {
  29853. console.warn( 'THREE.WebGLRenderer: .supportsVertexTextures() is now .capabilities.vertexTextures.' );
  29854. return this.capabilities.vertexTextures;
  29855. },
  29856. supportsInstancedArrays: function () {
  29857. console.warn( 'THREE.WebGLRenderer: .supportsInstancedArrays() is now .extensions.get( \'ANGLE_instanced_arrays\' ).' );
  29858. return this.extensions.get( 'ANGLE_instanced_arrays' );
  29859. },
  29860. enableScissorTest: function ( boolean ) {
  29861. console.warn( 'THREE.WebGLRenderer: .enableScissorTest() is now .setScissorTest().' );
  29862. this.setScissorTest( boolean );
  29863. },
  29864. initMaterial: function () {
  29865. console.warn( 'THREE.WebGLRenderer: .initMaterial() has been removed.' );
  29866. },
  29867. addPrePlugin: function () {
  29868. console.warn( 'THREE.WebGLRenderer: .addPrePlugin() has been removed.' );
  29869. },
  29870. addPostPlugin: function () {
  29871. console.warn( 'THREE.WebGLRenderer: .addPostPlugin() has been removed.' );
  29872. },
  29873. updateShadowMap: function () {
  29874. console.warn( 'THREE.WebGLRenderer: .updateShadowMap() has been removed.' );
  29875. }
  29876. } );
  29877. Object.defineProperties( WebGLRenderer.prototype, {
  29878. shadowMapEnabled: {
  29879. get: function () {
  29880. return this.shadowMap.enabled;
  29881. },
  29882. set: function ( value ) {
  29883. console.warn( 'THREE.WebGLRenderer: .shadowMapEnabled is now .shadowMap.enabled.' );
  29884. this.shadowMap.enabled = value;
  29885. }
  29886. },
  29887. shadowMapType: {
  29888. get: function () {
  29889. return this.shadowMap.type;
  29890. },
  29891. set: function ( value ) {
  29892. console.warn( 'THREE.WebGLRenderer: .shadowMapType is now .shadowMap.type.' );
  29893. this.shadowMap.type = value;
  29894. }
  29895. },
  29896. shadowMapCullFace: {
  29897. get: function () {
  29898. return this.shadowMap.cullFace;
  29899. },
  29900. set: function ( value ) {
  29901. console.warn( 'THREE.WebGLRenderer: .shadowMapCullFace is now .shadowMap.cullFace.' );
  29902. this.shadowMap.cullFace = value;
  29903. }
  29904. }
  29905. } );
  29906. Object.defineProperties( WebGLShadowMap.prototype, {
  29907. cullFace: {
  29908. get: function () {
  29909. return this.renderReverseSided ? CullFaceFront : CullFaceBack;
  29910. },
  29911. set: function ( cullFace ) {
  29912. var value = ( cullFace !== CullFaceBack );
  29913. console.warn( "WebGLRenderer: .shadowMap.cullFace is deprecated. Set .shadowMap.renderReverseSided to " + value + "." );
  29914. this.renderReverseSided = value;
  29915. }
  29916. }
  29917. } );
  29918. //
  29919. Object.defineProperties( WebGLRenderTarget.prototype, {
  29920. wrapS: {
  29921. get: function () {
  29922. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29923. return this.texture.wrapS;
  29924. },
  29925. set: function ( value ) {
  29926. console.warn( 'THREE.WebGLRenderTarget: .wrapS is now .texture.wrapS.' );
  29927. this.texture.wrapS = value;
  29928. }
  29929. },
  29930. wrapT: {
  29931. get: function () {
  29932. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29933. return this.texture.wrapT;
  29934. },
  29935. set: function ( value ) {
  29936. console.warn( 'THREE.WebGLRenderTarget: .wrapT is now .texture.wrapT.' );
  29937. this.texture.wrapT = value;
  29938. }
  29939. },
  29940. magFilter: {
  29941. get: function () {
  29942. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29943. return this.texture.magFilter;
  29944. },
  29945. set: function ( value ) {
  29946. console.warn( 'THREE.WebGLRenderTarget: .magFilter is now .texture.magFilter.' );
  29947. this.texture.magFilter = value;
  29948. }
  29949. },
  29950. minFilter: {
  29951. get: function () {
  29952. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29953. return this.texture.minFilter;
  29954. },
  29955. set: function ( value ) {
  29956. console.warn( 'THREE.WebGLRenderTarget: .minFilter is now .texture.minFilter.' );
  29957. this.texture.minFilter = value;
  29958. }
  29959. },
  29960. anisotropy: {
  29961. get: function () {
  29962. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29963. return this.texture.anisotropy;
  29964. },
  29965. set: function ( value ) {
  29966. console.warn( 'THREE.WebGLRenderTarget: .anisotropy is now .texture.anisotropy.' );
  29967. this.texture.anisotropy = value;
  29968. }
  29969. },
  29970. offset: {
  29971. get: function () {
  29972. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29973. return this.texture.offset;
  29974. },
  29975. set: function ( value ) {
  29976. console.warn( 'THREE.WebGLRenderTarget: .offset is now .texture.offset.' );
  29977. this.texture.offset = value;
  29978. }
  29979. },
  29980. repeat: {
  29981. get: function () {
  29982. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29983. return this.texture.repeat;
  29984. },
  29985. set: function ( value ) {
  29986. console.warn( 'THREE.WebGLRenderTarget: .repeat is now .texture.repeat.' );
  29987. this.texture.repeat = value;
  29988. }
  29989. },
  29990. format: {
  29991. get: function () {
  29992. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29993. return this.texture.format;
  29994. },
  29995. set: function ( value ) {
  29996. console.warn( 'THREE.WebGLRenderTarget: .format is now .texture.format.' );
  29997. this.texture.format = value;
  29998. }
  29999. },
  30000. type: {
  30001. get: function () {
  30002. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30003. return this.texture.type;
  30004. },
  30005. set: function ( value ) {
  30006. console.warn( 'THREE.WebGLRenderTarget: .type is now .texture.type.' );
  30007. this.texture.type = value;
  30008. }
  30009. },
  30010. generateMipmaps: {
  30011. get: function () {
  30012. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30013. return this.texture.generateMipmaps;
  30014. },
  30015. set: function ( value ) {
  30016. console.warn( 'THREE.WebGLRenderTarget: .generateMipmaps is now .texture.generateMipmaps.' );
  30017. this.texture.generateMipmaps = value;
  30018. }
  30019. }
  30020. } );
  30021. //
  30022. Audio.prototype.load = function ( file ) {
  30023. console.warn( 'THREE.Audio: .load has been deprecated. Use THREE.AudioLoader instead.' );
  30024. var scope = this;
  30025. var audioLoader = new AudioLoader();
  30026. audioLoader.load( file, function ( buffer ) {
  30027. scope.setBuffer( buffer );
  30028. } );
  30029. return this;
  30030. };
  30031. AudioAnalyser.prototype.getData = function () {
  30032. console.warn( 'THREE.AudioAnalyser: .getData() is now .getFrequencyData().' );
  30033. return this.getFrequencyData();
  30034. };
  30035. //
  30036. var GeometryUtils = {
  30037. merge: function ( geometry1, geometry2, materialIndexOffset ) {
  30038. console.warn( 'THREE.GeometryUtils: .merge() has been moved to Geometry. Use geometry.merge( geometry2, matrix, materialIndexOffset ) instead.' );
  30039. var matrix;
  30040. if ( geometry2.isMesh ) {
  30041. geometry2.matrixAutoUpdate && geometry2.updateMatrix();
  30042. matrix = geometry2.matrix;
  30043. geometry2 = geometry2.geometry;
  30044. }
  30045. geometry1.merge( geometry2, matrix, materialIndexOffset );
  30046. },
  30047. center: function ( geometry ) {
  30048. console.warn( 'THREE.GeometryUtils: .center() has been moved to Geometry. Use geometry.center() instead.' );
  30049. return geometry.center();
  30050. }
  30051. };
  30052. var ImageUtils = {
  30053. crossOrigin: undefined,
  30054. loadTexture: function ( url, mapping, onLoad, onError ) {
  30055. console.warn( 'THREE.ImageUtils.loadTexture has been deprecated. Use THREE.TextureLoader() instead.' );
  30056. var loader = new TextureLoader();
  30057. loader.setCrossOrigin( this.crossOrigin );
  30058. var texture = loader.load( url, onLoad, undefined, onError );
  30059. if ( mapping ) texture.mapping = mapping;
  30060. return texture;
  30061. },
  30062. loadTextureCube: function ( urls, mapping, onLoad, onError ) {
  30063. console.warn( 'THREE.ImageUtils.loadTextureCube has been deprecated. Use THREE.CubeTextureLoader() instead.' );
  30064. var loader = new CubeTextureLoader();
  30065. loader.setCrossOrigin( this.crossOrigin );
  30066. var texture = loader.load( urls, onLoad, undefined, onError );
  30067. if ( mapping ) texture.mapping = mapping;
  30068. return texture;
  30069. },
  30070. loadCompressedTexture: function () {
  30071. console.error( 'THREE.ImageUtils.loadCompressedTexture has been removed. Use THREE.DDSLoader instead.' );
  30072. },
  30073. loadCompressedTextureCube: function () {
  30074. console.error( 'THREE.ImageUtils.loadCompressedTextureCube has been removed. Use THREE.DDSLoader instead.' );
  30075. }
  30076. };
  30077. //
  30078. function Projector() {
  30079. console.error( 'THREE.Projector has been moved to /examples/js/renderers/Projector.js.' );
  30080. this.projectVector = function ( vector, camera ) {
  30081. console.warn( 'THREE.Projector: .projectVector() is now vector.project().' );
  30082. vector.project( camera );
  30083. };
  30084. this.unprojectVector = function ( vector, camera ) {
  30085. console.warn( 'THREE.Projector: .unprojectVector() is now vector.unproject().' );
  30086. vector.unproject( camera );
  30087. };
  30088. this.pickingRay = function () {
  30089. console.error( 'THREE.Projector: .pickingRay() is now raycaster.setFromCamera().' );
  30090. };
  30091. }
  30092. //
  30093. function CanvasRenderer() {
  30094. console.error( 'THREE.CanvasRenderer has been moved to /examples/js/renderers/CanvasRenderer.js' );
  30095. this.domElement = document.createElementNS( 'http://www.w3.org/1999/xhtml', 'canvas' );
  30096. this.clear = function () {};
  30097. this.render = function () {};
  30098. this.setClearColor = function () {};
  30099. this.setSize = function () {};
  30100. }
  30101. exports.WebGLRenderTargetCube = WebGLRenderTargetCube;
  30102. exports.WebGLRenderTarget = WebGLRenderTarget;
  30103. exports.WebGLRenderer = WebGLRenderer;
  30104. exports.ShaderLib = ShaderLib;
  30105. exports.UniformsLib = UniformsLib;
  30106. exports.UniformsUtils = UniformsUtils;
  30107. exports.ShaderChunk = ShaderChunk;
  30108. exports.FogExp2 = FogExp2;
  30109. exports.Fog = Fog;
  30110. exports.Scene = Scene;
  30111. exports.LensFlare = LensFlare;
  30112. exports.Sprite = Sprite;
  30113. exports.LOD = LOD;
  30114. exports.SkinnedMesh = SkinnedMesh;
  30115. exports.Skeleton = Skeleton;
  30116. exports.Bone = Bone;
  30117. exports.Mesh = Mesh;
  30118. exports.LineSegments = LineSegments;
  30119. exports.Line = Line;
  30120. exports.Points = Points;
  30121. exports.Group = Group;
  30122. exports.VideoTexture = VideoTexture;
  30123. exports.DataTexture = DataTexture;
  30124. exports.CompressedTexture = CompressedTexture;
  30125. exports.CubeTexture = CubeTexture;
  30126. exports.CanvasTexture = CanvasTexture;
  30127. exports.DepthTexture = DepthTexture;
  30128. exports.Texture = Texture;
  30129. exports.CompressedTextureLoader = CompressedTextureLoader;
  30130. exports.BinaryTextureLoader = BinaryTextureLoader;
  30131. exports.DataTextureLoader = DataTextureLoader;
  30132. exports.CubeTextureLoader = CubeTextureLoader;
  30133. exports.TextureLoader = TextureLoader;
  30134. exports.ObjectLoader = ObjectLoader;
  30135. exports.MaterialLoader = MaterialLoader;
  30136. exports.BufferGeometryLoader = BufferGeometryLoader;
  30137. exports.DefaultLoadingManager = DefaultLoadingManager;
  30138. exports.LoadingManager = LoadingManager;
  30139. exports.JSONLoader = JSONLoader;
  30140. exports.ImageLoader = ImageLoader;
  30141. exports.FontLoader = FontLoader;
  30142. exports.FileLoader = FileLoader;
  30143. exports.Loader = Loader;
  30144. exports.Cache = Cache;
  30145. exports.AudioLoader = AudioLoader;
  30146. exports.SpotLightShadow = SpotLightShadow;
  30147. exports.SpotLight = SpotLight;
  30148. exports.PointLight = PointLight;
  30149. exports.RectAreaLight = RectAreaLight;
  30150. exports.HemisphereLight = HemisphereLight;
  30151. exports.DirectionalLightShadow = DirectionalLightShadow;
  30152. exports.DirectionalLight = DirectionalLight;
  30153. exports.AmbientLight = AmbientLight;
  30154. exports.LightShadow = LightShadow;
  30155. exports.Light = Light;
  30156. exports.StereoCamera = StereoCamera;
  30157. exports.PerspectiveCamera = PerspectiveCamera;
  30158. exports.OrthographicCamera = OrthographicCamera;
  30159. exports.CubeCamera = CubeCamera;
  30160. exports.Camera = Camera;
  30161. exports.AudioListener = AudioListener;
  30162. exports.PositionalAudio = PositionalAudio;
  30163. exports.AudioContext = AudioContext;
  30164. exports.AudioAnalyser = AudioAnalyser;
  30165. exports.Audio = Audio;
  30166. exports.VectorKeyframeTrack = VectorKeyframeTrack;
  30167. exports.StringKeyframeTrack = StringKeyframeTrack;
  30168. exports.QuaternionKeyframeTrack = QuaternionKeyframeTrack;
  30169. exports.NumberKeyframeTrack = NumberKeyframeTrack;
  30170. exports.ColorKeyframeTrack = ColorKeyframeTrack;
  30171. exports.BooleanKeyframeTrack = BooleanKeyframeTrack;
  30172. exports.PropertyMixer = PropertyMixer;
  30173. exports.PropertyBinding = PropertyBinding;
  30174. exports.KeyframeTrack = KeyframeTrack;
  30175. exports.AnimationUtils = AnimationUtils;
  30176. exports.AnimationObjectGroup = AnimationObjectGroup;
  30177. exports.AnimationMixer = AnimationMixer;
  30178. exports.AnimationClip = AnimationClip;
  30179. exports.Uniform = Uniform;
  30180. exports.InstancedBufferGeometry = InstancedBufferGeometry;
  30181. exports.BufferGeometry = BufferGeometry;
  30182. exports.GeometryIdCount = GeometryIdCount;
  30183. exports.Geometry = Geometry;
  30184. exports.InterleavedBufferAttribute = InterleavedBufferAttribute;
  30185. exports.InstancedInterleavedBuffer = InstancedInterleavedBuffer;
  30186. exports.InterleavedBuffer = InterleavedBuffer;
  30187. exports.InstancedBufferAttribute = InstancedBufferAttribute;
  30188. exports.Face3 = Face3;
  30189. exports.Object3D = Object3D;
  30190. exports.Raycaster = Raycaster;
  30191. exports.Layers = Layers;
  30192. exports.EventDispatcher = EventDispatcher;
  30193. exports.Clock = Clock;
  30194. exports.QuaternionLinearInterpolant = QuaternionLinearInterpolant;
  30195. exports.LinearInterpolant = LinearInterpolant;
  30196. exports.DiscreteInterpolant = DiscreteInterpolant;
  30197. exports.CubicInterpolant = CubicInterpolant;
  30198. exports.Interpolant = Interpolant;
  30199. exports.Triangle = Triangle;
  30200. exports.Spline = Spline;
  30201. exports.Math = _Math;
  30202. exports.Spherical = Spherical;
  30203. exports.Cylindrical = Cylindrical;
  30204. exports.Plane = Plane;
  30205. exports.Frustum = Frustum;
  30206. exports.Sphere = Sphere;
  30207. exports.Ray = Ray;
  30208. exports.Matrix4 = Matrix4;
  30209. exports.Matrix3 = Matrix3;
  30210. exports.Box3 = Box3;
  30211. exports.Box2 = Box2;
  30212. exports.Line3 = Line3;
  30213. exports.Euler = Euler;
  30214. exports.Vector4 = Vector4;
  30215. exports.Vector3 = Vector3;
  30216. exports.Vector2 = Vector2;
  30217. exports.Quaternion = Quaternion;
  30218. exports.Color = Color;
  30219. exports.MorphBlendMesh = MorphBlendMesh;
  30220. exports.ImmediateRenderObject = ImmediateRenderObject;
  30221. exports.VertexNormalsHelper = VertexNormalsHelper;
  30222. exports.SpotLightHelper = SpotLightHelper;
  30223. exports.SkeletonHelper = SkeletonHelper;
  30224. exports.PointLightHelper = PointLightHelper;
  30225. exports.RectAreaLightHelper = RectAreaLightHelper;
  30226. exports.HemisphereLightHelper = HemisphereLightHelper;
  30227. exports.GridHelper = GridHelper;
  30228. exports.PolarGridHelper = PolarGridHelper;
  30229. exports.FaceNormalsHelper = FaceNormalsHelper;
  30230. exports.DirectionalLightHelper = DirectionalLightHelper;
  30231. exports.CameraHelper = CameraHelper;
  30232. exports.BoxHelper = BoxHelper;
  30233. exports.ArrowHelper = ArrowHelper;
  30234. exports.AxisHelper = AxisHelper;
  30235. exports.CatmullRomCurve3 = CatmullRomCurve3;
  30236. exports.SplineCurve3 = SplineCurve3;
  30237. exports.CubicBezierCurve3 = CubicBezierCurve3;
  30238. exports.QuadraticBezierCurve3 = QuadraticBezierCurve3;
  30239. exports.LineCurve3 = LineCurve3;
  30240. exports.ArcCurve = ArcCurve;
  30241. exports.EllipseCurve = EllipseCurve;
  30242. exports.SplineCurve = SplineCurve;
  30243. exports.CubicBezierCurve = CubicBezierCurve;
  30244. exports.QuadraticBezierCurve = QuadraticBezierCurve;
  30245. exports.LineCurve = LineCurve;
  30246. exports.Shape = Shape;
  30247. exports.ShapePath = ShapePath;
  30248. exports.Path = Path;
  30249. exports.Font = Font;
  30250. exports.CurvePath = CurvePath;
  30251. exports.Curve = Curve;
  30252. exports.ShapeUtils = ShapeUtils;
  30253. exports.SceneUtils = SceneUtils;
  30254. exports.CurveUtils = CurveUtils;
  30255. exports.WireframeGeometry = WireframeGeometry;
  30256. exports.ParametricGeometry = ParametricGeometry;
  30257. exports.ParametricBufferGeometry = ParametricBufferGeometry;
  30258. exports.TetrahedronGeometry = TetrahedronGeometry;
  30259. exports.TetrahedronBufferGeometry = TetrahedronBufferGeometry;
  30260. exports.OctahedronGeometry = OctahedronGeometry;
  30261. exports.OctahedronBufferGeometry = OctahedronBufferGeometry;
  30262. exports.IcosahedronGeometry = IcosahedronGeometry;
  30263. exports.IcosahedronBufferGeometry = IcosahedronBufferGeometry;
  30264. exports.DodecahedronGeometry = DodecahedronGeometry;
  30265. exports.DodecahedronBufferGeometry = DodecahedronBufferGeometry;
  30266. exports.PolyhedronGeometry = PolyhedronGeometry;
  30267. exports.PolyhedronBufferGeometry = PolyhedronBufferGeometry;
  30268. exports.TubeGeometry = TubeGeometry;
  30269. exports.TubeBufferGeometry = TubeBufferGeometry;
  30270. exports.TorusKnotGeometry = TorusKnotGeometry;
  30271. exports.TorusKnotBufferGeometry = TorusKnotBufferGeometry;
  30272. exports.TorusGeometry = TorusGeometry;
  30273. exports.TorusBufferGeometry = TorusBufferGeometry;
  30274. exports.TextGeometry = TextGeometry;
  30275. exports.SphereBufferGeometry = SphereBufferGeometry;
  30276. exports.SphereGeometry = SphereGeometry;
  30277. exports.RingGeometry = RingGeometry;
  30278. exports.RingBufferGeometry = RingBufferGeometry;
  30279. exports.PlaneBufferGeometry = PlaneBufferGeometry;
  30280. exports.PlaneGeometry = PlaneGeometry;
  30281. exports.LatheGeometry = LatheGeometry;
  30282. exports.LatheBufferGeometry = LatheBufferGeometry;
  30283. exports.ShapeGeometry = ShapeGeometry;
  30284. exports.ShapeBufferGeometry = ShapeBufferGeometry;
  30285. exports.ExtrudeGeometry = ExtrudeGeometry;
  30286. exports.EdgesGeometry = EdgesGeometry;
  30287. exports.ConeGeometry = ConeGeometry;
  30288. exports.ConeBufferGeometry = ConeBufferGeometry;
  30289. exports.CylinderGeometry = CylinderGeometry;
  30290. exports.CylinderBufferGeometry = CylinderBufferGeometry;
  30291. exports.CircleBufferGeometry = CircleBufferGeometry;
  30292. exports.CircleGeometry = CircleGeometry;
  30293. exports.BoxBufferGeometry = BoxBufferGeometry;
  30294. exports.BoxGeometry = BoxGeometry;
  30295. exports.ShadowMaterial = ShadowMaterial;
  30296. exports.SpriteMaterial = SpriteMaterial;
  30297. exports.RawShaderMaterial = RawShaderMaterial;
  30298. exports.ShaderMaterial = ShaderMaterial;
  30299. exports.PointsMaterial = PointsMaterial;
  30300. exports.MultiMaterial = MultiMaterial;
  30301. exports.MeshPhysicalMaterial = MeshPhysicalMaterial;
  30302. exports.MeshStandardMaterial = MeshStandardMaterial;
  30303. exports.MeshPhongMaterial = MeshPhongMaterial;
  30304. exports.MeshToonMaterial = MeshToonMaterial;
  30305. exports.MeshNormalMaterial = MeshNormalMaterial;
  30306. exports.MeshLambertMaterial = MeshLambertMaterial;
  30307. exports.MeshDepthMaterial = MeshDepthMaterial;
  30308. exports.MeshBasicMaterial = MeshBasicMaterial;
  30309. exports.LineDashedMaterial = LineDashedMaterial;
  30310. exports.LineBasicMaterial = LineBasicMaterial;
  30311. exports.Material = Material;
  30312. exports.Float64BufferAttribute = Float64BufferAttribute;
  30313. exports.Float32BufferAttribute = Float32BufferAttribute;
  30314. exports.Uint32BufferAttribute = Uint32BufferAttribute;
  30315. exports.Int32BufferAttribute = Int32BufferAttribute;
  30316. exports.Uint16BufferAttribute = Uint16BufferAttribute;
  30317. exports.Int16BufferAttribute = Int16BufferAttribute;
  30318. exports.Uint8ClampedBufferAttribute = Uint8ClampedBufferAttribute;
  30319. exports.Uint8BufferAttribute = Uint8BufferAttribute;
  30320. exports.Int8BufferAttribute = Int8BufferAttribute;
  30321. exports.BufferAttribute = BufferAttribute;
  30322. exports.REVISION = REVISION;
  30323. exports.MOUSE = MOUSE;
  30324. exports.CullFaceNone = CullFaceNone;
  30325. exports.CullFaceBack = CullFaceBack;
  30326. exports.CullFaceFront = CullFaceFront;
  30327. exports.CullFaceFrontBack = CullFaceFrontBack;
  30328. exports.FrontFaceDirectionCW = FrontFaceDirectionCW;
  30329. exports.FrontFaceDirectionCCW = FrontFaceDirectionCCW;
  30330. exports.BasicShadowMap = BasicShadowMap;
  30331. exports.PCFShadowMap = PCFShadowMap;
  30332. exports.PCFSoftShadowMap = PCFSoftShadowMap;
  30333. exports.FrontSide = FrontSide;
  30334. exports.BackSide = BackSide;
  30335. exports.DoubleSide = DoubleSide;
  30336. exports.FlatShading = FlatShading;
  30337. exports.SmoothShading = SmoothShading;
  30338. exports.NoColors = NoColors;
  30339. exports.FaceColors = FaceColors;
  30340. exports.VertexColors = VertexColors;
  30341. exports.NoBlending = NoBlending;
  30342. exports.NormalBlending = NormalBlending;
  30343. exports.AdditiveBlending = AdditiveBlending;
  30344. exports.SubtractiveBlending = SubtractiveBlending;
  30345. exports.MultiplyBlending = MultiplyBlending;
  30346. exports.CustomBlending = CustomBlending;
  30347. exports.BlendingMode = BlendingMode;
  30348. exports.AddEquation = AddEquation;
  30349. exports.SubtractEquation = SubtractEquation;
  30350. exports.ReverseSubtractEquation = ReverseSubtractEquation;
  30351. exports.MinEquation = MinEquation;
  30352. exports.MaxEquation = MaxEquation;
  30353. exports.ZeroFactor = ZeroFactor;
  30354. exports.OneFactor = OneFactor;
  30355. exports.SrcColorFactor = SrcColorFactor;
  30356. exports.OneMinusSrcColorFactor = OneMinusSrcColorFactor;
  30357. exports.SrcAlphaFactor = SrcAlphaFactor;
  30358. exports.OneMinusSrcAlphaFactor = OneMinusSrcAlphaFactor;
  30359. exports.DstAlphaFactor = DstAlphaFactor;
  30360. exports.OneMinusDstAlphaFactor = OneMinusDstAlphaFactor;
  30361. exports.DstColorFactor = DstColorFactor;
  30362. exports.OneMinusDstColorFactor = OneMinusDstColorFactor;
  30363. exports.SrcAlphaSaturateFactor = SrcAlphaSaturateFactor;
  30364. exports.NeverDepth = NeverDepth;
  30365. exports.AlwaysDepth = AlwaysDepth;
  30366. exports.LessDepth = LessDepth;
  30367. exports.LessEqualDepth = LessEqualDepth;
  30368. exports.EqualDepth = EqualDepth;
  30369. exports.GreaterEqualDepth = GreaterEqualDepth;
  30370. exports.GreaterDepth = GreaterDepth;
  30371. exports.NotEqualDepth = NotEqualDepth;
  30372. exports.MultiplyOperation = MultiplyOperation;
  30373. exports.MixOperation = MixOperation;
  30374. exports.AddOperation = AddOperation;
  30375. exports.NoToneMapping = NoToneMapping;
  30376. exports.LinearToneMapping = LinearToneMapping;
  30377. exports.ReinhardToneMapping = ReinhardToneMapping;
  30378. exports.Uncharted2ToneMapping = Uncharted2ToneMapping;
  30379. exports.CineonToneMapping = CineonToneMapping;
  30380. exports.UVMapping = UVMapping;
  30381. exports.CubeReflectionMapping = CubeReflectionMapping;
  30382. exports.CubeRefractionMapping = CubeRefractionMapping;
  30383. exports.EquirectangularReflectionMapping = EquirectangularReflectionMapping;
  30384. exports.EquirectangularRefractionMapping = EquirectangularRefractionMapping;
  30385. exports.SphericalReflectionMapping = SphericalReflectionMapping;
  30386. exports.CubeUVReflectionMapping = CubeUVReflectionMapping;
  30387. exports.CubeUVRefractionMapping = CubeUVRefractionMapping;
  30388. exports.TextureMapping = TextureMapping;
  30389. exports.RepeatWrapping = RepeatWrapping;
  30390. exports.ClampToEdgeWrapping = ClampToEdgeWrapping;
  30391. exports.MirroredRepeatWrapping = MirroredRepeatWrapping;
  30392. exports.TextureWrapping = TextureWrapping;
  30393. exports.NearestFilter = NearestFilter;
  30394. exports.NearestMipMapNearestFilter = NearestMipMapNearestFilter;
  30395. exports.NearestMipMapLinearFilter = NearestMipMapLinearFilter;
  30396. exports.LinearFilter = LinearFilter;
  30397. exports.LinearMipMapNearestFilter = LinearMipMapNearestFilter;
  30398. exports.LinearMipMapLinearFilter = LinearMipMapLinearFilter;
  30399. exports.TextureFilter = TextureFilter;
  30400. exports.UnsignedByteType = UnsignedByteType;
  30401. exports.ByteType = ByteType;
  30402. exports.ShortType = ShortType;
  30403. exports.UnsignedShortType = UnsignedShortType;
  30404. exports.IntType = IntType;
  30405. exports.UnsignedIntType = UnsignedIntType;
  30406. exports.FloatType = FloatType;
  30407. exports.HalfFloatType = HalfFloatType;
  30408. exports.UnsignedShort4444Type = UnsignedShort4444Type;
  30409. exports.UnsignedShort5551Type = UnsignedShort5551Type;
  30410. exports.UnsignedShort565Type = UnsignedShort565Type;
  30411. exports.UnsignedInt248Type = UnsignedInt248Type;
  30412. exports.AlphaFormat = AlphaFormat;
  30413. exports.RGBFormat = RGBFormat;
  30414. exports.RGBAFormat = RGBAFormat;
  30415. exports.LuminanceFormat = LuminanceFormat;
  30416. exports.LuminanceAlphaFormat = LuminanceAlphaFormat;
  30417. exports.RGBEFormat = RGBEFormat;
  30418. exports.DepthFormat = DepthFormat;
  30419. exports.DepthStencilFormat = DepthStencilFormat;
  30420. exports.RGB_S3TC_DXT1_Format = RGB_S3TC_DXT1_Format;
  30421. exports.RGBA_S3TC_DXT1_Format = RGBA_S3TC_DXT1_Format;
  30422. exports.RGBA_S3TC_DXT3_Format = RGBA_S3TC_DXT3_Format;
  30423. exports.RGBA_S3TC_DXT5_Format = RGBA_S3TC_DXT5_Format;
  30424. exports.RGB_PVRTC_4BPPV1_Format = RGB_PVRTC_4BPPV1_Format;
  30425. exports.RGB_PVRTC_2BPPV1_Format = RGB_PVRTC_2BPPV1_Format;
  30426. exports.RGBA_PVRTC_4BPPV1_Format = RGBA_PVRTC_4BPPV1_Format;
  30427. exports.RGBA_PVRTC_2BPPV1_Format = RGBA_PVRTC_2BPPV1_Format;
  30428. exports.RGB_ETC1_Format = RGB_ETC1_Format;
  30429. exports.LoopOnce = LoopOnce;
  30430. exports.LoopRepeat = LoopRepeat;
  30431. exports.LoopPingPong = LoopPingPong;
  30432. exports.InterpolateDiscrete = InterpolateDiscrete;
  30433. exports.InterpolateLinear = InterpolateLinear;
  30434. exports.InterpolateSmooth = InterpolateSmooth;
  30435. exports.ZeroCurvatureEnding = ZeroCurvatureEnding;
  30436. exports.ZeroSlopeEnding = ZeroSlopeEnding;
  30437. exports.WrapAroundEnding = WrapAroundEnding;
  30438. exports.TrianglesDrawMode = TrianglesDrawMode;
  30439. exports.TriangleStripDrawMode = TriangleStripDrawMode;
  30440. exports.TriangleFanDrawMode = TriangleFanDrawMode;
  30441. exports.LinearEncoding = LinearEncoding;
  30442. exports.sRGBEncoding = sRGBEncoding;
  30443. exports.GammaEncoding = GammaEncoding;
  30444. exports.RGBEEncoding = RGBEEncoding;
  30445. exports.LogLuvEncoding = LogLuvEncoding;
  30446. exports.RGBM7Encoding = RGBM7Encoding;
  30447. exports.RGBM16Encoding = RGBM16Encoding;
  30448. exports.RGBDEncoding = RGBDEncoding;
  30449. exports.BasicDepthPacking = BasicDepthPacking;
  30450. exports.RGBADepthPacking = RGBADepthPacking;
  30451. exports.CubeGeometry = BoxGeometry;
  30452. exports.Face4 = Face4;
  30453. exports.LineStrip = LineStrip;
  30454. exports.LinePieces = LinePieces;
  30455. exports.MeshFaceMaterial = MeshFaceMaterial;
  30456. exports.PointCloud = PointCloud;
  30457. exports.Particle = Particle;
  30458. exports.ParticleSystem = ParticleSystem;
  30459. exports.PointCloudMaterial = PointCloudMaterial;
  30460. exports.ParticleBasicMaterial = ParticleBasicMaterial;
  30461. exports.ParticleSystemMaterial = ParticleSystemMaterial;
  30462. exports.Vertex = Vertex;
  30463. exports.DynamicBufferAttribute = DynamicBufferAttribute;
  30464. exports.Int8Attribute = Int8Attribute;
  30465. exports.Uint8Attribute = Uint8Attribute;
  30466. exports.Uint8ClampedAttribute = Uint8ClampedAttribute;
  30467. exports.Int16Attribute = Int16Attribute;
  30468. exports.Uint16Attribute = Uint16Attribute;
  30469. exports.Int32Attribute = Int32Attribute;
  30470. exports.Uint32Attribute = Uint32Attribute;
  30471. exports.Float32Attribute = Float32Attribute;
  30472. exports.Float64Attribute = Float64Attribute;
  30473. exports.ClosedSplineCurve3 = ClosedSplineCurve3;
  30474. exports.BoundingBoxHelper = BoundingBoxHelper;
  30475. exports.EdgesHelper = EdgesHelper;
  30476. exports.WireframeHelper = WireframeHelper;
  30477. exports.XHRLoader = XHRLoader;
  30478. exports.GeometryUtils = GeometryUtils;
  30479. exports.ImageUtils = ImageUtils;
  30480. exports.Projector = Projector;
  30481. exports.CanvasRenderer = CanvasRenderer;
  30482. Object.defineProperty(exports, '__esModule', { value: true });
  30483. })));
  30484. },{}],43:[function(_dereq_,module,exports){
  30485. /**
  30486. * @author Michael Guerrero / http://realitymeltdown.com
  30487. */
  30488. THREE.BlendCharacter = function () {
  30489. this.weightSchedule = [];
  30490. this.warpSchedule = [];
  30491. this.load = function ( url, onLoad ) {
  30492. var scope = this;
  30493. var loader = new THREE.ObjectLoader();
  30494. loader.load( url, function( loadedObject ) {
  30495. // The exporter does not currently allow exporting a skinned mesh by itself
  30496. // so we must fish it out of the hierarchy it is embedded in (scene)
  30497. loadedObject.traverse( function( object ) {
  30498. if ( object instanceof THREE.SkinnedMesh ) {
  30499. scope.skinnedMesh = object;
  30500. }
  30501. } );
  30502. THREE.SkinnedMesh.call( scope, scope.skinnedMesh.geometry, scope.skinnedMesh.material );
  30503. // If we didn't successfully find the mesh, bail out
  30504. if ( scope.skinnedMesh == undefined ) {
  30505. console.log( 'unable to find skinned mesh in ' + url );
  30506. return;
  30507. }
  30508. scope.material.skinning = true;
  30509. scope.mixer = new THREE.AnimationMixer( scope );
  30510. // Create the animations
  30511. for ( var i = 0; i < scope.geometry.animations.length; ++ i ) {
  30512. scope.mixer.clipAction( scope.geometry.animations[ i ] );
  30513. }
  30514. // Loading is complete, fire the callback
  30515. if ( onLoad !== undefined ) onLoad();
  30516. } );
  30517. };
  30518. this.loadJSON = function ( url, onLoad ) {
  30519. var scope = this;
  30520. var loader = new THREE.JSONLoader();
  30521. loader.load( url, function( geometry, materials ) {
  30522. var originalMaterial = materials[ 0 ];
  30523. originalMaterial.skinning = true;
  30524. THREE.SkinnedMesh.call( scope, geometry, originalMaterial );
  30525. var mixer = new THREE.AnimationMixer( scope );
  30526. scope.mixer = mixer;
  30527. // Create the animations
  30528. for ( var i = 0; i < geometry.animations.length; ++ i ) {
  30529. mixer.clipAction( geometry.animations[ i ] );
  30530. }
  30531. // Loading is complete, fire the callback
  30532. if ( onLoad !== undefined ) onLoad();
  30533. } );
  30534. };
  30535. this.update = function( dt ) {
  30536. this.mixer.update( dt );
  30537. };
  30538. this.play = function( animName, weight ) {
  30539. //console.log("play('%s', %f)", animName, weight);
  30540. return this.mixer.clipAction( animName ).
  30541. setEffectiveWeight( weight ).play();
  30542. };
  30543. this.crossfade = function( fromAnimName, toAnimName, duration ) {
  30544. this.mixer.stopAllAction();
  30545. var fromAction = this.play( fromAnimName, 1 );
  30546. var toAction = this.play( toAnimName, 1 );
  30547. fromAction.crossFadeTo( toAction, duration, false );
  30548. };
  30549. this.warp = function( fromAnimName, toAnimName, duration ) {
  30550. this.mixer.stopAllAction();
  30551. var fromAction = this.play( fromAnimName, 1 );
  30552. var toAction = this.play( toAnimName, 1 );
  30553. fromAction.crossFadeTo( toAction, duration, true );
  30554. };
  30555. this.applyWeight = function( animName, weight ) {
  30556. this.mixer.clipAction( animName ).setEffectiveWeight( weight );
  30557. };
  30558. this.getWeight = function( animName ) {
  30559. return this.mixer.clipAction( animName ).getEffectiveWeight();
  30560. };
  30561. this.pauseAll = function() {
  30562. this.mixer.timeScale = 0;
  30563. };
  30564. this.unPauseAll = function() {
  30565. this.mixer.timeScale = 1;
  30566. };
  30567. this.stopAll = function() {
  30568. this.mixer.stopAllAction();
  30569. };
  30570. this.showModel = function( boolean ) {
  30571. this.visible = boolean;
  30572. };
  30573. };
  30574. THREE.BlendCharacter.prototype = Object.create( THREE.SkinnedMesh.prototype );
  30575. THREE.BlendCharacter.prototype.constructor = THREE.BlendCharacter;
  30576. THREE.BlendCharacter.prototype.getForward = function() {
  30577. var forward = new THREE.Vector3();
  30578. return function() {
  30579. // pull the character's forward basis vector out of the matrix
  30580. forward.set(
  30581. - this.matrix.elements[ 8 ],
  30582. - this.matrix.elements[ 9 ],
  30583. - this.matrix.elements[ 10 ]
  30584. );
  30585. return forward;
  30586. }
  30587. };
  30588. },{}],44:[function(_dereq_,module,exports){
  30589. /**
  30590. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  30591. * @author Tony Parisi / http://www.tonyparisi.com/
  30592. */
  30593. THREE.ColladaLoader = function () {
  30594. var COLLADA = null;
  30595. var scene = null;
  30596. var visualScene;
  30597. var kinematicsModel;
  30598. var readyCallbackFunc = null;
  30599. var sources = {};
  30600. var images = {};
  30601. var animations = {};
  30602. var controllers = {};
  30603. var geometries = {};
  30604. var materials = {};
  30605. var effects = {};
  30606. var cameras = {};
  30607. var lights = {};
  30608. var animData;
  30609. var kinematics;
  30610. var visualScenes;
  30611. var kinematicsModels;
  30612. var baseUrl;
  30613. var morphs;
  30614. var skins;
  30615. var flip_uv = true;
  30616. var preferredShading = THREE.SmoothShading;
  30617. var options = {
  30618. // Force Geometry to always be centered at the local origin of the
  30619. // containing Mesh.
  30620. centerGeometry: false,
  30621. // Axis conversion is done for geometries, animations, and controllers.
  30622. // If we ever pull cameras or lights out of the COLLADA file, they'll
  30623. // need extra work.
  30624. convertUpAxis: false,
  30625. subdivideFaces: true,
  30626. upAxis: 'Y',
  30627. // For reflective or refractive materials we'll use this cubemap
  30628. defaultEnvMap: null
  30629. };
  30630. var colladaUnit = 1.0;
  30631. var colladaUp = 'Y';
  30632. var upConversion = null;
  30633. function load ( url, readyCallback, progressCallback, failCallback ) {
  30634. var length = 0;
  30635. if ( document.implementation && document.implementation.createDocument ) {
  30636. var request = new XMLHttpRequest();
  30637. request.onreadystatechange = function() {
  30638. if ( request.readyState === 4 ) {
  30639. if ( request.status === 0 || request.status === 200 ) {
  30640. if ( request.response ) {
  30641. readyCallbackFunc = readyCallback;
  30642. parse( request.response, undefined, url );
  30643. } else {
  30644. if ( failCallback ) {
  30645. failCallback( { type: 'error', url: url } );
  30646. } else {
  30647. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  30648. }
  30649. }
  30650. }else{
  30651. if( failCallback ){
  30652. failCallback( { type: 'error', url: url } );
  30653. }else{
  30654. console.error( 'ColladaLoader: Couldn\'t load "' + url + '" (' + request.status + ')' );
  30655. }
  30656. }
  30657. } else if ( request.readyState === 3 ) {
  30658. if ( progressCallback ) {
  30659. if ( length === 0 ) {
  30660. length = request.getResponseHeader( "Content-Length" );
  30661. }
  30662. progressCallback( { total: length, loaded: request.responseText.length } );
  30663. }
  30664. }
  30665. };
  30666. request.open( "GET", url, true );
  30667. request.send( null );
  30668. } else {
  30669. alert( "Don't know how to parse XML!" );
  30670. }
  30671. }
  30672. function parse( text, callBack, url ) {
  30673. COLLADA = new DOMParser().parseFromString( text, 'text/xml' );
  30674. callBack = callBack || readyCallbackFunc;
  30675. if ( url !== undefined ) {
  30676. var parts = url.split( '/' );
  30677. parts.pop();
  30678. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  30679. }
  30680. parseAsset();
  30681. setUpConversion();
  30682. images = parseLib( "library_images image", _Image, "image" );
  30683. materials = parseLib( "library_materials material", Material, "material" );
  30684. effects = parseLib( "library_effects effect", Effect, "effect" );
  30685. geometries = parseLib( "library_geometries geometry", Geometry, "geometry" );
  30686. cameras = parseLib( "library_cameras camera", Camera, "camera" );
  30687. lights = parseLib( "library_lights light", Light, "light" );
  30688. controllers = parseLib( "library_controllers controller", Controller, "controller" );
  30689. animations = parseLib( "library_animations animation", Animation, "animation" );
  30690. visualScenes = parseLib( "library_visual_scenes visual_scene", VisualScene, "visual_scene" );
  30691. kinematicsModels = parseLib( "library_kinematics_models kinematics_model", KinematicsModel, "kinematics_model" );
  30692. morphs = [];
  30693. skins = [];
  30694. visualScene = parseScene();
  30695. scene = new THREE.Group();
  30696. for ( var i = 0; i < visualScene.nodes.length; i ++ ) {
  30697. scene.add( createSceneGraph( visualScene.nodes[ i ] ) );
  30698. }
  30699. // unit conversion
  30700. scene.scale.multiplyScalar( colladaUnit );
  30701. createAnimations();
  30702. kinematicsModel = parseKinematicsModel();
  30703. createKinematics();
  30704. var result = {
  30705. scene: scene,
  30706. morphs: morphs,
  30707. skins: skins,
  30708. animations: animData,
  30709. kinematics: kinematics,
  30710. dae: {
  30711. images: images,
  30712. materials: materials,
  30713. cameras: cameras,
  30714. lights: lights,
  30715. effects: effects,
  30716. geometries: geometries,
  30717. controllers: controllers,
  30718. animations: animations,
  30719. visualScenes: visualScenes,
  30720. visualScene: visualScene,
  30721. scene: visualScene,
  30722. kinematicsModels: kinematicsModels,
  30723. kinematicsModel: kinematicsModel
  30724. }
  30725. };
  30726. if ( callBack ) {
  30727. callBack( result );
  30728. }
  30729. return result;
  30730. }
  30731. function setPreferredShading ( shading ) {
  30732. preferredShading = shading;
  30733. }
  30734. function parseAsset () {
  30735. var elements = COLLADA.querySelectorAll('asset');
  30736. var element = elements[0];
  30737. if ( element && element.childNodes ) {
  30738. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  30739. var child = element.childNodes[ i ];
  30740. switch ( child.nodeName ) {
  30741. case 'unit':
  30742. var meter = child.getAttribute( 'meter' );
  30743. if ( meter ) {
  30744. colladaUnit = parseFloat( meter );
  30745. }
  30746. break;
  30747. case 'up_axis':
  30748. colladaUp = child.textContent.charAt(0);
  30749. break;
  30750. }
  30751. }
  30752. }
  30753. }
  30754. function parseLib ( q, classSpec, prefix ) {
  30755. var elements = COLLADA.querySelectorAll(q);
  30756. var lib = {};
  30757. var i = 0;
  30758. var elementsLength = elements.length;
  30759. for ( var j = 0; j < elementsLength; j ++ ) {
  30760. var element = elements[j];
  30761. var daeElement = ( new classSpec() ).parse( element );
  30762. if ( !daeElement.id || daeElement.id.length === 0 ) daeElement.id = prefix + ( i ++ );
  30763. lib[ daeElement.id ] = daeElement;
  30764. }
  30765. return lib;
  30766. }
  30767. function parseScene() {
  30768. var sceneElement = COLLADA.querySelectorAll('scene instance_visual_scene')[0];
  30769. if ( sceneElement ) {
  30770. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  30771. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  30772. } else {
  30773. return null;
  30774. }
  30775. }
  30776. function parseKinematicsModel() {
  30777. var kinematicsModelElement = COLLADA.querySelectorAll('instance_kinematics_model')[0];
  30778. if ( kinematicsModelElement ) {
  30779. var url = kinematicsModelElement.getAttribute( 'url' ).replace(/^#/, '');
  30780. return kinematicsModels[ url.length > 0 ? url : 'kinematics_model0' ];
  30781. } else {
  30782. return null;
  30783. }
  30784. }
  30785. function createAnimations() {
  30786. animData = [];
  30787. // fill in the keys
  30788. recurseHierarchy( scene );
  30789. }
  30790. function recurseHierarchy( node ) {
  30791. var n = visualScene.getChildById( node.colladaId, true ),
  30792. newData = null;
  30793. if ( n && n.keys ) {
  30794. newData = {
  30795. fps: 60,
  30796. hierarchy: [ {
  30797. node: n,
  30798. keys: n.keys,
  30799. sids: n.sids
  30800. } ],
  30801. node: node,
  30802. name: 'animation_' + node.name,
  30803. length: 0
  30804. };
  30805. animData.push(newData);
  30806. for ( var i = 0, il = n.keys.length; i < il; i ++ ) {
  30807. newData.length = Math.max( newData.length, n.keys[i].time );
  30808. }
  30809. } else {
  30810. newData = {
  30811. hierarchy: [ {
  30812. keys: [],
  30813. sids: []
  30814. } ]
  30815. }
  30816. }
  30817. for ( var i = 0, il = node.children.length; i < il; i ++ ) {
  30818. var d = recurseHierarchy( node.children[i] );
  30819. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  30820. newData.hierarchy.push( {
  30821. keys: [],
  30822. sids: []
  30823. } );
  30824. }
  30825. }
  30826. return newData;
  30827. }
  30828. function calcAnimationBounds () {
  30829. var start = 1000000;
  30830. var end = -start;
  30831. var frames = 0;
  30832. var ID;
  30833. for ( var id in animations ) {
  30834. var animation = animations[ id ];
  30835. ID = ID || animation.id;
  30836. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  30837. var sampler = animation.sampler[ i ];
  30838. sampler.create();
  30839. start = Math.min( start, sampler.startTime );
  30840. end = Math.max( end, sampler.endTime );
  30841. frames = Math.max( frames, sampler.input.length );
  30842. }
  30843. }
  30844. return { start:start, end:end, frames:frames,ID:ID };
  30845. }
  30846. function createMorph ( geometry, ctrl ) {
  30847. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  30848. if ( !morphCtrl || !morphCtrl.morph ) {
  30849. console.log("could not find morph controller!");
  30850. return;
  30851. }
  30852. var morph = morphCtrl.morph;
  30853. for ( var i = 0; i < morph.targets.length; i ++ ) {
  30854. var target_id = morph.targets[ i ];
  30855. var daeGeometry = geometries[ target_id ];
  30856. if ( !daeGeometry.mesh ||
  30857. !daeGeometry.mesh.primitives ||
  30858. !daeGeometry.mesh.primitives.length ) {
  30859. continue;
  30860. }
  30861. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  30862. if ( target.vertices.length === geometry.vertices.length ) {
  30863. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  30864. }
  30865. }
  30866. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  30867. }
  30868. function createSkin ( geometry, ctrl, applyBindShape ) {
  30869. var skinCtrl = controllers[ ctrl.url ];
  30870. if ( !skinCtrl || !skinCtrl.skin ) {
  30871. console.log( "could not find skin controller!" );
  30872. return;
  30873. }
  30874. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  30875. console.log( "could not find the skeleton for the skin!" );
  30876. return;
  30877. }
  30878. var skin = skinCtrl.skin;
  30879. var skeleton = visualScene.getChildById( ctrl.skeleton[ 0 ] );
  30880. var hierarchy = [];
  30881. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  30882. var bones = [];
  30883. geometry.skinWeights = [];
  30884. geometry.skinIndices = [];
  30885. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  30886. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  30887. /*
  30888. geometry.animation = {
  30889. name: 'take_001',
  30890. fps: 30,
  30891. length: 2,
  30892. JIT: true,
  30893. hierarchy: hierarchy
  30894. };
  30895. */
  30896. if ( applyBindShape ) {
  30897. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  30898. geometry.vertices[ i ].applyMatrix4( skin.bindShapeMatrix );
  30899. }
  30900. }
  30901. }
  30902. function setupSkeleton ( node, bones, frame, parent ) {
  30903. node.world = node.world || new THREE.Matrix4();
  30904. node.localworld = node.localworld || new THREE.Matrix4();
  30905. node.world.copy( node.matrix );
  30906. node.localworld.copy( node.matrix );
  30907. if ( node.channels && node.channels.length ) {
  30908. var channel = node.channels[ 0 ];
  30909. var m = channel.sampler.output[ frame ];
  30910. if ( m instanceof THREE.Matrix4 ) {
  30911. node.world.copy( m );
  30912. node.localworld.copy(m);
  30913. if (frame === 0)
  30914. node.matrix.copy(m);
  30915. }
  30916. }
  30917. if ( parent ) {
  30918. node.world.multiplyMatrices( parent, node.world );
  30919. }
  30920. bones.push( node );
  30921. for ( var i = 0; i < node.nodes.length; i ++ ) {
  30922. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  30923. }
  30924. }
  30925. function setupSkinningMatrices ( bones, skin ) {
  30926. // FIXME: this is dumb...
  30927. for ( var i = 0; i < bones.length; i ++ ) {
  30928. var bone = bones[ i ];
  30929. var found = -1;
  30930. if ( bone.type != 'JOINT' ) continue;
  30931. for ( var j = 0; j < skin.joints.length; j ++ ) {
  30932. if ( bone.sid === skin.joints[ j ] ) {
  30933. found = j;
  30934. break;
  30935. }
  30936. }
  30937. if ( found >= 0 ) {
  30938. var inv = skin.invBindMatrices[ found ];
  30939. bone.invBindMatrix = inv;
  30940. bone.skinningMatrix = new THREE.Matrix4();
  30941. bone.skinningMatrix.multiplyMatrices(bone.world, inv); // (IBMi * JMi)
  30942. bone.animatrix = new THREE.Matrix4();
  30943. bone.animatrix.copy(bone.localworld);
  30944. bone.weights = [];
  30945. for ( var j = 0; j < skin.weights.length; j ++ ) {
  30946. for (var k = 0; k < skin.weights[ j ].length; k ++ ) {
  30947. var w = skin.weights[ j ][ k ];
  30948. if ( w.joint === found ) {
  30949. bone.weights.push( w );
  30950. }
  30951. }
  30952. }
  30953. } else {
  30954. console.warn( "ColladaLoader: Could not find joint '" + bone.sid + "'." );
  30955. bone.skinningMatrix = new THREE.Matrix4();
  30956. bone.weights = [];
  30957. }
  30958. }
  30959. }
  30960. //Walk the Collada tree and flatten the bones into a list, extract the position, quat and scale from the matrix
  30961. function flattenSkeleton(skeleton) {
  30962. var list = [];
  30963. var walk = function(parentid, node, list) {
  30964. var bone = {};
  30965. bone.name = node.sid;
  30966. bone.parent = parentid;
  30967. bone.matrix = node.matrix;
  30968. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  30969. bone.matrix.decompose(data[0], data[1], data[2]);
  30970. bone.pos = [ data[0].x,data[0].y,data[0].z ];
  30971. bone.scl = [ data[2].x,data[2].y,data[2].z ];
  30972. bone.rotq = [ data[1].x,data[1].y,data[1].z,data[1].w ];
  30973. list.push(bone);
  30974. for (var i in node.nodes) {
  30975. walk(node.sid, node.nodes[i], list);
  30976. }
  30977. };
  30978. walk(-1, skeleton, list);
  30979. return list;
  30980. }
  30981. //Move the vertices into the pose that is proper for the start of the animation
  30982. function skinToBindPose(geometry,skeleton,skinController) {
  30983. var bones = [];
  30984. setupSkeleton( skeleton, bones, -1 );
  30985. setupSkinningMatrices( bones, skinController.skin );
  30986. var v = new THREE.Vector3();
  30987. var skinned = [];
  30988. for (var i = 0; i < geometry.vertices.length; i ++) {
  30989. skinned.push(new THREE.Vector3());
  30990. }
  30991. for ( i = 0; i < bones.length; i ++ ) {
  30992. if ( bones[ i ].type != 'JOINT' ) continue;
  30993. for ( var j = 0; j < bones[ i ].weights.length; j ++ ) {
  30994. var w = bones[ i ].weights[ j ];
  30995. var vidx = w.index;
  30996. var weight = w.weight;
  30997. var o = geometry.vertices[vidx];
  30998. var s = skinned[vidx];
  30999. v.x = o.x;
  31000. v.y = o.y;
  31001. v.z = o.z;
  31002. v.applyMatrix4( bones[i].skinningMatrix );
  31003. s.x += (v.x * weight);
  31004. s.y += (v.y * weight);
  31005. s.z += (v.z * weight);
  31006. }
  31007. }
  31008. for (var i = 0; i < geometry.vertices.length; i ++) {
  31009. geometry.vertices[i] = skinned[i];
  31010. }
  31011. }
  31012. function applySkin ( geometry, instanceCtrl, frame ) {
  31013. var skinController = controllers[ instanceCtrl.url ];
  31014. frame = frame !== undefined ? frame : 40;
  31015. if ( !skinController || !skinController.skin ) {
  31016. console.log( 'ColladaLoader: Could not find skin controller.' );
  31017. return;
  31018. }
  31019. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  31020. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  31021. return;
  31022. }
  31023. var animationBounds = calcAnimationBounds();
  31024. var skeleton = visualScene.getChildById( instanceCtrl.skeleton[0], true ) || visualScene.getChildBySid( instanceCtrl.skeleton[0], true );
  31025. //flatten the skeleton into a list of bones
  31026. var bonelist = flattenSkeleton(skeleton);
  31027. var joints = skinController.skin.joints;
  31028. //sort that list so that the order reflects the order in the joint list
  31029. var sortedbones = [];
  31030. for (var i = 0; i < joints.length; i ++) {
  31031. for (var j = 0; j < bonelist.length; j ++) {
  31032. if (bonelist[j].name === joints[i]) {
  31033. sortedbones[i] = bonelist[j];
  31034. }
  31035. }
  31036. }
  31037. //hook up the parents by index instead of name
  31038. for (var i = 0; i < sortedbones.length; i ++) {
  31039. for (var j = 0; j < sortedbones.length; j ++) {
  31040. if (sortedbones[i].parent === sortedbones[j].name) {
  31041. sortedbones[i].parent = j;
  31042. }
  31043. }
  31044. }
  31045. var i, j, w, vidx, weight;
  31046. var v = new THREE.Vector3(), o, s;
  31047. // move vertices to bind shape
  31048. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  31049. geometry.vertices[i].applyMatrix4( skinController.skin.bindShapeMatrix );
  31050. }
  31051. var skinIndices = [];
  31052. var skinWeights = [];
  31053. var weights = skinController.skin.weights;
  31054. // hook up the skin weights
  31055. // TODO - this might be a good place to choose greatest 4 weights
  31056. for ( var i =0; i < weights.length; i ++ ) {
  31057. var indicies = new THREE.Vector4(weights[i][0] ? weights[i][0].joint : 0,weights[i][1] ? weights[i][1].joint : 0,weights[i][2] ? weights[i][2].joint : 0,weights[i][3] ? weights[i][3].joint : 0);
  31058. var weight = new THREE.Vector4(weights[i][0] ? weights[i][0].weight : 0,weights[i][1] ? weights[i][1].weight : 0,weights[i][2] ? weights[i][2].weight : 0,weights[i][3] ? weights[i][3].weight : 0);
  31059. skinIndices.push(indicies);
  31060. skinWeights.push(weight);
  31061. }
  31062. geometry.skinIndices = skinIndices;
  31063. geometry.skinWeights = skinWeights;
  31064. geometry.bones = sortedbones;
  31065. // process animation, or simply pose the rig if no animation
  31066. //create an animation for the animated bones
  31067. //NOTE: this has no effect when using morphtargets
  31068. var animationdata = { "name":animationBounds.ID,"fps":30,"length":animationBounds.frames / 30,"hierarchy":[] };
  31069. for (var j = 0; j < sortedbones.length; j ++) {
  31070. animationdata.hierarchy.push({ parent:sortedbones[j].parent, name:sortedbones[j].name, keys:[] });
  31071. }
  31072. console.log( 'ColladaLoader:', animationBounds.ID + ' has ' + sortedbones.length + ' bones.' );
  31073. skinToBindPose(geometry, skeleton, skinController);
  31074. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  31075. var bones = [];
  31076. var skinned = [];
  31077. // process the frame and setup the rig with a fresh
  31078. // transform, possibly from the bone's animation channel(s)
  31079. setupSkeleton( skeleton, bones, frame );
  31080. setupSkinningMatrices( bones, skinController.skin );
  31081. for (var i = 0; i < bones.length; i ++) {
  31082. for (var j = 0; j < animationdata.hierarchy.length; j ++) {
  31083. if (animationdata.hierarchy[j].name === bones[i].sid) {
  31084. var key = {};
  31085. key.time = (frame / 30);
  31086. key.matrix = bones[i].animatrix;
  31087. if (frame === 0)
  31088. bones[i].matrix = key.matrix;
  31089. var data = [ new THREE.Vector3(),new THREE.Quaternion(),new THREE.Vector3() ];
  31090. key.matrix.decompose(data[0], data[1], data[2]);
  31091. key.pos = [ data[0].x,data[0].y,data[0].z ];
  31092. key.scl = [ data[2].x,data[2].y,data[2].z ];
  31093. key.rot = data[1];
  31094. animationdata.hierarchy[j].keys.push(key);
  31095. }
  31096. }
  31097. }
  31098. geometry.animation = animationdata;
  31099. }
  31100. }
  31101. function createKinematics() {
  31102. if ( kinematicsModel && kinematicsModel.joints.length === 0 ) {
  31103. kinematics = undefined;
  31104. return;
  31105. }
  31106. var jointMap = {};
  31107. var _addToMap = function( jointIndex, parentVisualElement ) {
  31108. var parentVisualElementId = parentVisualElement.getAttribute( 'id' );
  31109. var colladaNode = visualScene.getChildById( parentVisualElementId, true );
  31110. var joint = kinematicsModel.joints[ jointIndex ];
  31111. scene.traverse(function( node ) {
  31112. if ( node.colladaId == parentVisualElementId ) {
  31113. jointMap[ jointIndex ] = {
  31114. node: node,
  31115. transforms: colladaNode.transforms,
  31116. joint: joint,
  31117. position: joint.zeroPosition
  31118. };
  31119. }
  31120. });
  31121. };
  31122. kinematics = {
  31123. joints: kinematicsModel && kinematicsModel.joints,
  31124. getJointValue: function( jointIndex ) {
  31125. var jointData = jointMap[ jointIndex ];
  31126. if ( jointData ) {
  31127. return jointData.position;
  31128. } else {
  31129. console.log( 'getJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31130. }
  31131. },
  31132. setJointValue: function( jointIndex, value ) {
  31133. var jointData = jointMap[ jointIndex ];
  31134. if ( jointData ) {
  31135. var joint = jointData.joint;
  31136. if ( value > joint.limits.max || value < joint.limits.min ) {
  31137. console.log( 'setJointValue: joint ' + jointIndex + ' value ' + value + ' outside of limits (min: ' + joint.limits.min + ', max: ' + joint.limits.max + ')' );
  31138. } else if ( joint.static ) {
  31139. console.log( 'setJointValue: joint ' + jointIndex + ' is static' );
  31140. } else {
  31141. var threejsNode = jointData.node;
  31142. var axis = joint.axis;
  31143. var transforms = jointData.transforms;
  31144. var matrix = new THREE.Matrix4();
  31145. for (i = 0; i < transforms.length; i ++ ) {
  31146. var transform = transforms[ i ];
  31147. // kinda ghetto joint detection
  31148. if ( transform.sid && transform.sid.indexOf( 'joint' + jointIndex ) !== -1 ) {
  31149. // apply actual joint value here
  31150. switch ( joint.type ) {
  31151. case 'revolute':
  31152. matrix.multiply( m1.makeRotationAxis( axis, THREE.Math.degToRad(value) ) );
  31153. break;
  31154. case 'prismatic':
  31155. matrix.multiply( m1.makeTranslation(axis.x * value, axis.y * value, axis.z * value ) );
  31156. break;
  31157. default:
  31158. console.warn( 'setJointValue: unknown joint type: ' + joint.type );
  31159. break;
  31160. }
  31161. } else {
  31162. var m1 = new THREE.Matrix4();
  31163. switch ( transform.type ) {
  31164. case 'matrix':
  31165. matrix.multiply( transform.obj );
  31166. break;
  31167. case 'translate':
  31168. matrix.multiply( m1.makeTranslation( transform.obj.x, transform.obj.y, transform.obj.z ) );
  31169. break;
  31170. case 'rotate':
  31171. matrix.multiply( m1.makeRotationAxis( transform.obj, transform.angle ) );
  31172. break;
  31173. }
  31174. }
  31175. }
  31176. // apply the matrix to the threejs node
  31177. var elementsFloat32Arr = matrix.elements;
  31178. var elements = Array.prototype.slice.call( elementsFloat32Arr );
  31179. var elementsRowMajor = [
  31180. elements[ 0 ],
  31181. elements[ 4 ],
  31182. elements[ 8 ],
  31183. elements[ 12 ],
  31184. elements[ 1 ],
  31185. elements[ 5 ],
  31186. elements[ 9 ],
  31187. elements[ 13 ],
  31188. elements[ 2 ],
  31189. elements[ 6 ],
  31190. elements[ 10 ],
  31191. elements[ 14 ],
  31192. elements[ 3 ],
  31193. elements[ 7 ],
  31194. elements[ 11 ],
  31195. elements[ 15 ]
  31196. ];
  31197. threejsNode.matrix.set.apply( threejsNode.matrix, elementsRowMajor );
  31198. threejsNode.matrix.decompose( threejsNode.position, threejsNode.quaternion, threejsNode.scale );
  31199. }
  31200. } else {
  31201. console.log( 'setJointValue: joint ' + jointIndex + ' doesn\'t exist' );
  31202. }
  31203. }
  31204. };
  31205. var element = COLLADA.querySelector('scene instance_kinematics_scene');
  31206. if ( element ) {
  31207. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31208. var child = element.childNodes[ i ];
  31209. if ( child.nodeType != 1 ) continue;
  31210. switch ( child.nodeName ) {
  31211. case 'bind_joint_axis':
  31212. var visualTarget = child.getAttribute( 'target' ).split( '/' ).pop();
  31213. var axis = child.querySelector('axis param').textContent;
  31214. var jointIndex = parseInt( axis.split( 'joint' ).pop().split( '.' )[0] );
  31215. var visualTargetElement = COLLADA.querySelector( '[sid="' + visualTarget + '"]' );
  31216. if ( visualTargetElement ) {
  31217. var parentVisualElement = visualTargetElement.parentElement;
  31218. _addToMap(jointIndex, parentVisualElement);
  31219. }
  31220. break;
  31221. default:
  31222. break;
  31223. }
  31224. }
  31225. }
  31226. }
  31227. function createSceneGraph ( node, parent ) {
  31228. var obj = new THREE.Object3D();
  31229. var skinned = false;
  31230. var skinController;
  31231. var morphController;
  31232. var i, j;
  31233. // FIXME: controllers
  31234. for ( i = 0; i < node.controllers.length; i ++ ) {
  31235. var controller = controllers[ node.controllers[ i ].url ];
  31236. switch ( controller.type ) {
  31237. case 'skin':
  31238. if ( geometries[ controller.skin.source ] ) {
  31239. var inst_geom = new InstanceGeometry();
  31240. inst_geom.url = controller.skin.source;
  31241. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31242. node.geometries.push( inst_geom );
  31243. skinned = true;
  31244. skinController = node.controllers[ i ];
  31245. } else if ( controllers[ controller.skin.source ] ) {
  31246. // urgh: controller can be chained
  31247. // handle the most basic case...
  31248. var second = controllers[ controller.skin.source ];
  31249. morphController = second;
  31250. // skinController = node.controllers[i];
  31251. if ( second.morph && geometries[ second.morph.source ] ) {
  31252. var inst_geom = new InstanceGeometry();
  31253. inst_geom.url = second.morph.source;
  31254. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31255. node.geometries.push( inst_geom );
  31256. }
  31257. }
  31258. break;
  31259. case 'morph':
  31260. if ( geometries[ controller.morph.source ] ) {
  31261. var inst_geom = new InstanceGeometry();
  31262. inst_geom.url = controller.morph.source;
  31263. inst_geom.instance_material = node.controllers[ i ].instance_material;
  31264. node.geometries.push( inst_geom );
  31265. morphController = node.controllers[ i ];
  31266. }
  31267. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  31268. default:
  31269. break;
  31270. }
  31271. }
  31272. // geometries
  31273. var double_sided_materials = {};
  31274. for ( i = 0; i < node.geometries.length; i ++ ) {
  31275. var instance_geometry = node.geometries[i];
  31276. var instance_materials = instance_geometry.instance_material;
  31277. var geometry = geometries[ instance_geometry.url ];
  31278. var used_materials = {};
  31279. var used_materials_array = [];
  31280. var num_materials = 0;
  31281. var first_material;
  31282. if ( geometry ) {
  31283. if ( !geometry.mesh || !geometry.mesh.primitives )
  31284. continue;
  31285. if ( obj.name.length === 0 ) {
  31286. obj.name = geometry.id;
  31287. }
  31288. // collect used fx for this geometry-instance
  31289. if ( instance_materials ) {
  31290. for ( j = 0; j < instance_materials.length; j ++ ) {
  31291. var instance_material = instance_materials[ j ];
  31292. var mat = materials[ instance_material.target ];
  31293. var effect_id = mat.instance_effect.url;
  31294. var shader = effects[ effect_id ].shader;
  31295. var material3js = shader.material;
  31296. if ( geometry.doubleSided ) {
  31297. if ( !( instance_material.symbol in double_sided_materials ) ) {
  31298. var _copied_material = material3js.clone();
  31299. _copied_material.side = THREE.DoubleSide;
  31300. double_sided_materials[ instance_material.symbol ] = _copied_material;
  31301. }
  31302. material3js = double_sided_materials[ instance_material.symbol ];
  31303. }
  31304. material3js.opacity = !material3js.opacity ? 1 : material3js.opacity;
  31305. used_materials[ instance_material.symbol ] = num_materials;
  31306. used_materials_array.push( material3js );
  31307. first_material = material3js;
  31308. first_material.name = mat.name === null || mat.name === '' ? mat.id : mat.name;
  31309. num_materials ++;
  31310. }
  31311. }
  31312. var mesh;
  31313. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, side: geometry.doubleSided ? THREE.DoubleSide : THREE.FrontSide } );
  31314. var geom = geometry.mesh.geometry3js;
  31315. if ( num_materials > 1 ) {
  31316. material = new THREE.MultiMaterial( used_materials_array );
  31317. for ( j = 0; j < geom.faces.length; j ++ ) {
  31318. var face = geom.faces[ j ];
  31319. face.materialIndex = used_materials[ face.daeMaterial ]
  31320. }
  31321. }
  31322. if ( skinController !== undefined ) {
  31323. applySkin( geom, skinController );
  31324. if ( geom.morphTargets.length > 0 ) {
  31325. material.morphTargets = true;
  31326. material.skinning = false;
  31327. } else {
  31328. material.morphTargets = false;
  31329. material.skinning = true;
  31330. }
  31331. mesh = new THREE.SkinnedMesh( geom, material, false );
  31332. //mesh.skeleton = skinController.skeleton;
  31333. //mesh.skinController = controllers[ skinController.url ];
  31334. //mesh.skinInstanceController = skinController;
  31335. mesh.name = 'skin_' + skins.length;
  31336. //mesh.animationHandle.setKey(0);
  31337. skins.push( mesh );
  31338. } else if ( morphController !== undefined ) {
  31339. createMorph( geom, morphController );
  31340. material.morphTargets = true;
  31341. mesh = new THREE.Mesh( geom, material );
  31342. mesh.name = 'morph_' + morphs.length;
  31343. morphs.push( mesh );
  31344. } else {
  31345. if ( geom.isLineStrip === true ) {
  31346. mesh = new THREE.Line( geom );
  31347. } else {
  31348. mesh = new THREE.Mesh( geom, material );
  31349. }
  31350. }
  31351. obj.add(mesh);
  31352. }
  31353. }
  31354. for ( i = 0; i < node.cameras.length; i ++ ) {
  31355. var instance_camera = node.cameras[i];
  31356. var cparams = cameras[instance_camera.url];
  31357. var cam = new THREE.PerspectiveCamera(cparams.yfov, parseFloat(cparams.aspect_ratio),
  31358. parseFloat(cparams.znear), parseFloat(cparams.zfar));
  31359. obj.add(cam);
  31360. }
  31361. for ( i = 0; i < node.lights.length; i ++ ) {
  31362. var light = null;
  31363. var instance_light = node.lights[i];
  31364. var lparams = lights[instance_light.url];
  31365. if ( lparams && lparams.technique ) {
  31366. var color = lparams.color.getHex();
  31367. var intensity = lparams.intensity;
  31368. var distance = lparams.distance;
  31369. var angle = lparams.falloff_angle;
  31370. switch ( lparams.technique ) {
  31371. case 'directional':
  31372. light = new THREE.DirectionalLight( color, intensity, distance );
  31373. light.position.set(0, 0, 1);
  31374. break;
  31375. case 'point':
  31376. light = new THREE.PointLight( color, intensity, distance );
  31377. break;
  31378. case 'spot':
  31379. light = new THREE.SpotLight( color, intensity, distance, angle );
  31380. light.position.set(0, 0, 1);
  31381. break;
  31382. case 'ambient':
  31383. light = new THREE.AmbientLight( color );
  31384. break;
  31385. }
  31386. }
  31387. if (light) {
  31388. obj.add(light);
  31389. }
  31390. }
  31391. obj.name = node.name || node.id || "";
  31392. obj.colladaId = node.id || "";
  31393. obj.layer = node.layer || "";
  31394. obj.matrix = node.matrix;
  31395. obj.matrix.decompose( obj.position, obj.quaternion, obj.scale );
  31396. if ( options.centerGeometry && obj.geometry ) {
  31397. var delta = obj.geometry.center();
  31398. delta.multiply( obj.scale );
  31399. delta.applyQuaternion( obj.quaternion );
  31400. obj.position.sub( delta );
  31401. }
  31402. for ( i = 0; i < node.nodes.length; i ++ ) {
  31403. obj.add( createSceneGraph( node.nodes[i], node ) );
  31404. }
  31405. return obj;
  31406. }
  31407. function getJointId( skin, id ) {
  31408. for ( var i = 0; i < skin.joints.length; i ++ ) {
  31409. if ( skin.joints[ i ] === id ) {
  31410. return i;
  31411. }
  31412. }
  31413. }
  31414. function getLibraryNode( id ) {
  31415. var nodes = COLLADA.querySelectorAll('library_nodes node');
  31416. for ( var i = 0; i < nodes.length; i++ ) {
  31417. var attObj = nodes[i].attributes.getNamedItem('id');
  31418. if ( attObj && attObj.value === id ) {
  31419. return nodes[i];
  31420. }
  31421. }
  31422. return undefined;
  31423. }
  31424. function getChannelsForNode ( node ) {
  31425. var channels = [];
  31426. var startTime = 1000000;
  31427. var endTime = -1000000;
  31428. for ( var id in animations ) {
  31429. var animation = animations[id];
  31430. for ( var i = 0; i < animation.channel.length; i ++ ) {
  31431. var channel = animation.channel[i];
  31432. var sampler = animation.sampler[i];
  31433. var id = channel.target.split('/')[0];
  31434. if ( id == node.id ) {
  31435. sampler.create();
  31436. channel.sampler = sampler;
  31437. startTime = Math.min(startTime, sampler.startTime);
  31438. endTime = Math.max(endTime, sampler.endTime);
  31439. channels.push(channel);
  31440. }
  31441. }
  31442. }
  31443. if ( channels.length ) {
  31444. node.startTime = startTime;
  31445. node.endTime = endTime;
  31446. }
  31447. return channels;
  31448. }
  31449. function calcFrameDuration( node ) {
  31450. var minT = 10000000;
  31451. for ( var i = 0; i < node.channels.length; i ++ ) {
  31452. var sampler = node.channels[i].sampler;
  31453. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  31454. var t0 = sampler.input[ j ];
  31455. var t1 = sampler.input[ j + 1 ];
  31456. minT = Math.min( minT, t1 - t0 );
  31457. }
  31458. }
  31459. return minT;
  31460. }
  31461. function calcMatrixAt( node, t ) {
  31462. var animated = {};
  31463. var i, j;
  31464. for ( i = 0; i < node.channels.length; i ++ ) {
  31465. var channel = node.channels[ i ];
  31466. animated[ channel.sid ] = channel;
  31467. }
  31468. var matrix = new THREE.Matrix4();
  31469. for ( i = 0; i < node.transforms.length; i ++ ) {
  31470. var transform = node.transforms[ i ];
  31471. var channel = animated[ transform.sid ];
  31472. if ( channel !== undefined ) {
  31473. var sampler = channel.sampler;
  31474. var value;
  31475. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  31476. if ( sampler.input[ j + 1 ] > t ) {
  31477. value = sampler.output[ j ];
  31478. //console.log(value.flatten)
  31479. break;
  31480. }
  31481. }
  31482. if ( value !== undefined ) {
  31483. if ( value instanceof THREE.Matrix4 ) {
  31484. matrix.multiplyMatrices( matrix, value );
  31485. } else {
  31486. // FIXME: handle other types
  31487. matrix.multiplyMatrices( matrix, transform.matrix );
  31488. }
  31489. } else {
  31490. matrix.multiplyMatrices( matrix, transform.matrix );
  31491. }
  31492. } else {
  31493. matrix.multiplyMatrices( matrix, transform.matrix );
  31494. }
  31495. }
  31496. return matrix;
  31497. }
  31498. function bakeAnimations ( node ) {
  31499. if ( node.channels && node.channels.length ) {
  31500. var keys = [],
  31501. sids = [];
  31502. for ( var i = 0, il = node.channels.length; i < il; i ++ ) {
  31503. var channel = node.channels[i],
  31504. fullSid = channel.fullSid,
  31505. sampler = channel.sampler,
  31506. input = sampler.input,
  31507. transform = node.getTransformBySid( channel.sid ),
  31508. member;
  31509. if ( channel.arrIndices ) {
  31510. member = [];
  31511. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j ++ ) {
  31512. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  31513. }
  31514. } else {
  31515. member = getConvertedMember( channel.member );
  31516. }
  31517. if ( transform ) {
  31518. if ( sids.indexOf( fullSid ) === -1 ) {
  31519. sids.push( fullSid );
  31520. }
  31521. for ( var j = 0, jl = input.length; j < jl; j ++ ) {
  31522. var time = input[j],
  31523. data = sampler.getData( transform.type, j, member ),
  31524. key = findKey( keys, time );
  31525. if ( !key ) {
  31526. key = new Key( time );
  31527. var timeNdx = findTimeNdx( keys, time );
  31528. keys.splice( timeNdx === -1 ? keys.length : timeNdx, 0, key );
  31529. }
  31530. key.addTarget( fullSid, transform, member, data );
  31531. }
  31532. } else {
  31533. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  31534. }
  31535. }
  31536. // post process
  31537. for ( var i = 0; i < sids.length; i ++ ) {
  31538. var sid = sids[ i ];
  31539. for ( var j = 0; j < keys.length; j ++ ) {
  31540. var key = keys[ j ];
  31541. if ( !key.hasTarget( sid ) ) {
  31542. interpolateKeys( keys, key, j, sid );
  31543. }
  31544. }
  31545. }
  31546. node.keys = keys;
  31547. node.sids = sids;
  31548. }
  31549. }
  31550. function findKey ( keys, time) {
  31551. var retVal = null;
  31552. for ( var i = 0, il = keys.length; i < il && retVal === null; i ++ ) {
  31553. var key = keys[i];
  31554. if ( key.time === time ) {
  31555. retVal = key;
  31556. } else if ( key.time > time ) {
  31557. break;
  31558. }
  31559. }
  31560. return retVal;
  31561. }
  31562. function findTimeNdx ( keys, time) {
  31563. var ndx = -1;
  31564. for ( var i = 0, il = keys.length; i < il && ndx === -1; i ++ ) {
  31565. var key = keys[i];
  31566. if ( key.time >= time ) {
  31567. ndx = i;
  31568. }
  31569. }
  31570. return ndx;
  31571. }
  31572. function interpolateKeys ( keys, key, ndx, fullSid ) {
  31573. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx - 1 : 0 ),
  31574. nextKey = getNextKeyWith( keys, fullSid, ndx + 1 );
  31575. if ( prevKey && nextKey ) {
  31576. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  31577. prevTarget = prevKey.getTarget( fullSid ),
  31578. nextData = nextKey.getTarget( fullSid ).data,
  31579. prevData = prevTarget.data,
  31580. data;
  31581. if ( prevTarget.type === 'matrix' ) {
  31582. data = prevData;
  31583. } else if ( prevData.length ) {
  31584. data = [];
  31585. for ( var i = 0; i < prevData.length; ++ i ) {
  31586. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  31587. }
  31588. } else {
  31589. data = prevData + ( nextData - prevData ) * scale;
  31590. }
  31591. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  31592. }
  31593. }
  31594. // Get next key with given sid
  31595. function getNextKeyWith( keys, fullSid, ndx ) {
  31596. for ( ; ndx < keys.length; ndx ++ ) {
  31597. var key = keys[ ndx ];
  31598. if ( key.hasTarget( fullSid ) ) {
  31599. return key;
  31600. }
  31601. }
  31602. return null;
  31603. }
  31604. // Get previous key with given sid
  31605. function getPrevKeyWith( keys, fullSid, ndx ) {
  31606. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  31607. for ( ; ndx >= 0; ndx -- ) {
  31608. var key = keys[ ndx ];
  31609. if ( key.hasTarget( fullSid ) ) {
  31610. return key;
  31611. }
  31612. }
  31613. return null;
  31614. }
  31615. function _Image() {
  31616. this.id = "";
  31617. this.init_from = "";
  31618. }
  31619. _Image.prototype.parse = function(element) {
  31620. this.id = element.getAttribute('id');
  31621. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31622. var child = element.childNodes[ i ];
  31623. if ( child.nodeName === 'init_from' ) {
  31624. this.init_from = child.textContent;
  31625. }
  31626. }
  31627. return this;
  31628. };
  31629. function Controller() {
  31630. this.id = "";
  31631. this.name = "";
  31632. this.type = "";
  31633. this.skin = null;
  31634. this.morph = null;
  31635. }
  31636. Controller.prototype.parse = function( element ) {
  31637. this.id = element.getAttribute('id');
  31638. this.name = element.getAttribute('name');
  31639. this.type = "none";
  31640. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31641. var child = element.childNodes[ i ];
  31642. switch ( child.nodeName ) {
  31643. case 'skin':
  31644. this.skin = (new Skin()).parse(child);
  31645. this.type = child.nodeName;
  31646. break;
  31647. case 'morph':
  31648. this.morph = (new Morph()).parse(child);
  31649. this.type = child.nodeName;
  31650. break;
  31651. default:
  31652. break;
  31653. }
  31654. }
  31655. return this;
  31656. };
  31657. function Morph() {
  31658. this.method = null;
  31659. this.source = null;
  31660. this.targets = null;
  31661. this.weights = null;
  31662. }
  31663. Morph.prototype.parse = function( element ) {
  31664. var sources = {};
  31665. var inputs = [];
  31666. var i;
  31667. this.method = element.getAttribute( 'method' );
  31668. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31669. for ( i = 0; i < element.childNodes.length; i ++ ) {
  31670. var child = element.childNodes[ i ];
  31671. if ( child.nodeType != 1 ) continue;
  31672. switch ( child.nodeName ) {
  31673. case 'source':
  31674. var source = ( new Source() ).parse( child );
  31675. sources[ source.id ] = source;
  31676. break;
  31677. case 'targets':
  31678. inputs = this.parseInputs( child );
  31679. break;
  31680. default:
  31681. console.log( child.nodeName );
  31682. break;
  31683. }
  31684. }
  31685. for ( i = 0; i < inputs.length; i ++ ) {
  31686. var input = inputs[ i ];
  31687. var source = sources[ input.source ];
  31688. switch ( input.semantic ) {
  31689. case 'MORPH_TARGET':
  31690. this.targets = source.read();
  31691. break;
  31692. case 'MORPH_WEIGHT':
  31693. this.weights = source.read();
  31694. break;
  31695. default:
  31696. break;
  31697. }
  31698. }
  31699. return this;
  31700. };
  31701. Morph.prototype.parseInputs = function(element) {
  31702. var inputs = [];
  31703. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31704. var child = element.childNodes[i];
  31705. if ( child.nodeType != 1) continue;
  31706. switch ( child.nodeName ) {
  31707. case 'input':
  31708. inputs.push( (new Input()).parse(child) );
  31709. break;
  31710. default:
  31711. break;
  31712. }
  31713. }
  31714. return inputs;
  31715. };
  31716. function Skin() {
  31717. this.source = "";
  31718. this.bindShapeMatrix = null;
  31719. this.invBindMatrices = [];
  31720. this.joints = [];
  31721. this.weights = [];
  31722. }
  31723. Skin.prototype.parse = function( element ) {
  31724. var sources = {};
  31725. var joints, weights;
  31726. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  31727. this.invBindMatrices = [];
  31728. this.joints = [];
  31729. this.weights = [];
  31730. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31731. var child = element.childNodes[i];
  31732. if ( child.nodeType != 1 ) continue;
  31733. switch ( child.nodeName ) {
  31734. case 'bind_shape_matrix':
  31735. var f = _floats(child.textContent);
  31736. this.bindShapeMatrix = getConvertedMat4( f );
  31737. break;
  31738. case 'source':
  31739. var src = new Source().parse(child);
  31740. sources[ src.id ] = src;
  31741. break;
  31742. case 'joints':
  31743. joints = child;
  31744. break;
  31745. case 'vertex_weights':
  31746. weights = child;
  31747. break;
  31748. default:
  31749. console.log( child.nodeName );
  31750. break;
  31751. }
  31752. }
  31753. this.parseJoints( joints, sources );
  31754. this.parseWeights( weights, sources );
  31755. return this;
  31756. };
  31757. Skin.prototype.parseJoints = function ( element, sources ) {
  31758. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31759. var child = element.childNodes[ i ];
  31760. if ( child.nodeType != 1 ) continue;
  31761. switch ( child.nodeName ) {
  31762. case 'input':
  31763. var input = ( new Input() ).parse( child );
  31764. var source = sources[ input.source ];
  31765. if ( input.semantic === 'JOINT' ) {
  31766. this.joints = source.read();
  31767. } else if ( input.semantic === 'INV_BIND_MATRIX' ) {
  31768. this.invBindMatrices = source.read();
  31769. }
  31770. break;
  31771. default:
  31772. break;
  31773. }
  31774. }
  31775. };
  31776. Skin.prototype.parseWeights = function ( element, sources ) {
  31777. var v, vcount, inputs = [];
  31778. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31779. var child = element.childNodes[ i ];
  31780. if ( child.nodeType != 1 ) continue;
  31781. switch ( child.nodeName ) {
  31782. case 'input':
  31783. inputs.push( ( new Input() ).parse( child ) );
  31784. break;
  31785. case 'v':
  31786. v = _ints( child.textContent );
  31787. break;
  31788. case 'vcount':
  31789. vcount = _ints( child.textContent );
  31790. break;
  31791. default:
  31792. break;
  31793. }
  31794. }
  31795. var index = 0;
  31796. for ( var i = 0; i < vcount.length; i ++ ) {
  31797. var numBones = vcount[i];
  31798. var vertex_weights = [];
  31799. for ( var j = 0; j < numBones; j ++ ) {
  31800. var influence = {};
  31801. for ( var k = 0; k < inputs.length; k ++ ) {
  31802. var input = inputs[ k ];
  31803. var value = v[ index + input.offset ];
  31804. switch ( input.semantic ) {
  31805. case 'JOINT':
  31806. influence.joint = value;//this.joints[value];
  31807. break;
  31808. case 'WEIGHT':
  31809. influence.weight = sources[ input.source ].data[ value ];
  31810. break;
  31811. default:
  31812. break;
  31813. }
  31814. }
  31815. vertex_weights.push( influence );
  31816. index += inputs.length;
  31817. }
  31818. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  31819. vertex_weights[ j ].index = i;
  31820. }
  31821. this.weights.push( vertex_weights );
  31822. }
  31823. };
  31824. function VisualScene () {
  31825. this.id = "";
  31826. this.name = "";
  31827. this.nodes = [];
  31828. this.scene = new THREE.Group();
  31829. }
  31830. VisualScene.prototype.getChildById = function( id, recursive ) {
  31831. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31832. var node = this.nodes[ i ].getChildById( id, recursive );
  31833. if ( node ) {
  31834. return node;
  31835. }
  31836. }
  31837. return null;
  31838. };
  31839. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  31840. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31841. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  31842. if ( node ) {
  31843. return node;
  31844. }
  31845. }
  31846. return null;
  31847. };
  31848. VisualScene.prototype.parse = function( element ) {
  31849. this.id = element.getAttribute( 'id' );
  31850. this.name = element.getAttribute( 'name' );
  31851. this.nodes = [];
  31852. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31853. var child = element.childNodes[ i ];
  31854. if ( child.nodeType != 1 ) continue;
  31855. switch ( child.nodeName ) {
  31856. case 'node':
  31857. this.nodes.push( ( new Node() ).parse( child ) );
  31858. break;
  31859. default:
  31860. break;
  31861. }
  31862. }
  31863. return this;
  31864. };
  31865. function Node() {
  31866. this.id = "";
  31867. this.name = "";
  31868. this.sid = "";
  31869. this.nodes = [];
  31870. this.controllers = [];
  31871. this.transforms = [];
  31872. this.geometries = [];
  31873. this.channels = [];
  31874. this.matrix = new THREE.Matrix4();
  31875. }
  31876. Node.prototype.getChannelForTransform = function( transformSid ) {
  31877. for ( var i = 0; i < this.channels.length; i ++ ) {
  31878. var channel = this.channels[i];
  31879. var parts = channel.target.split('/');
  31880. var id = parts.shift();
  31881. var sid = parts.shift();
  31882. var dotSyntax = (sid.indexOf(".") >= 0);
  31883. var arrSyntax = (sid.indexOf("(") >= 0);
  31884. var arrIndices;
  31885. var member;
  31886. if ( dotSyntax ) {
  31887. parts = sid.split(".");
  31888. sid = parts.shift();
  31889. member = parts.shift();
  31890. } else if ( arrSyntax ) {
  31891. arrIndices = sid.split("(");
  31892. sid = arrIndices.shift();
  31893. for ( var j = 0; j < arrIndices.length; j ++ ) {
  31894. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  31895. }
  31896. }
  31897. if ( sid === transformSid ) {
  31898. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  31899. return channel;
  31900. }
  31901. }
  31902. return null;
  31903. };
  31904. Node.prototype.getChildById = function ( id, recursive ) {
  31905. if ( this.id === id ) {
  31906. return this;
  31907. }
  31908. if ( recursive ) {
  31909. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31910. var n = this.nodes[ i ].getChildById( id, recursive );
  31911. if ( n ) {
  31912. return n;
  31913. }
  31914. }
  31915. }
  31916. return null;
  31917. };
  31918. Node.prototype.getChildBySid = function ( sid, recursive ) {
  31919. if ( this.sid === sid ) {
  31920. return this;
  31921. }
  31922. if ( recursive ) {
  31923. for ( var i = 0; i < this.nodes.length; i ++ ) {
  31924. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  31925. if ( n ) {
  31926. return n;
  31927. }
  31928. }
  31929. }
  31930. return null;
  31931. };
  31932. Node.prototype.getTransformBySid = function ( sid ) {
  31933. for ( var i = 0; i < this.transforms.length; i ++ ) {
  31934. if ( this.transforms[ i ].sid === sid ) return this.transforms[ i ];
  31935. }
  31936. return null;
  31937. };
  31938. Node.prototype.parse = function( element ) {
  31939. var url;
  31940. this.id = element.getAttribute('id');
  31941. this.sid = element.getAttribute('sid');
  31942. this.name = element.getAttribute('name');
  31943. this.type = element.getAttribute('type');
  31944. this.layer = element.getAttribute('layer');
  31945. this.type = this.type === 'JOINT' ? this.type : 'NODE';
  31946. this.nodes = [];
  31947. this.transforms = [];
  31948. this.geometries = [];
  31949. this.cameras = [];
  31950. this.lights = [];
  31951. this.controllers = [];
  31952. this.matrix = new THREE.Matrix4();
  31953. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  31954. var child = element.childNodes[ i ];
  31955. if ( child.nodeType != 1 ) continue;
  31956. switch ( child.nodeName ) {
  31957. case 'node':
  31958. this.nodes.push( ( new Node() ).parse( child ) );
  31959. break;
  31960. case 'instance_camera':
  31961. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  31962. break;
  31963. case 'instance_controller':
  31964. this.controllers.push( ( new InstanceController() ).parse( child ) );
  31965. break;
  31966. case 'instance_geometry':
  31967. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  31968. break;
  31969. case 'instance_light':
  31970. this.lights.push( ( new InstanceLight() ).parse( child ) );
  31971. break;
  31972. case 'instance_node':
  31973. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  31974. var iNode = getLibraryNode( url );
  31975. if ( iNode ) {
  31976. this.nodes.push( ( new Node() ).parse( iNode )) ;
  31977. }
  31978. break;
  31979. case 'rotate':
  31980. case 'translate':
  31981. case 'scale':
  31982. case 'matrix':
  31983. case 'lookat':
  31984. case 'skew':
  31985. this.transforms.push( ( new Transform() ).parse( child ) );
  31986. break;
  31987. case 'extra':
  31988. break;
  31989. default:
  31990. console.log( child.nodeName );
  31991. break;
  31992. }
  31993. }
  31994. this.channels = getChannelsForNode( this );
  31995. bakeAnimations( this );
  31996. this.updateMatrix();
  31997. return this;
  31998. };
  31999. Node.prototype.updateMatrix = function () {
  32000. this.matrix.identity();
  32001. for ( var i = 0; i < this.transforms.length; i ++ ) {
  32002. this.transforms[ i ].apply( this.matrix );
  32003. }
  32004. };
  32005. function Transform () {
  32006. this.sid = "";
  32007. this.type = "";
  32008. this.data = [];
  32009. this.obj = null;
  32010. }
  32011. Transform.prototype.parse = function ( element ) {
  32012. this.sid = element.getAttribute( 'sid' );
  32013. this.type = element.nodeName;
  32014. this.data = _floats( element.textContent );
  32015. this.convert();
  32016. return this;
  32017. };
  32018. Transform.prototype.convert = function () {
  32019. switch ( this.type ) {
  32020. case 'matrix':
  32021. this.obj = getConvertedMat4( this.data );
  32022. break;
  32023. case 'rotate':
  32024. this.angle = THREE.Math.degToRad( this.data[3] );
  32025. case 'translate':
  32026. fixCoords( this.data, -1 );
  32027. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32028. break;
  32029. case 'scale':
  32030. fixCoords( this.data, 1 );
  32031. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  32032. break;
  32033. default:
  32034. console.log( 'Can not convert Transform of type ' + this.type );
  32035. break;
  32036. }
  32037. };
  32038. Transform.prototype.apply = function () {
  32039. var m1 = new THREE.Matrix4();
  32040. return function ( matrix ) {
  32041. switch ( this.type ) {
  32042. case 'matrix':
  32043. matrix.multiply( this.obj );
  32044. break;
  32045. case 'translate':
  32046. matrix.multiply( m1.makeTranslation( this.obj.x, this.obj.y, this.obj.z ) );
  32047. break;
  32048. case 'rotate':
  32049. matrix.multiply( m1.makeRotationAxis( this.obj, this.angle ) );
  32050. break;
  32051. case 'scale':
  32052. matrix.scale( this.obj );
  32053. break;
  32054. }
  32055. };
  32056. }();
  32057. Transform.prototype.update = function ( data, member ) {
  32058. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  32059. switch ( this.type ) {
  32060. case 'matrix':
  32061. if ( ! member ) {
  32062. this.obj.copy( data );
  32063. } else if ( member.length === 1 ) {
  32064. switch ( member[ 0 ] ) {
  32065. case 0:
  32066. this.obj.n11 = data[ 0 ];
  32067. this.obj.n21 = data[ 1 ];
  32068. this.obj.n31 = data[ 2 ];
  32069. this.obj.n41 = data[ 3 ];
  32070. break;
  32071. case 1:
  32072. this.obj.n12 = data[ 0 ];
  32073. this.obj.n22 = data[ 1 ];
  32074. this.obj.n32 = data[ 2 ];
  32075. this.obj.n42 = data[ 3 ];
  32076. break;
  32077. case 2:
  32078. this.obj.n13 = data[ 0 ];
  32079. this.obj.n23 = data[ 1 ];
  32080. this.obj.n33 = data[ 2 ];
  32081. this.obj.n43 = data[ 3 ];
  32082. break;
  32083. case 3:
  32084. this.obj.n14 = data[ 0 ];
  32085. this.obj.n24 = data[ 1 ];
  32086. this.obj.n34 = data[ 2 ];
  32087. this.obj.n44 = data[ 3 ];
  32088. break;
  32089. }
  32090. } else if ( member.length === 2 ) {
  32091. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  32092. this.obj[ propName ] = data;
  32093. } else {
  32094. console.log('Incorrect addressing of matrix in transform.');
  32095. }
  32096. break;
  32097. case 'translate':
  32098. case 'scale':
  32099. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32100. member = members[ member[ 0 ] ];
  32101. }
  32102. switch ( member ) {
  32103. case 'X':
  32104. this.obj.x = data;
  32105. break;
  32106. case 'Y':
  32107. this.obj.y = data;
  32108. break;
  32109. case 'Z':
  32110. this.obj.z = data;
  32111. break;
  32112. default:
  32113. this.obj.x = data[ 0 ];
  32114. this.obj.y = data[ 1 ];
  32115. this.obj.z = data[ 2 ];
  32116. break;
  32117. }
  32118. break;
  32119. case 'rotate':
  32120. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  32121. member = members[ member[ 0 ] ];
  32122. }
  32123. switch ( member ) {
  32124. case 'X':
  32125. this.obj.x = data;
  32126. break;
  32127. case 'Y':
  32128. this.obj.y = data;
  32129. break;
  32130. case 'Z':
  32131. this.obj.z = data;
  32132. break;
  32133. case 'ANGLE':
  32134. this.angle = THREE.Math.degToRad( data );
  32135. break;
  32136. default:
  32137. this.obj.x = data[ 0 ];
  32138. this.obj.y = data[ 1 ];
  32139. this.obj.z = data[ 2 ];
  32140. this.angle = THREE.Math.degToRad( data[ 3 ] );
  32141. break;
  32142. }
  32143. break;
  32144. }
  32145. };
  32146. function InstanceController() {
  32147. this.url = "";
  32148. this.skeleton = [];
  32149. this.instance_material = [];
  32150. }
  32151. InstanceController.prototype.parse = function ( element ) {
  32152. this.url = element.getAttribute('url').replace(/^#/, '');
  32153. this.skeleton = [];
  32154. this.instance_material = [];
  32155. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32156. var child = element.childNodes[ i ];
  32157. if ( child.nodeType !== 1 ) continue;
  32158. switch ( child.nodeName ) {
  32159. case 'skeleton':
  32160. this.skeleton.push( child.textContent.replace(/^#/, '') );
  32161. break;
  32162. case 'bind_material':
  32163. var instances = child.querySelectorAll('instance_material');
  32164. for ( var j = 0; j < instances.length; j ++ ) {
  32165. var instance = instances[j];
  32166. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32167. }
  32168. break;
  32169. case 'extra':
  32170. break;
  32171. default:
  32172. break;
  32173. }
  32174. }
  32175. return this;
  32176. };
  32177. function InstanceMaterial () {
  32178. this.symbol = "";
  32179. this.target = "";
  32180. }
  32181. InstanceMaterial.prototype.parse = function ( element ) {
  32182. this.symbol = element.getAttribute('symbol');
  32183. this.target = element.getAttribute('target').replace(/^#/, '');
  32184. return this;
  32185. };
  32186. function InstanceGeometry() {
  32187. this.url = "";
  32188. this.instance_material = [];
  32189. }
  32190. InstanceGeometry.prototype.parse = function ( element ) {
  32191. this.url = element.getAttribute('url').replace(/^#/, '');
  32192. this.instance_material = [];
  32193. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32194. var child = element.childNodes[i];
  32195. if ( child.nodeType != 1 ) continue;
  32196. if ( child.nodeName === 'bind_material' ) {
  32197. var instances = child.querySelectorAll('instance_material');
  32198. for ( var j = 0; j < instances.length; j ++ ) {
  32199. var instance = instances[j];
  32200. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  32201. }
  32202. break;
  32203. }
  32204. }
  32205. return this;
  32206. };
  32207. function Geometry() {
  32208. this.id = "";
  32209. this.mesh = null;
  32210. }
  32211. Geometry.prototype.parse = function ( element ) {
  32212. this.id = element.getAttribute('id');
  32213. extractDoubleSided( this, element );
  32214. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32215. var child = element.childNodes[i];
  32216. switch ( child.nodeName ) {
  32217. case 'mesh':
  32218. this.mesh = (new Mesh(this)).parse(child);
  32219. break;
  32220. case 'extra':
  32221. // console.log( child );
  32222. break;
  32223. default:
  32224. break;
  32225. }
  32226. }
  32227. return this;
  32228. };
  32229. function Mesh( geometry ) {
  32230. this.geometry = geometry.id;
  32231. this.primitives = [];
  32232. this.vertices = null;
  32233. this.geometry3js = null;
  32234. }
  32235. Mesh.prototype.parse = function ( element ) {
  32236. this.primitives = [];
  32237. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32238. var child = element.childNodes[ i ];
  32239. switch ( child.nodeName ) {
  32240. case 'source':
  32241. _source( child );
  32242. break;
  32243. case 'vertices':
  32244. this.vertices = ( new Vertices() ).parse( child );
  32245. break;
  32246. case 'linestrips':
  32247. this.primitives.push( ( new LineStrips().parse( child ) ) );
  32248. break;
  32249. case 'triangles':
  32250. this.primitives.push( ( new Triangles().parse( child ) ) );
  32251. break;
  32252. case 'polygons':
  32253. this.primitives.push( ( new Polygons().parse( child ) ) );
  32254. break;
  32255. case 'polylist':
  32256. this.primitives.push( ( new Polylist().parse( child ) ) );
  32257. break;
  32258. default:
  32259. break;
  32260. }
  32261. }
  32262. this.geometry3js = new THREE.Geometry();
  32263. if ( this.vertices === null ) {
  32264. // TODO (mrdoob): Study case when this is null (carrier.dae)
  32265. return this;
  32266. }
  32267. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  32268. for ( var i = 0; i < vertexData.length; i += 3 ) {
  32269. this.geometry3js.vertices.push( getConvertedVec3( vertexData, i ).clone() );
  32270. }
  32271. for ( var i = 0; i < this.primitives.length; i ++ ) {
  32272. var primitive = this.primitives[ i ];
  32273. primitive.setVertices( this.vertices );
  32274. this.handlePrimitive( primitive, this.geometry3js );
  32275. }
  32276. if ( this.geometry3js.calcNormals ) {
  32277. this.geometry3js.computeVertexNormals();
  32278. delete this.geometry3js.calcNormals;
  32279. }
  32280. return this;
  32281. };
  32282. Mesh.prototype.handlePrimitive = function ( primitive, geom ) {
  32283. if ( primitive instanceof LineStrips ) {
  32284. // TODO: Handle indices. Maybe easier with BufferGeometry?
  32285. geom.isLineStrip = true;
  32286. return;
  32287. }
  32288. var j, k, pList = primitive.p, inputs = primitive.inputs;
  32289. var input, index, idx32;
  32290. var source, numParams;
  32291. var vcIndex = 0, vcount = 3, maxOffset = 0;
  32292. var texture_sets = [];
  32293. for ( j = 0; j < inputs.length; j ++ ) {
  32294. input = inputs[ j ];
  32295. var offset = input.offset + 1;
  32296. maxOffset = (maxOffset < offset) ? offset : maxOffset;
  32297. switch ( input.semantic ) {
  32298. case 'TEXCOORD':
  32299. texture_sets.push( input.set );
  32300. break;
  32301. }
  32302. }
  32303. for ( var pCount = 0; pCount < pList.length; ++ pCount ) {
  32304. var p = pList[ pCount ], i = 0;
  32305. while ( i < p.length ) {
  32306. var vs = [];
  32307. var ns = [];
  32308. var ts = null;
  32309. var cs = [];
  32310. if ( primitive.vcount ) {
  32311. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  32312. } else {
  32313. vcount = p.length / maxOffset;
  32314. }
  32315. for ( j = 0; j < vcount; j ++ ) {
  32316. for ( k = 0; k < inputs.length; k ++ ) {
  32317. input = inputs[ k ];
  32318. source = sources[ input.source ];
  32319. index = p[ i + ( j * maxOffset ) + input.offset ];
  32320. numParams = source.accessor.params.length;
  32321. idx32 = index * numParams;
  32322. switch ( input.semantic ) {
  32323. case 'VERTEX':
  32324. vs.push( index );
  32325. break;
  32326. case 'NORMAL':
  32327. ns.push( getConvertedVec3( source.data, idx32 ) );
  32328. break;
  32329. case 'TEXCOORD':
  32330. ts = ts || { };
  32331. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  32332. // invert the V
  32333. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], source.data[ idx32 + 1 ] ) );
  32334. break;
  32335. case 'COLOR':
  32336. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32337. break;
  32338. default:
  32339. break;
  32340. }
  32341. }
  32342. }
  32343. if ( ns.length === 0 ) {
  32344. // check the vertices inputs
  32345. input = this.vertices.input.NORMAL;
  32346. if ( input ) {
  32347. source = sources[ input.source ];
  32348. numParams = source.accessor.params.length;
  32349. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32350. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  32351. }
  32352. } else {
  32353. geom.calcNormals = true;
  32354. }
  32355. }
  32356. if ( !ts ) {
  32357. ts = { };
  32358. // check the vertices inputs
  32359. input = this.vertices.input.TEXCOORD;
  32360. if ( input ) {
  32361. texture_sets.push( input.set );
  32362. source = sources[ input.source ];
  32363. numParams = source.accessor.params.length;
  32364. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32365. idx32 = vs[ ndx ] * numParams;
  32366. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [ ];
  32367. // invert the V
  32368. ts[ input.set ].push( new THREE.Vector2( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  32369. }
  32370. }
  32371. }
  32372. if ( cs.length === 0 ) {
  32373. // check the vertices inputs
  32374. input = this.vertices.input.COLOR;
  32375. if ( input ) {
  32376. source = sources[ input.source ];
  32377. numParams = source.accessor.params.length;
  32378. for ( var ndx = 0, len = vs.length; ndx < len; ndx ++ ) {
  32379. idx32 = vs[ ndx ] * numParams;
  32380. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  32381. }
  32382. }
  32383. }
  32384. var face = null, faces = [], uv, uvArr;
  32385. if ( vcount === 3 ) {
  32386. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  32387. } else if ( vcount === 4 ) {
  32388. faces.push( new THREE.Face3( vs[0], vs[1], vs[3], ns.length ? [ ns[0].clone(), ns[1].clone(), ns[3].clone() ] : [], cs.length ? [ cs[0], cs[1], cs[3] ] : new THREE.Color() ) );
  32389. faces.push( new THREE.Face3( vs[1], vs[2], vs[3], ns.length ? [ ns[1].clone(), ns[2].clone(), ns[3].clone() ] : [], cs.length ? [ cs[1], cs[2], cs[3] ] : new THREE.Color() ) );
  32390. } else if ( vcount > 4 && options.subdivideFaces ) {
  32391. var clr = cs.length ? cs : new THREE.Color(),
  32392. vec1, vec2, vec3, v1, v2, norm;
  32393. // subdivide into multiple Face3s
  32394. for ( k = 1; k < vcount - 1; ) {
  32395. faces.push( new THREE.Face3( vs[0], vs[k], vs[k + 1], ns.length ? [ ns[0].clone(), ns[k ++].clone(), ns[k].clone() ] : [], clr ) );
  32396. }
  32397. }
  32398. if ( faces.length ) {
  32399. for ( var ndx = 0, len = faces.length; ndx < len; ndx ++ ) {
  32400. face = faces[ndx];
  32401. face.daeMaterial = primitive.material;
  32402. geom.faces.push( face );
  32403. for ( k = 0; k < texture_sets.length; k ++ ) {
  32404. uv = ts[ texture_sets[k] ];
  32405. if ( vcount > 4 ) {
  32406. // Grab the right UVs for the vertices in this face
  32407. uvArr = [ uv[0], uv[ndx + 1], uv[ndx + 2] ];
  32408. } else if ( vcount === 4 ) {
  32409. if ( ndx === 0 ) {
  32410. uvArr = [ uv[0], uv[1], uv[3] ];
  32411. } else {
  32412. uvArr = [ uv[1].clone(), uv[2], uv[3].clone() ];
  32413. }
  32414. } else {
  32415. uvArr = [ uv[0], uv[1], uv[2] ];
  32416. }
  32417. if ( geom.faceVertexUvs[k] === undefined ) {
  32418. geom.faceVertexUvs[k] = [];
  32419. }
  32420. geom.faceVertexUvs[k].push( uvArr );
  32421. }
  32422. }
  32423. } else {
  32424. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  32425. }
  32426. i += maxOffset * vcount;
  32427. }
  32428. }
  32429. };
  32430. function Polygons () {
  32431. this.material = "";
  32432. this.count = 0;
  32433. this.inputs = [];
  32434. this.vcount = null;
  32435. this.p = [];
  32436. this.geometry = new THREE.Geometry();
  32437. }
  32438. Polygons.prototype.setVertices = function ( vertices ) {
  32439. for ( var i = 0; i < this.inputs.length; i ++ ) {
  32440. if ( this.inputs[ i ].source === vertices.id ) {
  32441. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  32442. }
  32443. }
  32444. };
  32445. Polygons.prototype.parse = function ( element ) {
  32446. this.material = element.getAttribute( 'material' );
  32447. this.count = _attr_as_int( element, 'count', 0 );
  32448. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32449. var child = element.childNodes[ i ];
  32450. switch ( child.nodeName ) {
  32451. case 'input':
  32452. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  32453. break;
  32454. case 'vcount':
  32455. this.vcount = _ints( child.textContent );
  32456. break;
  32457. case 'p':
  32458. this.p.push( _ints( child.textContent ) );
  32459. break;
  32460. case 'ph':
  32461. console.warn( 'polygon holes not yet supported!' );
  32462. break;
  32463. default:
  32464. break;
  32465. }
  32466. }
  32467. return this;
  32468. };
  32469. function Polylist () {
  32470. Polygons.call( this );
  32471. this.vcount = [];
  32472. }
  32473. Polylist.prototype = Object.create( Polygons.prototype );
  32474. Polylist.prototype.constructor = Polylist;
  32475. function LineStrips() {
  32476. Polygons.call( this );
  32477. this.vcount = 1;
  32478. }
  32479. LineStrips.prototype = Object.create( Polygons.prototype );
  32480. LineStrips.prototype.constructor = LineStrips;
  32481. function Triangles () {
  32482. Polygons.call( this );
  32483. this.vcount = 3;
  32484. }
  32485. Triangles.prototype = Object.create( Polygons.prototype );
  32486. Triangles.prototype.constructor = Triangles;
  32487. function Accessor() {
  32488. this.source = "";
  32489. this.count = 0;
  32490. this.stride = 0;
  32491. this.params = [];
  32492. }
  32493. Accessor.prototype.parse = function ( element ) {
  32494. this.params = [];
  32495. this.source = element.getAttribute( 'source' );
  32496. this.count = _attr_as_int( element, 'count', 0 );
  32497. this.stride = _attr_as_int( element, 'stride', 0 );
  32498. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32499. var child = element.childNodes[ i ];
  32500. if ( child.nodeName === 'param' ) {
  32501. var param = {};
  32502. param[ 'name' ] = child.getAttribute( 'name' );
  32503. param[ 'type' ] = child.getAttribute( 'type' );
  32504. this.params.push( param );
  32505. }
  32506. }
  32507. return this;
  32508. };
  32509. function Vertices() {
  32510. this.input = {};
  32511. }
  32512. Vertices.prototype.parse = function ( element ) {
  32513. this.id = element.getAttribute('id');
  32514. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32515. if ( element.childNodes[i].nodeName === 'input' ) {
  32516. var input = ( new Input() ).parse( element.childNodes[ i ] );
  32517. this.input[ input.semantic ] = input;
  32518. }
  32519. }
  32520. return this;
  32521. };
  32522. function Input () {
  32523. this.semantic = "";
  32524. this.offset = 0;
  32525. this.source = "";
  32526. this.set = 0;
  32527. }
  32528. Input.prototype.parse = function ( element ) {
  32529. this.semantic = element.getAttribute('semantic');
  32530. this.source = element.getAttribute('source').replace(/^#/, '');
  32531. this.set = _attr_as_int(element, 'set', -1);
  32532. this.offset = _attr_as_int(element, 'offset', 0);
  32533. if ( this.semantic === 'TEXCOORD' && this.set < 0 ) {
  32534. this.set = 0;
  32535. }
  32536. return this;
  32537. };
  32538. function Source ( id ) {
  32539. this.id = id;
  32540. this.type = null;
  32541. }
  32542. Source.prototype.parse = function ( element ) {
  32543. this.id = element.getAttribute( 'id' );
  32544. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32545. var child = element.childNodes[i];
  32546. switch ( child.nodeName ) {
  32547. case 'bool_array':
  32548. this.data = _bools( child.textContent );
  32549. this.type = child.nodeName;
  32550. break;
  32551. case 'float_array':
  32552. this.data = _floats( child.textContent );
  32553. this.type = child.nodeName;
  32554. break;
  32555. case 'int_array':
  32556. this.data = _ints( child.textContent );
  32557. this.type = child.nodeName;
  32558. break;
  32559. case 'IDREF_array':
  32560. case 'Name_array':
  32561. this.data = _strings( child.textContent );
  32562. this.type = child.nodeName;
  32563. break;
  32564. case 'technique_common':
  32565. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  32566. if ( child.childNodes[ j ].nodeName === 'accessor' ) {
  32567. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  32568. break;
  32569. }
  32570. }
  32571. break;
  32572. default:
  32573. // console.log(child.nodeName);
  32574. break;
  32575. }
  32576. }
  32577. return this;
  32578. };
  32579. Source.prototype.read = function () {
  32580. var result = [];
  32581. //for (var i = 0; i < this.accessor.params.length; i++) {
  32582. var param = this.accessor.params[ 0 ];
  32583. //console.log(param.name + " " + param.type);
  32584. switch ( param.type ) {
  32585. case 'IDREF':
  32586. case 'Name': case 'name':
  32587. case 'float':
  32588. return this.data;
  32589. case 'float4x4':
  32590. for ( var j = 0; j < this.data.length; j += 16 ) {
  32591. var s = this.data.slice( j, j + 16 );
  32592. var m = getConvertedMat4( s );
  32593. result.push( m );
  32594. }
  32595. break;
  32596. default:
  32597. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  32598. break;
  32599. }
  32600. //}
  32601. return result;
  32602. };
  32603. function Material () {
  32604. this.id = "";
  32605. this.name = "";
  32606. this.instance_effect = null;
  32607. }
  32608. Material.prototype.parse = function ( element ) {
  32609. this.id = element.getAttribute( 'id' );
  32610. this.name = element.getAttribute( 'name' );
  32611. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32612. if ( element.childNodes[ i ].nodeName === 'instance_effect' ) {
  32613. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  32614. break;
  32615. }
  32616. }
  32617. return this;
  32618. };
  32619. function ColorOrTexture () {
  32620. this.color = new THREE.Color();
  32621. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  32622. this.color.a = 1.0;
  32623. this.texture = null;
  32624. this.texcoord = null;
  32625. this.texOpts = null;
  32626. }
  32627. ColorOrTexture.prototype.isColor = function () {
  32628. return ( this.texture === null );
  32629. };
  32630. ColorOrTexture.prototype.isTexture = function () {
  32631. return ( this.texture != null );
  32632. };
  32633. ColorOrTexture.prototype.parse = function ( element ) {
  32634. if (element.nodeName === 'transparent') {
  32635. this.opaque = element.getAttribute('opaque');
  32636. }
  32637. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32638. var child = element.childNodes[ i ];
  32639. if ( child.nodeType != 1 ) continue;
  32640. switch ( child.nodeName ) {
  32641. case 'color':
  32642. var rgba = _floats( child.textContent );
  32643. this.color = new THREE.Color();
  32644. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  32645. this.color.a = rgba[3];
  32646. break;
  32647. case 'texture':
  32648. this.texture = child.getAttribute('texture');
  32649. this.texcoord = child.getAttribute('texcoord');
  32650. // Defaults from:
  32651. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  32652. this.texOpts = {
  32653. offsetU: 0,
  32654. offsetV: 0,
  32655. repeatU: 1,
  32656. repeatV: 1,
  32657. wrapU: 1,
  32658. wrapV: 1
  32659. };
  32660. this.parseTexture( child );
  32661. break;
  32662. default:
  32663. break;
  32664. }
  32665. }
  32666. return this;
  32667. };
  32668. ColorOrTexture.prototype.parseTexture = function ( element ) {
  32669. if ( ! element.childNodes ) return this;
  32670. // This should be supported by Maya, 3dsMax, and MotionBuilder
  32671. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  32672. element = element.childNodes[1];
  32673. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  32674. element = element.childNodes[1];
  32675. }
  32676. }
  32677. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32678. var child = element.childNodes[ i ];
  32679. switch ( child.nodeName ) {
  32680. case 'offsetU':
  32681. case 'offsetV':
  32682. case 'repeatU':
  32683. case 'repeatV':
  32684. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  32685. break;
  32686. case 'wrapU':
  32687. case 'wrapV':
  32688. // some dae have a value of true which becomes NaN via parseInt
  32689. if ( child.textContent.toUpperCase() === 'TRUE' ) {
  32690. this.texOpts[ child.nodeName ] = 1;
  32691. } else {
  32692. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  32693. }
  32694. break;
  32695. default:
  32696. this.texOpts[ child.nodeName ] = child.textContent;
  32697. break;
  32698. }
  32699. }
  32700. return this;
  32701. };
  32702. function Shader ( type, effect ) {
  32703. this.type = type;
  32704. this.effect = effect;
  32705. this.material = null;
  32706. }
  32707. Shader.prototype.parse = function ( element ) {
  32708. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32709. var child = element.childNodes[ i ];
  32710. if ( child.nodeType != 1 ) continue;
  32711. switch ( child.nodeName ) {
  32712. case 'emission':
  32713. case 'diffuse':
  32714. case 'specular':
  32715. case 'transparent':
  32716. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  32717. break;
  32718. case 'bump':
  32719. // If 'bumptype' is 'heightfield', create a 'bump' property
  32720. // Else if 'bumptype' is 'normalmap', create a 'normal' property
  32721. // (Default to 'bump')
  32722. var bumpType = child.getAttribute( 'bumptype' );
  32723. if ( bumpType ) {
  32724. if ( bumpType.toLowerCase() === "heightfield" ) {
  32725. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32726. } else if ( bumpType.toLowerCase() === "normalmap" ) {
  32727. this[ 'normal' ] = ( new ColorOrTexture() ).parse( child );
  32728. } else {
  32729. console.error( "Shader.prototype.parse: Invalid value for attribute 'bumptype' (" + bumpType + ") - valid bumptypes are 'HEIGHTFIELD' and 'NORMALMAP' - defaulting to 'HEIGHTFIELD'" );
  32730. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32731. }
  32732. } else {
  32733. console.warn( "Shader.prototype.parse: Attribute 'bumptype' missing from bump node - defaulting to 'HEIGHTFIELD'" );
  32734. this[ 'bump' ] = ( new ColorOrTexture() ).parse( child );
  32735. }
  32736. break;
  32737. case 'shininess':
  32738. case 'reflectivity':
  32739. case 'index_of_refraction':
  32740. case 'transparency':
  32741. var f = child.querySelectorAll('float');
  32742. if ( f.length > 0 )
  32743. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  32744. break;
  32745. default:
  32746. break;
  32747. }
  32748. }
  32749. this.create();
  32750. return this;
  32751. };
  32752. Shader.prototype.create = function() {
  32753. var props = {};
  32754. var transparent = false;
  32755. if (this['transparency'] !== undefined && this['transparent'] !== undefined) {
  32756. // convert transparent color RBG to average value
  32757. var transparentColor = this['transparent'];
  32758. var transparencyLevel = (this.transparent.color.r + this.transparent.color.g + this.transparent.color.b) / 3 * this.transparency;
  32759. if (transparencyLevel > 0) {
  32760. transparent = true;
  32761. props[ 'transparent' ] = true;
  32762. props[ 'opacity' ] = 1 - transparencyLevel;
  32763. }
  32764. }
  32765. var keys = {
  32766. 'diffuse':'map',
  32767. 'ambient':'lightMap',
  32768. 'specular':'specularMap',
  32769. 'emission':'emissionMap',
  32770. 'bump':'bumpMap',
  32771. 'normal':'normalMap'
  32772. };
  32773. for ( var prop in this ) {
  32774. switch ( prop ) {
  32775. case 'ambient':
  32776. case 'emission':
  32777. case 'diffuse':
  32778. case 'specular':
  32779. case 'bump':
  32780. case 'normal':
  32781. var cot = this[ prop ];
  32782. if ( cot instanceof ColorOrTexture ) {
  32783. if ( cot.isTexture() ) {
  32784. var samplerId = cot.texture;
  32785. var surfaceId = this.effect.sampler[samplerId];
  32786. if ( surfaceId !== undefined && surfaceId.source !== undefined ) {
  32787. var surface = this.effect.surface[surfaceId.source];
  32788. if ( surface !== undefined ) {
  32789. var image = images[ surface.init_from ];
  32790. if ( image ) {
  32791. var url = baseUrl + image.init_from;
  32792. var texture;
  32793. var loader = THREE.Loader.Handlers.get( url );
  32794. if ( loader !== null ) {
  32795. texture = loader.load( url );
  32796. } else {
  32797. texture = new THREE.Texture();
  32798. loadTextureImage( texture, url );
  32799. }
  32800. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  32801. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  32802. texture.offset.x = cot.texOpts.offsetU;
  32803. texture.offset.y = cot.texOpts.offsetV;
  32804. texture.repeat.x = cot.texOpts.repeatU;
  32805. texture.repeat.y = cot.texOpts.repeatV;
  32806. props[keys[prop]] = texture;
  32807. // Texture with baked lighting?
  32808. if (prop === 'emission') props['emissive'] = 0xffffff;
  32809. }
  32810. }
  32811. }
  32812. } else if ( prop === 'diffuse' || !transparent ) {
  32813. if ( prop === 'emission' ) {
  32814. props[ 'emissive' ] = cot.color.getHex();
  32815. } else {
  32816. props[ prop ] = cot.color.getHex();
  32817. }
  32818. }
  32819. }
  32820. break;
  32821. case 'shininess':
  32822. props[ prop ] = this[ prop ];
  32823. break;
  32824. case 'reflectivity':
  32825. props[ prop ] = this[ prop ];
  32826. if ( props[ prop ] > 0.0 ) props['envMap'] = options.defaultEnvMap;
  32827. props['combine'] = THREE.MixOperation; //mix regular shading with reflective component
  32828. break;
  32829. case 'index_of_refraction':
  32830. props[ 'refractionRatio' ] = this[ prop ]; //TODO: "index_of_refraction" becomes "refractionRatio" in shader, but I'm not sure if the two are actually comparable
  32831. if ( this[ prop ] !== 1.0 ) props['envMap'] = options.defaultEnvMap;
  32832. break;
  32833. case 'transparency':
  32834. // gets figured out up top
  32835. break;
  32836. default:
  32837. break;
  32838. }
  32839. }
  32840. props[ 'shading' ] = preferredShading;
  32841. props[ 'side' ] = this.effect.doubleSided ? THREE.DoubleSide : THREE.FrontSide;
  32842. if ( props.diffuse !== undefined ) {
  32843. props.color = props.diffuse;
  32844. delete props.diffuse;
  32845. }
  32846. switch ( this.type ) {
  32847. case 'constant':
  32848. if (props.emissive != undefined) props.color = props.emissive;
  32849. this.material = new THREE.MeshBasicMaterial( props );
  32850. break;
  32851. case 'phong':
  32852. case 'blinn':
  32853. this.material = new THREE.MeshPhongMaterial( props );
  32854. break;
  32855. case 'lambert':
  32856. default:
  32857. this.material = new THREE.MeshLambertMaterial( props );
  32858. break;
  32859. }
  32860. return this.material;
  32861. };
  32862. function Surface ( effect ) {
  32863. this.effect = effect;
  32864. this.init_from = null;
  32865. this.format = null;
  32866. }
  32867. Surface.prototype.parse = function ( element ) {
  32868. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32869. var child = element.childNodes[ i ];
  32870. if ( child.nodeType != 1 ) continue;
  32871. switch ( child.nodeName ) {
  32872. case 'init_from':
  32873. this.init_from = child.textContent;
  32874. break;
  32875. case 'format':
  32876. this.format = child.textContent;
  32877. break;
  32878. default:
  32879. console.log( "unhandled Surface prop: " + child.nodeName );
  32880. break;
  32881. }
  32882. }
  32883. return this;
  32884. };
  32885. function Sampler2D ( effect ) {
  32886. this.effect = effect;
  32887. this.source = null;
  32888. this.wrap_s = null;
  32889. this.wrap_t = null;
  32890. this.minfilter = null;
  32891. this.magfilter = null;
  32892. this.mipfilter = null;
  32893. }
  32894. Sampler2D.prototype.parse = function ( element ) {
  32895. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32896. var child = element.childNodes[ i ];
  32897. if ( child.nodeType != 1 ) continue;
  32898. switch ( child.nodeName ) {
  32899. case 'source':
  32900. this.source = child.textContent;
  32901. break;
  32902. case 'minfilter':
  32903. this.minfilter = child.textContent;
  32904. break;
  32905. case 'magfilter':
  32906. this.magfilter = child.textContent;
  32907. break;
  32908. case 'mipfilter':
  32909. this.mipfilter = child.textContent;
  32910. break;
  32911. case 'wrap_s':
  32912. this.wrap_s = child.textContent;
  32913. break;
  32914. case 'wrap_t':
  32915. this.wrap_t = child.textContent;
  32916. break;
  32917. default:
  32918. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  32919. break;
  32920. }
  32921. }
  32922. return this;
  32923. };
  32924. function Effect () {
  32925. this.id = "";
  32926. this.name = "";
  32927. this.shader = null;
  32928. this.surface = {};
  32929. this.sampler = {};
  32930. }
  32931. Effect.prototype.create = function () {
  32932. if ( this.shader === null ) {
  32933. return null;
  32934. }
  32935. };
  32936. Effect.prototype.parse = function ( element ) {
  32937. this.id = element.getAttribute( 'id' );
  32938. this.name = element.getAttribute( 'name' );
  32939. extractDoubleSided( this, element );
  32940. this.shader = null;
  32941. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32942. var child = element.childNodes[ i ];
  32943. if ( child.nodeType != 1 ) continue;
  32944. switch ( child.nodeName ) {
  32945. case 'profile_COMMON':
  32946. this.parseTechnique( this.parseProfileCOMMON( child ) );
  32947. break;
  32948. default:
  32949. break;
  32950. }
  32951. }
  32952. return this;
  32953. };
  32954. Effect.prototype.parseNewparam = function ( element ) {
  32955. var sid = element.getAttribute( 'sid' );
  32956. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32957. var child = element.childNodes[ i ];
  32958. if ( child.nodeType != 1 ) continue;
  32959. switch ( child.nodeName ) {
  32960. case 'surface':
  32961. this.surface[sid] = ( new Surface( this ) ).parse( child );
  32962. break;
  32963. case 'sampler2D':
  32964. this.sampler[sid] = ( new Sampler2D( this ) ).parse( child );
  32965. break;
  32966. case 'extra':
  32967. break;
  32968. default:
  32969. console.log( child.nodeName );
  32970. break;
  32971. }
  32972. }
  32973. };
  32974. Effect.prototype.parseProfileCOMMON = function ( element ) {
  32975. var technique;
  32976. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  32977. var child = element.childNodes[ i ];
  32978. if ( child.nodeType != 1 ) continue;
  32979. switch ( child.nodeName ) {
  32980. case 'profile_COMMON':
  32981. this.parseProfileCOMMON( child );
  32982. break;
  32983. case 'technique':
  32984. technique = child;
  32985. break;
  32986. case 'newparam':
  32987. this.parseNewparam( child );
  32988. break;
  32989. case 'image':
  32990. var _image = ( new _Image() ).parse( child );
  32991. images[ _image.id ] = _image;
  32992. break;
  32993. case 'extra':
  32994. break;
  32995. default:
  32996. console.log( child.nodeName );
  32997. break;
  32998. }
  32999. }
  33000. return technique;
  33001. };
  33002. Effect.prototype.parseTechnique = function ( element ) {
  33003. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33004. var child = element.childNodes[i];
  33005. if ( child.nodeType != 1 ) continue;
  33006. switch ( child.nodeName ) {
  33007. case 'constant':
  33008. case 'lambert':
  33009. case 'blinn':
  33010. case 'phong':
  33011. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  33012. break;
  33013. case 'extra':
  33014. this.parseExtra(child);
  33015. break;
  33016. default:
  33017. break;
  33018. }
  33019. }
  33020. };
  33021. Effect.prototype.parseExtra = function ( element ) {
  33022. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33023. var child = element.childNodes[i];
  33024. if ( child.nodeType != 1 ) continue;
  33025. switch ( child.nodeName ) {
  33026. case 'technique':
  33027. this.parseExtraTechnique( child );
  33028. break;
  33029. default:
  33030. break;
  33031. }
  33032. }
  33033. };
  33034. Effect.prototype.parseExtraTechnique = function ( element ) {
  33035. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33036. var child = element.childNodes[i];
  33037. if ( child.nodeType != 1 ) continue;
  33038. switch ( child.nodeName ) {
  33039. case 'bump':
  33040. this.shader.parse( element );
  33041. break;
  33042. default:
  33043. break;
  33044. }
  33045. }
  33046. };
  33047. function InstanceEffect () {
  33048. this.url = "";
  33049. }
  33050. InstanceEffect.prototype.parse = function ( element ) {
  33051. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  33052. return this;
  33053. };
  33054. function Animation() {
  33055. this.id = "";
  33056. this.name = "";
  33057. this.source = {};
  33058. this.sampler = [];
  33059. this.channel = [];
  33060. }
  33061. Animation.prototype.parse = function ( element ) {
  33062. this.id = element.getAttribute( 'id' );
  33063. this.name = element.getAttribute( 'name' );
  33064. this.source = {};
  33065. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33066. var child = element.childNodes[ i ];
  33067. if ( child.nodeType != 1 ) continue;
  33068. switch ( child.nodeName ) {
  33069. case 'animation':
  33070. var anim = ( new Animation() ).parse( child );
  33071. for ( var src in anim.source ) {
  33072. this.source[ src ] = anim.source[ src ];
  33073. }
  33074. for ( var j = 0; j < anim.channel.length; j ++ ) {
  33075. this.channel.push( anim.channel[ j ] );
  33076. this.sampler.push( anim.sampler[ j ] );
  33077. }
  33078. break;
  33079. case 'source':
  33080. var src = ( new Source() ).parse( child );
  33081. this.source[ src.id ] = src;
  33082. break;
  33083. case 'sampler':
  33084. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  33085. break;
  33086. case 'channel':
  33087. this.channel.push( ( new Channel( this ) ).parse( child ) );
  33088. break;
  33089. default:
  33090. break;
  33091. }
  33092. }
  33093. return this;
  33094. };
  33095. function Channel( animation ) {
  33096. this.animation = animation;
  33097. this.source = "";
  33098. this.target = "";
  33099. this.fullSid = null;
  33100. this.sid = null;
  33101. this.dotSyntax = null;
  33102. this.arrSyntax = null;
  33103. this.arrIndices = null;
  33104. this.member = null;
  33105. }
  33106. Channel.prototype.parse = function ( element ) {
  33107. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  33108. this.target = element.getAttribute( 'target' );
  33109. var parts = this.target.split( '/' );
  33110. var id = parts.shift();
  33111. var sid = parts.shift();
  33112. var dotSyntax = ( sid.indexOf(".") >= 0 );
  33113. var arrSyntax = ( sid.indexOf("(") >= 0 );
  33114. if ( dotSyntax ) {
  33115. parts = sid.split(".");
  33116. this.sid = parts.shift();
  33117. this.member = parts.shift();
  33118. } else if ( arrSyntax ) {
  33119. var arrIndices = sid.split("(");
  33120. this.sid = arrIndices.shift();
  33121. for (var j = 0; j < arrIndices.length; j ++ ) {
  33122. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  33123. }
  33124. this.arrIndices = arrIndices;
  33125. } else {
  33126. this.sid = sid;
  33127. }
  33128. this.fullSid = sid;
  33129. this.dotSyntax = dotSyntax;
  33130. this.arrSyntax = arrSyntax;
  33131. return this;
  33132. };
  33133. function Sampler ( animation ) {
  33134. this.id = "";
  33135. this.animation = animation;
  33136. this.inputs = [];
  33137. this.input = null;
  33138. this.output = null;
  33139. this.strideOut = null;
  33140. this.interpolation = null;
  33141. this.startTime = null;
  33142. this.endTime = null;
  33143. this.duration = 0;
  33144. }
  33145. Sampler.prototype.parse = function ( element ) {
  33146. this.id = element.getAttribute( 'id' );
  33147. this.inputs = [];
  33148. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33149. var child = element.childNodes[ i ];
  33150. if ( child.nodeType != 1 ) continue;
  33151. switch ( child.nodeName ) {
  33152. case 'input':
  33153. this.inputs.push( (new Input()).parse( child ) );
  33154. break;
  33155. default:
  33156. break;
  33157. }
  33158. }
  33159. return this;
  33160. };
  33161. Sampler.prototype.create = function () {
  33162. for ( var i = 0; i < this.inputs.length; i ++ ) {
  33163. var input = this.inputs[ i ];
  33164. var source = this.animation.source[ input.source ];
  33165. switch ( input.semantic ) {
  33166. case 'INPUT':
  33167. this.input = source.read();
  33168. break;
  33169. case 'OUTPUT':
  33170. this.output = source.read();
  33171. this.strideOut = source.accessor.stride;
  33172. break;
  33173. case 'INTERPOLATION':
  33174. this.interpolation = source.read();
  33175. break;
  33176. case 'IN_TANGENT':
  33177. break;
  33178. case 'OUT_TANGENT':
  33179. break;
  33180. default:
  33181. console.log(input.semantic);
  33182. break;
  33183. }
  33184. }
  33185. this.startTime = 0;
  33186. this.endTime = 0;
  33187. this.duration = 0;
  33188. if ( this.input.length ) {
  33189. this.startTime = 100000000;
  33190. this.endTime = -100000000;
  33191. for ( var i = 0; i < this.input.length; i ++ ) {
  33192. this.startTime = Math.min( this.startTime, this.input[ i ] );
  33193. this.endTime = Math.max( this.endTime, this.input[ i ] );
  33194. }
  33195. this.duration = this.endTime - this.startTime;
  33196. }
  33197. };
  33198. Sampler.prototype.getData = function ( type, ndx, member ) {
  33199. var data;
  33200. if ( type === 'matrix' && this.strideOut === 16 ) {
  33201. data = this.output[ ndx ];
  33202. } else if ( this.strideOut > 1 ) {
  33203. data = [];
  33204. ndx *= this.strideOut;
  33205. for ( var i = 0; i < this.strideOut; ++ i ) {
  33206. data[ i ] = this.output[ ndx + i ];
  33207. }
  33208. if ( this.strideOut === 3 ) {
  33209. switch ( type ) {
  33210. case 'rotate':
  33211. case 'translate':
  33212. fixCoords( data, -1 );
  33213. break;
  33214. case 'scale':
  33215. fixCoords( data, 1 );
  33216. break;
  33217. }
  33218. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  33219. fixCoords( data, -1 );
  33220. }
  33221. } else {
  33222. data = this.output[ ndx ];
  33223. if ( member && type === 'translate' ) {
  33224. data = getConvertedTranslation( member, data );
  33225. }
  33226. }
  33227. return data;
  33228. };
  33229. function Key ( time ) {
  33230. this.targets = [];
  33231. this.time = time;
  33232. }
  33233. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  33234. this.targets.push( {
  33235. sid: fullSid,
  33236. member: member,
  33237. transform: transform,
  33238. data: data
  33239. } );
  33240. };
  33241. Key.prototype.apply = function ( opt_sid ) {
  33242. for ( var i = 0; i < this.targets.length; ++ i ) {
  33243. var target = this.targets[ i ];
  33244. if ( !opt_sid || target.sid === opt_sid ) {
  33245. target.transform.update( target.data, target.member );
  33246. }
  33247. }
  33248. };
  33249. Key.prototype.getTarget = function ( fullSid ) {
  33250. for ( var i = 0; i < this.targets.length; ++ i ) {
  33251. if ( this.targets[ i ].sid === fullSid ) {
  33252. return this.targets[ i ];
  33253. }
  33254. }
  33255. return null;
  33256. };
  33257. Key.prototype.hasTarget = function ( fullSid ) {
  33258. for ( var i = 0; i < this.targets.length; ++ i ) {
  33259. if ( this.targets[ i ].sid === fullSid ) {
  33260. return true;
  33261. }
  33262. }
  33263. return false;
  33264. };
  33265. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  33266. Key.prototype.interpolate = function ( nextKey, time ) {
  33267. for ( var i = 0, l = this.targets.length; i < l; i ++ ) {
  33268. var target = this.targets[ i ],
  33269. nextTarget = nextKey.getTarget( target.sid ),
  33270. data;
  33271. if ( target.transform.type !== 'matrix' && nextTarget ) {
  33272. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  33273. nextData = nextTarget.data,
  33274. prevData = target.data;
  33275. if ( scale < 0 ) scale = 0;
  33276. if ( scale > 1 ) scale = 1;
  33277. if ( prevData.length ) {
  33278. data = [];
  33279. for ( var j = 0; j < prevData.length; ++ j ) {
  33280. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  33281. }
  33282. } else {
  33283. data = prevData + ( nextData - prevData ) * scale;
  33284. }
  33285. } else {
  33286. data = target.data;
  33287. }
  33288. target.transform.update( data, target.member );
  33289. }
  33290. };
  33291. // Camera
  33292. function Camera() {
  33293. this.id = "";
  33294. this.name = "";
  33295. this.technique = "";
  33296. }
  33297. Camera.prototype.parse = function ( element ) {
  33298. this.id = element.getAttribute( 'id' );
  33299. this.name = element.getAttribute( 'name' );
  33300. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33301. var child = element.childNodes[ i ];
  33302. if ( child.nodeType != 1 ) continue;
  33303. switch ( child.nodeName ) {
  33304. case 'optics':
  33305. this.parseOptics( child );
  33306. break;
  33307. default:
  33308. break;
  33309. }
  33310. }
  33311. return this;
  33312. };
  33313. Camera.prototype.parseOptics = function ( element ) {
  33314. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33315. if ( element.childNodes[ i ].nodeName === 'technique_common' ) {
  33316. var technique = element.childNodes[ i ];
  33317. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  33318. this.technique = technique.childNodes[ j ].nodeName;
  33319. if ( this.technique === 'perspective' ) {
  33320. var perspective = technique.childNodes[ j ];
  33321. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  33322. var param = perspective.childNodes[ k ];
  33323. switch ( param.nodeName ) {
  33324. case 'yfov':
  33325. this.yfov = param.textContent;
  33326. break;
  33327. case 'xfov':
  33328. this.xfov = param.textContent;
  33329. break;
  33330. case 'znear':
  33331. this.znear = param.textContent;
  33332. break;
  33333. case 'zfar':
  33334. this.zfar = param.textContent;
  33335. break;
  33336. case 'aspect_ratio':
  33337. this.aspect_ratio = param.textContent;
  33338. break;
  33339. }
  33340. }
  33341. } else if ( this.technique === 'orthographic' ) {
  33342. var orthographic = technique.childNodes[ j ];
  33343. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  33344. var param = orthographic.childNodes[ k ];
  33345. switch ( param.nodeName ) {
  33346. case 'xmag':
  33347. this.xmag = param.textContent;
  33348. break;
  33349. case 'ymag':
  33350. this.ymag = param.textContent;
  33351. break;
  33352. case 'znear':
  33353. this.znear = param.textContent;
  33354. break;
  33355. case 'zfar':
  33356. this.zfar = param.textContent;
  33357. break;
  33358. case 'aspect_ratio':
  33359. this.aspect_ratio = param.textContent;
  33360. break;
  33361. }
  33362. }
  33363. }
  33364. }
  33365. }
  33366. }
  33367. return this;
  33368. };
  33369. function InstanceCamera() {
  33370. this.url = "";
  33371. }
  33372. InstanceCamera.prototype.parse = function ( element ) {
  33373. this.url = element.getAttribute('url').replace(/^#/, '');
  33374. return this;
  33375. };
  33376. // Light
  33377. function Light() {
  33378. this.id = "";
  33379. this.name = "";
  33380. this.technique = "";
  33381. }
  33382. Light.prototype.parse = function ( element ) {
  33383. this.id = element.getAttribute( 'id' );
  33384. this.name = element.getAttribute( 'name' );
  33385. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33386. var child = element.childNodes[ i ];
  33387. if ( child.nodeType != 1 ) continue;
  33388. switch ( child.nodeName ) {
  33389. case 'technique_common':
  33390. this.parseCommon( child );
  33391. break;
  33392. case 'technique':
  33393. this.parseTechnique( child );
  33394. break;
  33395. default:
  33396. break;
  33397. }
  33398. }
  33399. return this;
  33400. };
  33401. Light.prototype.parseCommon = function ( element ) {
  33402. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33403. switch ( element.childNodes[ i ].nodeName ) {
  33404. case 'directional':
  33405. case 'point':
  33406. case 'spot':
  33407. case 'ambient':
  33408. this.technique = element.childNodes[ i ].nodeName;
  33409. var light = element.childNodes[ i ];
  33410. for ( var j = 0; j < light.childNodes.length; j ++ ) {
  33411. var child = light.childNodes[j];
  33412. switch ( child.nodeName ) {
  33413. case 'color':
  33414. var rgba = _floats( child.textContent );
  33415. this.color = new THREE.Color(0);
  33416. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  33417. this.color.a = rgba[3];
  33418. break;
  33419. case 'falloff_angle':
  33420. this.falloff_angle = parseFloat( child.textContent );
  33421. break;
  33422. case 'quadratic_attenuation':
  33423. var f = parseFloat( child.textContent );
  33424. this.distance = f ? Math.sqrt( 1 / f ) : 0;
  33425. }
  33426. }
  33427. }
  33428. }
  33429. return this;
  33430. };
  33431. Light.prototype.parseTechnique = function ( element ) {
  33432. this.profile = element.getAttribute( 'profile' );
  33433. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  33434. var child = element.childNodes[ i ];
  33435. switch ( child.nodeName ) {
  33436. case 'intensity':
  33437. this.intensity = parseFloat(child.textContent);
  33438. break;
  33439. }
  33440. }
  33441. return this;
  33442. };
  33443. function InstanceLight() {
  33444. this.url = "";
  33445. }
  33446. InstanceLight.prototype.parse = function ( element ) {
  33447. this.url = element.getAttribute('url').replace(/^#/, '');
  33448. return this;
  33449. };
  33450. function KinematicsModel( ) {
  33451. this.id = '';
  33452. this.name = '';
  33453. this.joints = [];
  33454. this.links = [];
  33455. }
  33456. KinematicsModel.prototype.parse = function( element ) {
  33457. this.id = element.getAttribute('id');
  33458. this.name = element.getAttribute('name');
  33459. this.joints = [];
  33460. this.links = [];
  33461. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33462. var child = element.childNodes[ i ];
  33463. if ( child.nodeType != 1 ) continue;
  33464. switch ( child.nodeName ) {
  33465. case 'technique_common':
  33466. this.parseCommon(child);
  33467. break;
  33468. default:
  33469. break;
  33470. }
  33471. }
  33472. return this;
  33473. };
  33474. KinematicsModel.prototype.parseCommon = function( element ) {
  33475. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33476. var child = element.childNodes[ i ];
  33477. if ( child.nodeType != 1 ) continue;
  33478. switch ( element.childNodes[ i ].nodeName ) {
  33479. case 'joint':
  33480. this.joints.push( (new Joint()).parse(child) );
  33481. break;
  33482. case 'link':
  33483. this.links.push( (new Link()).parse(child) );
  33484. break;
  33485. default:
  33486. break;
  33487. }
  33488. }
  33489. return this;
  33490. };
  33491. function Joint( ) {
  33492. this.sid = '';
  33493. this.name = '';
  33494. this.axis = new THREE.Vector3();
  33495. this.limits = {
  33496. min: 0,
  33497. max: 0
  33498. };
  33499. this.type = '';
  33500. this.static = false;
  33501. this.zeroPosition = 0.0;
  33502. this.middlePosition = 0.0;
  33503. }
  33504. Joint.prototype.parse = function( element ) {
  33505. this.sid = element.getAttribute('sid');
  33506. this.name = element.getAttribute('name');
  33507. this.axis = new THREE.Vector3();
  33508. this.limits = {
  33509. min: 0,
  33510. max: 0
  33511. };
  33512. this.type = '';
  33513. this.static = false;
  33514. this.zeroPosition = 0.0;
  33515. this.middlePosition = 0.0;
  33516. var axisElement = element.querySelector('axis');
  33517. var _axis = _floats(axisElement.textContent);
  33518. this.axis = getConvertedVec3(_axis, 0);
  33519. var min = element.querySelector('limits min') ? parseFloat(element.querySelector('limits min').textContent) : -360;
  33520. var max = element.querySelector('limits max') ? parseFloat(element.querySelector('limits max').textContent) : 360;
  33521. this.limits = {
  33522. min: min,
  33523. max: max
  33524. };
  33525. var jointTypes = [ 'prismatic', 'revolute' ];
  33526. for (var i = 0; i < jointTypes.length; i ++ ) {
  33527. var type = jointTypes[ i ];
  33528. var jointElement = element.querySelector(type);
  33529. if ( jointElement ) {
  33530. this.type = type;
  33531. }
  33532. }
  33533. // if the min is equal to or somehow greater than the max, consider the joint static
  33534. if ( this.limits.min >= this.limits.max ) {
  33535. this.static = true;
  33536. }
  33537. this.middlePosition = (this.limits.min + this.limits.max) / 2.0;
  33538. return this;
  33539. };
  33540. function Link( ) {
  33541. this.sid = '';
  33542. this.name = '';
  33543. this.transforms = [];
  33544. this.attachments = [];
  33545. }
  33546. Link.prototype.parse = function( element ) {
  33547. this.sid = element.getAttribute('sid');
  33548. this.name = element.getAttribute('name');
  33549. this.transforms = [];
  33550. this.attachments = [];
  33551. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33552. var child = element.childNodes[ i ];
  33553. if ( child.nodeType != 1 ) continue;
  33554. switch ( child.nodeName ) {
  33555. case 'attachment_full':
  33556. this.attachments.push( (new Attachment()).parse(child) );
  33557. break;
  33558. case 'rotate':
  33559. case 'translate':
  33560. case 'matrix':
  33561. this.transforms.push( (new Transform()).parse(child) );
  33562. break;
  33563. default:
  33564. break;
  33565. }
  33566. }
  33567. return this;
  33568. };
  33569. function Attachment( ) {
  33570. this.joint = '';
  33571. this.transforms = [];
  33572. this.links = [];
  33573. }
  33574. Attachment.prototype.parse = function( element ) {
  33575. this.joint = element.getAttribute('joint').split('/').pop();
  33576. this.links = [];
  33577. for (var i = 0; i < element.childNodes.length; i ++ ) {
  33578. var child = element.childNodes[ i ];
  33579. if ( child.nodeType != 1 ) continue;
  33580. switch ( child.nodeName ) {
  33581. case 'link':
  33582. this.links.push( (new Link()).parse(child) );
  33583. break;
  33584. case 'rotate':
  33585. case 'translate':
  33586. case 'matrix':
  33587. this.transforms.push( (new Transform()).parse(child) );
  33588. break;
  33589. default:
  33590. break;
  33591. }
  33592. }
  33593. return this;
  33594. };
  33595. function _source( element ) {
  33596. var id = element.getAttribute( 'id' );
  33597. if ( sources[ id ] != undefined ) {
  33598. return sources[ id ];
  33599. }
  33600. sources[ id ] = ( new Source(id )).parse( element );
  33601. return sources[ id ];
  33602. }
  33603. function _nsResolver( nsPrefix ) {
  33604. if ( nsPrefix === "dae" ) {
  33605. return "http://www.collada.org/2005/11/COLLADASchema";
  33606. }
  33607. return null;
  33608. }
  33609. function _bools( str ) {
  33610. var raw = _strings( str );
  33611. var data = [];
  33612. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33613. data.push( (raw[i] === 'true' || raw[i] === '1') ? true : false );
  33614. }
  33615. return data;
  33616. }
  33617. function _floats( str ) {
  33618. var raw = _strings(str);
  33619. var data = [];
  33620. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33621. data.push( parseFloat( raw[ i ] ) );
  33622. }
  33623. return data;
  33624. }
  33625. function _ints( str ) {
  33626. var raw = _strings( str );
  33627. var data = [];
  33628. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  33629. data.push( parseInt( raw[ i ], 10 ) );
  33630. }
  33631. return data;
  33632. }
  33633. function _strings( str ) {
  33634. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  33635. }
  33636. function _trimString( str ) {
  33637. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  33638. }
  33639. function _attr_as_float( element, name, defaultValue ) {
  33640. if ( element.hasAttribute( name ) ) {
  33641. return parseFloat( element.getAttribute( name ) );
  33642. } else {
  33643. return defaultValue;
  33644. }
  33645. }
  33646. function _attr_as_int( element, name, defaultValue ) {
  33647. if ( element.hasAttribute( name ) ) {
  33648. return parseInt( element.getAttribute( name ), 10) ;
  33649. } else {
  33650. return defaultValue;
  33651. }
  33652. }
  33653. function _attr_as_string( element, name, defaultValue ) {
  33654. if ( element.hasAttribute( name ) ) {
  33655. return element.getAttribute( name );
  33656. } else {
  33657. return defaultValue;
  33658. }
  33659. }
  33660. function _format_float( f, num ) {
  33661. if ( f === undefined ) {
  33662. var s = '0.';
  33663. while ( s.length < num + 2 ) {
  33664. s += '0';
  33665. }
  33666. return s;
  33667. }
  33668. num = num || 2;
  33669. var parts = f.toString().split( '.' );
  33670. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  33671. while ( parts[ 1 ].length < num ) {
  33672. parts[ 1 ] += '0';
  33673. }
  33674. return parts.join( '.' );
  33675. }
  33676. function loadTextureImage ( texture, url ) {
  33677. var loader = new THREE.ImageLoader();
  33678. loader.load( url, function ( image ) {
  33679. texture.image = image;
  33680. texture.needsUpdate = true;
  33681. } );
  33682. }
  33683. function extractDoubleSided( obj, element ) {
  33684. obj.doubleSided = false;
  33685. var node = element.querySelectorAll('extra double_sided')[0];
  33686. if ( node ) {
  33687. if ( node && parseInt( node.textContent, 10 ) === 1 ) {
  33688. obj.doubleSided = true;
  33689. }
  33690. }
  33691. }
  33692. // Up axis conversion
  33693. function setUpConversion() {
  33694. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33695. upConversion = null;
  33696. } else {
  33697. switch ( colladaUp ) {
  33698. case 'X':
  33699. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  33700. break;
  33701. case 'Y':
  33702. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  33703. break;
  33704. case 'Z':
  33705. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  33706. break;
  33707. }
  33708. }
  33709. }
  33710. function fixCoords( data, sign ) {
  33711. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33712. return;
  33713. }
  33714. switch ( upConversion ) {
  33715. case 'XtoY':
  33716. var tmp = data[ 0 ];
  33717. data[ 0 ] = sign * data[ 1 ];
  33718. data[ 1 ] = tmp;
  33719. break;
  33720. case 'XtoZ':
  33721. var tmp = data[ 2 ];
  33722. data[ 2 ] = data[ 1 ];
  33723. data[ 1 ] = data[ 0 ];
  33724. data[ 0 ] = tmp;
  33725. break;
  33726. case 'YtoX':
  33727. var tmp = data[ 0 ];
  33728. data[ 0 ] = data[ 1 ];
  33729. data[ 1 ] = sign * tmp;
  33730. break;
  33731. case 'YtoZ':
  33732. var tmp = data[ 1 ];
  33733. data[ 1 ] = sign * data[ 2 ];
  33734. data[ 2 ] = tmp;
  33735. break;
  33736. case 'ZtoX':
  33737. var tmp = data[ 0 ];
  33738. data[ 0 ] = data[ 1 ];
  33739. data[ 1 ] = data[ 2 ];
  33740. data[ 2 ] = tmp;
  33741. break;
  33742. case 'ZtoY':
  33743. var tmp = data[ 1 ];
  33744. data[ 1 ] = data[ 2 ];
  33745. data[ 2 ] = sign * tmp;
  33746. break;
  33747. }
  33748. }
  33749. function getConvertedTranslation( axis, data ) {
  33750. if ( options.convertUpAxis !== true || colladaUp === options.upAxis ) {
  33751. return data;
  33752. }
  33753. switch ( axis ) {
  33754. case 'X':
  33755. data = upConversion === 'XtoY' ? data * -1 : data;
  33756. break;
  33757. case 'Y':
  33758. data = upConversion === 'YtoZ' || upConversion === 'YtoX' ? data * -1 : data;
  33759. break;
  33760. case 'Z':
  33761. data = upConversion === 'ZtoY' ? data * -1 : data ;
  33762. break;
  33763. default:
  33764. break;
  33765. }
  33766. return data;
  33767. }
  33768. function getConvertedVec3( data, offset ) {
  33769. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  33770. fixCoords( arr, -1 );
  33771. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  33772. }
  33773. function getConvertedMat4( data ) {
  33774. if ( options.convertUpAxis ) {
  33775. // First fix rotation and scale
  33776. // Columns first
  33777. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  33778. fixCoords( arr, -1 );
  33779. data[ 0 ] = arr[ 0 ];
  33780. data[ 4 ] = arr[ 1 ];
  33781. data[ 8 ] = arr[ 2 ];
  33782. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  33783. fixCoords( arr, -1 );
  33784. data[ 1 ] = arr[ 0 ];
  33785. data[ 5 ] = arr[ 1 ];
  33786. data[ 9 ] = arr[ 2 ];
  33787. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  33788. fixCoords( arr, -1 );
  33789. data[ 2 ] = arr[ 0 ];
  33790. data[ 6 ] = arr[ 1 ];
  33791. data[ 10 ] = arr[ 2 ];
  33792. // Rows second
  33793. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  33794. fixCoords( arr, -1 );
  33795. data[ 0 ] = arr[ 0 ];
  33796. data[ 1 ] = arr[ 1 ];
  33797. data[ 2 ] = arr[ 2 ];
  33798. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  33799. fixCoords( arr, -1 );
  33800. data[ 4 ] = arr[ 0 ];
  33801. data[ 5 ] = arr[ 1 ];
  33802. data[ 6 ] = arr[ 2 ];
  33803. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  33804. fixCoords( arr, -1 );
  33805. data[ 8 ] = arr[ 0 ];
  33806. data[ 9 ] = arr[ 1 ];
  33807. data[ 10 ] = arr[ 2 ];
  33808. // Now fix translation
  33809. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  33810. fixCoords( arr, -1 );
  33811. data[ 3 ] = arr[ 0 ];
  33812. data[ 7 ] = arr[ 1 ];
  33813. data[ 11 ] = arr[ 2 ];
  33814. }
  33815. return new THREE.Matrix4().set(
  33816. data[0], data[1], data[2], data[3],
  33817. data[4], data[5], data[6], data[7],
  33818. data[8], data[9], data[10], data[11],
  33819. data[12], data[13], data[14], data[15]
  33820. );
  33821. }
  33822. function getConvertedIndex( index ) {
  33823. if ( index > -1 && index < 3 ) {
  33824. var members = [ 'X', 'Y', 'Z' ],
  33825. indices = { X: 0, Y: 1, Z: 2 };
  33826. index = getConvertedMember( members[ index ] );
  33827. index = indices[ index ];
  33828. }
  33829. return index;
  33830. }
  33831. function getConvertedMember( member ) {
  33832. if ( options.convertUpAxis ) {
  33833. switch ( member ) {
  33834. case 'X':
  33835. switch ( upConversion ) {
  33836. case 'XtoY':
  33837. case 'XtoZ':
  33838. case 'YtoX':
  33839. member = 'Y';
  33840. break;
  33841. case 'ZtoX':
  33842. member = 'Z';
  33843. break;
  33844. }
  33845. break;
  33846. case 'Y':
  33847. switch ( upConversion ) {
  33848. case 'XtoY':
  33849. case 'YtoX':
  33850. case 'ZtoX':
  33851. member = 'X';
  33852. break;
  33853. case 'XtoZ':
  33854. case 'YtoZ':
  33855. case 'ZtoY':
  33856. member = 'Z';
  33857. break;
  33858. }
  33859. break;
  33860. case 'Z':
  33861. switch ( upConversion ) {
  33862. case 'XtoZ':
  33863. member = 'X';
  33864. break;
  33865. case 'YtoZ':
  33866. case 'ZtoX':
  33867. case 'ZtoY':
  33868. member = 'Y';
  33869. break;
  33870. }
  33871. break;
  33872. }
  33873. }
  33874. return member;
  33875. }
  33876. return {
  33877. load: load,
  33878. parse: parse,
  33879. setPreferredShading: setPreferredShading,
  33880. applySkin: applySkin,
  33881. geometries : geometries,
  33882. options: options
  33883. };
  33884. };
  33885. },{}],45:[function(_dereq_,module,exports){
  33886. /**
  33887. * @author Rich Tibbett / https://github.com/richtr
  33888. * @author mrdoob / http://mrdoob.com/
  33889. * @author Tony Parisi / http://www.tonyparisi.com/
  33890. */
  33891. THREE.GLTFLoader = ( function () {
  33892. function GLTFLoader( manager ) {
  33893. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  33894. }
  33895. GLTFLoader.prototype = {
  33896. constructor: GLTFLoader,
  33897. load: function ( url, onLoad, onProgress, onError ) {
  33898. var scope = this;
  33899. var path = this.path && ( typeof this.path === "string" ) ? this.path : THREE.Loader.prototype.extractUrlBase( url );
  33900. var loader = new THREE.FileLoader( scope.manager );
  33901. loader.load( url, function ( text ) {
  33902. scope.parse( JSON.parse( text ), onLoad, path );
  33903. }, onProgress, onError );
  33904. },
  33905. setCrossOrigin: function ( value ) {
  33906. this.crossOrigin = value;
  33907. },
  33908. setPath: function ( value ) {
  33909. this.path = value;
  33910. },
  33911. parse: function ( json, callback, path ) {
  33912. console.time( 'GLTFLoader' );
  33913. var parser = new GLTFParser( json, {
  33914. path: path || this.path,
  33915. crossOrigin: !! this.crossOrigin
  33916. } );
  33917. parser.parse( function ( scene, cameras, animations ) {
  33918. console.timeEnd( 'GLTFLoader' );
  33919. var glTF = {
  33920. "scene": scene,
  33921. "cameras": cameras,
  33922. "animations": animations
  33923. };
  33924. callback( glTF );
  33925. } );
  33926. }
  33927. };
  33928. /* GLTFREGISTRY */
  33929. function GLTFRegistry() {
  33930. var objects = {};
  33931. return {
  33932. get: function ( key ) {
  33933. return objects[ key ];
  33934. },
  33935. add: function ( key, object ) {
  33936. objects[ key ] = object;
  33937. },
  33938. remove: function ( key ) {
  33939. delete objects[ key ];
  33940. },
  33941. removeAll: function () {
  33942. objects = {};
  33943. },
  33944. update: function ( scene, camera ) {
  33945. for ( var name in objects ) {
  33946. var object = objects[ name ];
  33947. if ( object.update ) {
  33948. object.update( scene, camera );
  33949. }
  33950. }
  33951. }
  33952. };
  33953. }
  33954. /* GLTFSHADERS */
  33955. GLTFLoader.Shaders = new GLTFRegistry();
  33956. /* GLTFSHADER */
  33957. function GLTFShader( targetNode, allNodes ) {
  33958. var boundUniforms = {};
  33959. // bind each uniform to its source node
  33960. var uniforms = targetNode.material.uniforms;
  33961. for ( var uniformId in uniforms ) {
  33962. var uniform = uniforms[ uniformId ];
  33963. if ( uniform.semantic ) {
  33964. var sourceNodeRef = uniform.node;
  33965. var sourceNode = targetNode;
  33966. if ( sourceNodeRef ) {
  33967. sourceNode = allNodes[ sourceNodeRef ];
  33968. }
  33969. boundUniforms[ uniformId ] = {
  33970. semantic: uniform.semantic,
  33971. sourceNode: sourceNode,
  33972. targetNode: targetNode,
  33973. uniform: uniform
  33974. };
  33975. }
  33976. }
  33977. this.boundUniforms = boundUniforms;
  33978. this._m4 = new THREE.Matrix4();
  33979. }
  33980. // Update - update all the uniform values
  33981. GLTFShader.prototype.update = function ( scene, camera ) {
  33982. // update scene graph
  33983. scene.updateMatrixWorld();
  33984. // update camera matrices and frustum
  33985. camera.updateMatrixWorld();
  33986. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  33987. var boundUniforms = this.boundUniforms;
  33988. for ( var name in boundUniforms ) {
  33989. var boundUniform = boundUniforms[ name ];
  33990. switch ( boundUniform.semantic ) {
  33991. case "MODELVIEW":
  33992. var m4 = boundUniform.uniform.value;
  33993. m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  33994. break;
  33995. case "MODELVIEWINVERSETRANSPOSE":
  33996. var m3 = boundUniform.uniform.value;
  33997. this._m4.multiplyMatrices( camera.matrixWorldInverse, boundUniform.sourceNode.matrixWorld );
  33998. m3.getNormalMatrix( this._m4 );
  33999. break;
  34000. case "PROJECTION":
  34001. var m4 = boundUniform.uniform.value;
  34002. m4.copy( camera.projectionMatrix );
  34003. break;
  34004. case "JOINTMATRIX":
  34005. var m4v = boundUniform.uniform.value;
  34006. for ( var mi = 0; mi < m4v.length; mi ++ ) {
  34007. // So it goes like this:
  34008. // SkinnedMesh world matrix is already baked into MODELVIEW;
  34009. // transform joints to local space,
  34010. // then transform using joint's inverse
  34011. m4v[ mi ]
  34012. .getInverse( boundUniform.sourceNode.matrixWorld )
  34013. .multiply( boundUniform.targetNode.skeleton.bones[ mi ].matrixWorld )
  34014. .multiply( boundUniform.targetNode.skeleton.boneInverses[ mi ] )
  34015. .multiply( boundUniform.targetNode.bindMatrix );
  34016. }
  34017. break;
  34018. default :
  34019. console.warn( "Unhandled shader semantic: " + boundUniform.semantic );
  34020. break;
  34021. }
  34022. }
  34023. };
  34024. /* ANIMATION */
  34025. GLTFLoader.Animations = {
  34026. update: function () {
  34027. console.warn( 'THREE.GLTFLoader.Animation has been deprecated. Use THREE.AnimationMixer instead.' );
  34028. }
  34029. };
  34030. function createAnimation( name, interps ) {
  34031. var tracks = [];
  34032. for ( var i = 0, len = interps.length; i < len; i ++ ) {
  34033. var interp = interps[ i ];
  34034. // KeyframeTrack.optimize() will modify given 'times' and 'values'
  34035. // buffers before creating a truncated copy to keep. Because buffers may
  34036. // be reused by other tracks, make copies here.
  34037. interp.times = THREE.AnimationUtils.arraySlice( interp.times, 0 );
  34038. interp.values = THREE.AnimationUtils.arraySlice( interp.values, 0 );
  34039. interp.target.updateMatrix();
  34040. interp.target.matrixAutoUpdate = true;
  34041. tracks.push( new THREE.KeyframeTrack(
  34042. interp.name,
  34043. interp.times,
  34044. interp.values,
  34045. interp.type
  34046. ) );
  34047. }
  34048. return new THREE.AnimationClip( name, undefined, tracks );
  34049. }
  34050. /*********************************/
  34051. /********** INTERNALS ************/
  34052. /*********************************/
  34053. /* CONSTANTS */
  34054. var WEBGL_CONSTANTS = {
  34055. FLOAT: 5126,
  34056. //FLOAT_MAT2: 35674,
  34057. FLOAT_MAT3: 35675,
  34058. FLOAT_MAT4: 35676,
  34059. FLOAT_VEC2: 35664,
  34060. FLOAT_VEC3: 35665,
  34061. FLOAT_VEC4: 35666,
  34062. LINEAR: 9729,
  34063. REPEAT: 10497,
  34064. SAMPLER_2D: 35678,
  34065. TRIANGLES: 4,
  34066. UNSIGNED_BYTE: 5121,
  34067. UNSIGNED_SHORT: 5123,
  34068. VERTEX_SHADER: 35633,
  34069. FRAGMENT_SHADER: 35632
  34070. };
  34071. var WEBGL_TYPE = {
  34072. 5126: Number,
  34073. //35674: THREE.Matrix2,
  34074. 35675: THREE.Matrix3,
  34075. 35676: THREE.Matrix4,
  34076. 35664: THREE.Vector2,
  34077. 35665: THREE.Vector3,
  34078. 35666: THREE.Vector4,
  34079. 35678: THREE.Texture
  34080. };
  34081. var WEBGL_COMPONENT_TYPES = {
  34082. 5120: Int8Array,
  34083. 5121: Uint8Array,
  34084. 5122: Int16Array,
  34085. 5123: Uint16Array,
  34086. 5125: Uint32Array,
  34087. 5126: Float32Array
  34088. };
  34089. var WEBGL_FILTERS = {
  34090. 9728: THREE.NearestFilter,
  34091. 9729: THREE.LinearFilter,
  34092. 9984: THREE.NearestMipMapNearestFilter,
  34093. 9985: THREE.LinearMipMapNearestFilter,
  34094. 9986: THREE.NearestMipMapLinearFilter,
  34095. 9987: THREE.LinearMipMapLinearFilter
  34096. };
  34097. var WEBGL_WRAPPINGS = {
  34098. 33071: THREE.ClampToEdgeWrapping,
  34099. 33648: THREE.MirroredRepeatWrapping,
  34100. 10497: THREE.RepeatWrapping
  34101. };
  34102. var WEBGL_TYPE_SIZES = {
  34103. 'SCALAR': 1,
  34104. 'VEC2': 2,
  34105. 'VEC3': 3,
  34106. 'VEC4': 4,
  34107. 'MAT2': 4,
  34108. 'MAT3': 9,
  34109. 'MAT4': 16
  34110. };
  34111. var PATH_PROPERTIES = {
  34112. scale: 'scale',
  34113. translation: 'position',
  34114. rotation: 'quaternion'
  34115. };
  34116. var INTERPOLATION = {
  34117. LINEAR: THREE.InterpolateLinear,
  34118. STEP: THREE.InterpolateDiscrete
  34119. };
  34120. /* UTILITY FUNCTIONS */
  34121. function _each( object, callback, thisObj ) {
  34122. if ( !object ) {
  34123. return Promise.resolve();
  34124. }
  34125. var results;
  34126. var fns = [];
  34127. if ( Object.prototype.toString.call( object ) === '[object Array]' ) {
  34128. results = [];
  34129. var length = object.length;
  34130. for ( var idx = 0; idx < length; idx ++ ) {
  34131. var value = callback.call( thisObj || this, object[ idx ], idx );
  34132. if ( value ) {
  34133. fns.push( value );
  34134. if ( value instanceof Promise ) {
  34135. value.then( function( key, value ) {
  34136. results[ idx ] = value;
  34137. }.bind( this, key ));
  34138. } else {
  34139. results[ idx ] = value;
  34140. }
  34141. }
  34142. }
  34143. } else {
  34144. results = {};
  34145. for ( var key in object ) {
  34146. if ( object.hasOwnProperty( key ) ) {
  34147. var value = callback.call( thisObj || this, object[ key ], key );
  34148. if ( value ) {
  34149. fns.push( value );
  34150. if ( value instanceof Promise ) {
  34151. value.then( function( key, value ) {
  34152. results[ key ] = value;
  34153. }.bind( this, key ));
  34154. } else {
  34155. results[ key ] = value;
  34156. }
  34157. }
  34158. }
  34159. }
  34160. }
  34161. return Promise.all( fns ).then( function() {
  34162. return results;
  34163. });
  34164. }
  34165. function resolveURL( url, path ) {
  34166. // Invalid URL
  34167. if ( typeof url !== 'string' || url === '' )
  34168. return '';
  34169. // Absolute URL
  34170. if ( /^https?:\/\//i.test( url ) ) {
  34171. return url;
  34172. }
  34173. // Data URI
  34174. if ( /^data:.*,.*$/i.test( url ) ) {
  34175. return url;
  34176. }
  34177. // Relative URL
  34178. return ( path || '' ) + url;
  34179. }
  34180. // Three.js seems too dependent on attribute names so globally
  34181. // replace those in the shader code
  34182. function replaceTHREEShaderAttributes( shaderText, technique ) {
  34183. // Expected technique attributes
  34184. var attributes = {};
  34185. for ( var attributeId in technique.attributes ) {
  34186. var pname = technique.attributes[ attributeId ];
  34187. var param = technique.parameters[ pname ];
  34188. var atype = param.type;
  34189. var semantic = param.semantic;
  34190. attributes[ attributeId ] = {
  34191. type: atype,
  34192. semantic: semantic
  34193. };
  34194. }
  34195. // Figure out which attributes to change in technique
  34196. var shaderParams = technique.parameters;
  34197. var shaderAttributes = technique.attributes;
  34198. var params = {};
  34199. for ( var attributeId in attributes ) {
  34200. var pname = shaderAttributes[ attributeId ];
  34201. var shaderParam = shaderParams[ pname ];
  34202. var semantic = shaderParam.semantic;
  34203. if ( semantic ) {
  34204. params[ attributeId ] = shaderParam;
  34205. }
  34206. }
  34207. for ( var pname in params ) {
  34208. var param = params[ pname ];
  34209. var semantic = param.semantic;
  34210. var regEx = new RegExp( "\\b" + pname + "\\b", "g" );
  34211. switch ( semantic ) {
  34212. case "POSITION":
  34213. shaderText = shaderText.replace( regEx, 'position' );
  34214. break;
  34215. case "NORMAL":
  34216. shaderText = shaderText.replace( regEx, 'normal' );
  34217. break;
  34218. case 'TEXCOORD_0':
  34219. case 'TEXCOORD0':
  34220. case 'TEXCOORD':
  34221. shaderText = shaderText.replace( regEx, 'uv' );
  34222. break;
  34223. case "WEIGHT":
  34224. shaderText = shaderText.replace( regEx, 'skinWeight' );
  34225. break;
  34226. case "JOINT":
  34227. shaderText = shaderText.replace( regEx, 'skinIndex' );
  34228. break;
  34229. }
  34230. }
  34231. return shaderText;
  34232. }
  34233. // Deferred constructor for RawShaderMaterial types
  34234. function DeferredShaderMaterial( params ) {
  34235. this.isDeferredShaderMaterial = true;
  34236. this.params = params;
  34237. }
  34238. DeferredShaderMaterial.prototype.create = function () {
  34239. var uniforms = THREE.UniformsUtils.clone( this.params.uniforms );
  34240. for ( var uniformId in this.params.uniforms ) {
  34241. var originalUniform = this.params.uniforms[ uniformId ];
  34242. if ( originalUniform.value instanceof THREE.Texture ) {
  34243. uniforms[ uniformId ].value = originalUniform.value;
  34244. uniforms[ uniformId ].value.needsUpdate = true;
  34245. }
  34246. uniforms[ uniformId ].semantic = originalUniform.semantic;
  34247. uniforms[ uniformId ].node = originalUniform.node;
  34248. }
  34249. this.params.uniforms = uniforms;
  34250. return new THREE.RawShaderMaterial( this.params );
  34251. };
  34252. /* GLTF PARSER */
  34253. function GLTFParser( json, options ) {
  34254. this.json = json || {};
  34255. this.options = options || {};
  34256. // loader object cache
  34257. this.cache = new GLTFRegistry();
  34258. }
  34259. GLTFParser.prototype._withDependencies = function ( dependencies ) {
  34260. var _dependencies = {};
  34261. for ( var i = 0; i < dependencies.length; i ++ ) {
  34262. var dependency = dependencies[ i ];
  34263. var fnName = "load" + dependency.charAt( 0 ).toUpperCase() + dependency.slice( 1 );
  34264. var cached = this.cache.get( dependency );
  34265. if ( cached !== undefined ) {
  34266. _dependencies[ dependency ] = cached;
  34267. } else if ( this[ fnName ] ) {
  34268. var fn = this[ fnName ]();
  34269. this.cache.add( dependency, fn );
  34270. _dependencies[ dependency ] = fn;
  34271. }
  34272. }
  34273. return _each( _dependencies, function ( dependency ) {
  34274. return dependency;
  34275. } );
  34276. };
  34277. GLTFParser.prototype.parse = function ( callback ) {
  34278. var json = this.json;
  34279. // Clear the loader cache
  34280. this.cache.removeAll();
  34281. // Fire the callback on complete
  34282. this._withDependencies( [
  34283. "scenes",
  34284. "cameras",
  34285. "animations"
  34286. ] ).then( function ( dependencies ) {
  34287. var scene = dependencies.scenes[ json.scene ];
  34288. var cameras = [];
  34289. for ( var name in dependencies.cameras ) {
  34290. var camera = dependencies.cameras[ name ];
  34291. cameras.push( camera );
  34292. }
  34293. var animations = [];
  34294. for ( var name in dependencies.animations ) {
  34295. animations.push( dependencies.animations[ name ] );
  34296. }
  34297. callback( scene, cameras, animations );
  34298. } );
  34299. };
  34300. GLTFParser.prototype.loadShaders = function () {
  34301. var json = this.json;
  34302. var options = this.options;
  34303. return _each( json.shaders, function ( shader ) {
  34304. return new Promise( function ( resolve ) {
  34305. var loader = new THREE.FileLoader();
  34306. loader.responseType = 'text';
  34307. loader.load( resolveURL( shader.uri, options.path ), function ( shaderText ) {
  34308. resolve( shaderText );
  34309. } );
  34310. } );
  34311. } );
  34312. };
  34313. GLTFParser.prototype.loadBuffers = function () {
  34314. var json = this.json;
  34315. var options = this.options;
  34316. return _each( json.buffers, function ( buffer ) {
  34317. if ( buffer.type === 'arraybuffer' ) {
  34318. return new Promise( function ( resolve ) {
  34319. var loader = new THREE.FileLoader();
  34320. loader.responseType = 'arraybuffer';
  34321. loader.load( resolveURL( buffer.uri, options.path ), function ( buffer ) {
  34322. resolve( buffer );
  34323. } );
  34324. } );
  34325. }
  34326. } );
  34327. };
  34328. GLTFParser.prototype.loadBufferViews = function () {
  34329. var json = this.json;
  34330. return this._withDependencies( [
  34331. "buffers"
  34332. ] ).then( function ( dependencies ) {
  34333. return _each( json.bufferViews, function ( bufferView ) {
  34334. var arraybuffer = dependencies.buffers[ bufferView.buffer ];
  34335. return arraybuffer.slice( bufferView.byteOffset, bufferView.byteOffset + bufferView.byteLength );
  34336. } );
  34337. } );
  34338. };
  34339. GLTFParser.prototype.loadAccessors = function () {
  34340. var json = this.json;
  34341. return this._withDependencies( [
  34342. "bufferViews"
  34343. ] ).then( function ( dependencies ) {
  34344. return _each( json.accessors, function ( accessor ) {
  34345. var arraybuffer = dependencies.bufferViews[ accessor.bufferView ];
  34346. var itemSize = WEBGL_TYPE_SIZES[ accessor.type ];
  34347. var TypedArray = WEBGL_COMPONENT_TYPES[ accessor.componentType ];
  34348. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  34349. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  34350. var itemBytes = elementBytes * itemSize;
  34351. // The buffer is not interleaved if the stride is the item size in bytes.
  34352. if ( accessor.byteStride && accessor.byteStride !== itemBytes ) {
  34353. // Use the full buffer if it's interleaved.
  34354. var array = new TypedArray( arraybuffer );
  34355. // Integer parameters to IB/IBA are in array elements, not bytes.
  34356. var ib = new THREE.InterleavedBuffer( array, accessor.byteStride / elementBytes );
  34357. return new THREE.InterleavedBufferAttribute( ib, itemSize, accessor.byteOffset / elementBytes );
  34358. } else {
  34359. array = new TypedArray( arraybuffer, accessor.byteOffset, accessor.count * itemSize );
  34360. return new THREE.BufferAttribute( array, itemSize );
  34361. }
  34362. } );
  34363. } );
  34364. };
  34365. GLTFParser.prototype.loadTextures = function () {
  34366. var json = this.json;
  34367. var options = this.options;
  34368. return _each( json.textures, function ( texture ) {
  34369. if ( texture.source ) {
  34370. return new Promise( function ( resolve ) {
  34371. var source = json.images[ texture.source ];
  34372. var textureLoader = THREE.Loader.Handlers.get( source.uri );
  34373. if ( textureLoader === null ) {
  34374. textureLoader = new THREE.TextureLoader();
  34375. }
  34376. textureLoader.crossOrigin = options.crossOrigin || false;
  34377. textureLoader.load( resolveURL( source.uri, options.path ), function ( _texture ) {
  34378. _texture.flipY = false;
  34379. if ( texture.sampler ) {
  34380. var sampler = json.samplers[ texture.sampler ];
  34381. _texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ];
  34382. _texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ];
  34383. _texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ];
  34384. _texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ];
  34385. }
  34386. resolve( _texture );
  34387. }, undefined, function () {
  34388. resolve();
  34389. } );
  34390. } );
  34391. }
  34392. } );
  34393. };
  34394. GLTFParser.prototype.loadMaterials = function () {
  34395. var json = this.json;
  34396. return this._withDependencies( [
  34397. "shaders",
  34398. "textures"
  34399. ] ).then( function ( dependencies ) {
  34400. return _each( json.materials, function ( material ) {
  34401. var materialType;
  34402. var materialValues = {};
  34403. var materialParams = {};
  34404. var khr_material;
  34405. if ( material.extensions && material.extensions.KHR_materials_common ) {
  34406. khr_material = material.extensions.KHR_materials_common;
  34407. } else if ( json.extensions && json.extensions.KHR_materials_common ) {
  34408. khr_material = json.extensions.KHR_materials_common;
  34409. }
  34410. if ( khr_material ) {
  34411. switch ( khr_material.technique ) {
  34412. case 'BLINN' :
  34413. case 'PHONG' :
  34414. materialType = THREE.MeshPhongMaterial;
  34415. break;
  34416. case 'LAMBERT' :
  34417. materialType = THREE.MeshLambertMaterial;
  34418. break;
  34419. case 'CONSTANT' :
  34420. default :
  34421. materialType = THREE.MeshBasicMaterial;
  34422. break;
  34423. }
  34424. Object.assign( materialValues, khr_material.values );
  34425. if ( khr_material.doubleSided || materialValues.doubleSided ) {
  34426. materialParams.side = THREE.DoubleSide;
  34427. }
  34428. if ( khr_material.transparent || materialValues.transparent ) {
  34429. materialParams.transparent = true;
  34430. materialParams.opacity = ( materialValues.transparency !== undefined ) ? materialValues.transparency : 1;
  34431. }
  34432. } else if ( material.technique === undefined ) {
  34433. materialType = THREE.MeshPhongMaterial;
  34434. Object.assign( materialValues, material.values );
  34435. } else {
  34436. materialType = DeferredShaderMaterial;
  34437. var technique = json.techniques[ material.technique ];
  34438. materialParams.uniforms = {};
  34439. var program = json.programs[ technique.program ];
  34440. if ( program ) {
  34441. materialParams.fragmentShader = dependencies.shaders[ program.fragmentShader ];
  34442. if ( ! materialParams.fragmentShader ) {
  34443. console.warn( "ERROR: Missing fragment shader definition:", program.fragmentShader );
  34444. materialType = THREE.MeshPhongMaterial;
  34445. }
  34446. var vertexShader = dependencies.shaders[ program.vertexShader ];
  34447. if ( ! vertexShader ) {
  34448. console.warn( "ERROR: Missing vertex shader definition:", program.vertexShader );
  34449. materialType = THREE.MeshPhongMaterial;
  34450. }
  34451. // IMPORTANT: FIX VERTEX SHADER ATTRIBUTE DEFINITIONS
  34452. materialParams.vertexShader = replaceTHREEShaderAttributes( vertexShader, technique );
  34453. var uniforms = technique.uniforms;
  34454. for ( var uniformId in uniforms ) {
  34455. var pname = uniforms[ uniformId ];
  34456. var shaderParam = technique.parameters[ pname ];
  34457. var ptype = shaderParam.type;
  34458. if ( WEBGL_TYPE[ ptype ] ) {
  34459. var pcount = shaderParam.count;
  34460. var value = material.values[ pname ];
  34461. var uvalue = new WEBGL_TYPE[ ptype ]();
  34462. var usemantic = shaderParam.semantic;
  34463. var unode = shaderParam.node;
  34464. switch ( ptype ) {
  34465. case WEBGL_CONSTANTS.FLOAT:
  34466. uvalue = shaderParam.value;
  34467. if ( pname == "transparency" ) {
  34468. materialParams.transparent = true;
  34469. }
  34470. if ( value !== undefined ) {
  34471. uvalue = value;
  34472. }
  34473. break;
  34474. case WEBGL_CONSTANTS.FLOAT_VEC2:
  34475. case WEBGL_CONSTANTS.FLOAT_VEC3:
  34476. case WEBGL_CONSTANTS.FLOAT_VEC4:
  34477. case WEBGL_CONSTANTS.FLOAT_MAT3:
  34478. if ( shaderParam && shaderParam.value ) {
  34479. uvalue.fromArray( shaderParam.value );
  34480. }
  34481. if ( value ) {
  34482. uvalue.fromArray( value );
  34483. }
  34484. break;
  34485. case WEBGL_CONSTANTS.FLOAT_MAT2:
  34486. // what to do?
  34487. console.warn( "FLOAT_MAT2 is not a supported uniform type" );
  34488. break;
  34489. case WEBGL_CONSTANTS.FLOAT_MAT4:
  34490. if ( pcount ) {
  34491. uvalue = new Array( pcount );
  34492. for ( var mi = 0; mi < pcount; mi ++ ) {
  34493. uvalue[ mi ] = new WEBGL_TYPE[ ptype ]();
  34494. }
  34495. if ( shaderParam && shaderParam.value ) {
  34496. var m4v = shaderParam.value;
  34497. uvalue.fromArray( m4v );
  34498. }
  34499. if ( value ) {
  34500. uvalue.fromArray( value );
  34501. }
  34502. } else {
  34503. if ( shaderParam && shaderParam.value ) {
  34504. var m4 = shaderParam.value;
  34505. uvalue.fromArray( m4 );
  34506. }
  34507. if ( value ) {
  34508. uvalue.fromArray( value );
  34509. }
  34510. }
  34511. break;
  34512. case WEBGL_CONSTANTS.SAMPLER_2D:
  34513. uvalue = value ? dependencies.textures[ value ] : null;
  34514. break;
  34515. }
  34516. materialParams.uniforms[ uniformId ] = {
  34517. value: uvalue,
  34518. semantic: usemantic,
  34519. node: unode
  34520. };
  34521. } else {
  34522. throw new Error( "Unknown shader uniform param type: " + ptype );
  34523. }
  34524. }
  34525. }
  34526. }
  34527. if ( Array.isArray( materialValues.diffuse ) ) {
  34528. materialParams.color = new THREE.Color().fromArray( materialValues.diffuse );
  34529. } else if ( typeof( materialValues.diffuse ) === 'string' ) {
  34530. materialParams.map = dependencies.textures[ materialValues.diffuse ];
  34531. }
  34532. delete materialParams.diffuse;
  34533. if ( typeof( materialValues.reflective ) === 'string' ) {
  34534. materialParams.envMap = dependencies.textures[ materialValues.reflective ];
  34535. }
  34536. if ( typeof( materialValues.bump ) === 'string' ) {
  34537. materialParams.bumpMap = dependencies.textures[ materialValues.bump ];
  34538. }
  34539. if ( Array.isArray( materialValues.emission ) ) {
  34540. if ( materialType === THREE.MeshBasicMaterial ) {
  34541. materialParams.color = new THREE.Color().fromArray( materialValues.emission );
  34542. } else {
  34543. materialParams.emissive = new THREE.Color().fromArray( materialValues.emission );
  34544. }
  34545. } else if ( typeof( materialValues.emission ) === 'string' ) {
  34546. if ( materialType === THREE.MeshBasicMaterial ) {
  34547. materialParams.map = dependencies.textures[ materialValues.emission ];
  34548. } else {
  34549. materialParams.emissiveMap = dependencies.textures[ materialValues.emission ];
  34550. }
  34551. }
  34552. if ( Array.isArray( materialValues.specular ) ) {
  34553. materialParams.specular = new THREE.Color().fromArray( materialValues.specular );
  34554. } else if ( typeof( materialValues.specular ) === 'string' ) {
  34555. materialParams.specularMap = dependencies.textures[ materialValues.specular ];
  34556. }
  34557. if ( materialValues.shininess !== undefined ) {
  34558. materialParams.shininess = materialValues.shininess;
  34559. }
  34560. var _material = new materialType( materialParams );
  34561. _material.name = material.name;
  34562. return _material;
  34563. } );
  34564. } );
  34565. };
  34566. GLTFParser.prototype.loadMeshes = function () {
  34567. var json = this.json;
  34568. return this._withDependencies( [
  34569. "accessors",
  34570. "materials"
  34571. ] ).then( function ( dependencies ) {
  34572. return _each( json.meshes, function ( mesh ) {
  34573. var group = new THREE.Object3D();
  34574. group.name = mesh.name;
  34575. var primitives = mesh.primitives;
  34576. for ( var name in primitives ) {
  34577. var primitive = primitives[ name ];
  34578. if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === undefined ) {
  34579. var geometry = new THREE.BufferGeometry();
  34580. var attributes = primitive.attributes;
  34581. for ( var attributeId in attributes ) {
  34582. var attributeEntry = attributes[ attributeId ];
  34583. if ( ! attributeEntry ) return;
  34584. var bufferAttribute = dependencies.accessors[ attributeEntry ];
  34585. switch ( attributeId ) {
  34586. case 'POSITION':
  34587. geometry.addAttribute( 'position', bufferAttribute );
  34588. break;
  34589. case 'NORMAL':
  34590. geometry.addAttribute( 'normal', bufferAttribute );
  34591. break;
  34592. case 'TEXCOORD_0':
  34593. case 'TEXCOORD0':
  34594. case 'TEXCOORD':
  34595. geometry.addAttribute( 'uv', bufferAttribute );
  34596. break;
  34597. case 'WEIGHT':
  34598. geometry.addAttribute( 'skinWeight', bufferAttribute );
  34599. break;
  34600. case 'JOINT':
  34601. geometry.addAttribute( 'skinIndex', bufferAttribute );
  34602. break;
  34603. }
  34604. }
  34605. if ( primitive.indices ) {
  34606. var indexArray = dependencies.accessors[ primitive.indices ];
  34607. geometry.setIndex( indexArray );
  34608. var offset = {
  34609. start: 0,
  34610. index: 0,
  34611. count: indexArray.count
  34612. };
  34613. geometry.groups.push( offset );
  34614. geometry.computeBoundingSphere();
  34615. }
  34616. var material = dependencies.materials[ primitive.material ];
  34617. var meshNode = new THREE.Mesh( geometry, material );
  34618. meshNode.castShadow = true;
  34619. group.add( meshNode );
  34620. } else {
  34621. console.warn( "Non-triangular primitives are not supported" );
  34622. }
  34623. }
  34624. return group;
  34625. } );
  34626. } );
  34627. };
  34628. GLTFParser.prototype.loadCameras = function () {
  34629. var json = this.json;
  34630. return _each( json.cameras, function ( camera ) {
  34631. if ( camera.type == "perspective" && camera.perspective ) {
  34632. var yfov = camera.perspective.yfov;
  34633. var xfov = camera.perspective.xfov;
  34634. var aspect_ratio = camera.perspective.aspect_ratio || 1;
  34635. // According to COLLADA spec...
  34636. // aspect_ratio = xfov / yfov
  34637. xfov = ( xfov === undefined && yfov ) ? yfov * aspect_ratio : xfov;
  34638. // According to COLLADA spec...
  34639. // aspect_ratio = xfov / yfov
  34640. // yfov = ( yfov === undefined && xfov ) ? xfov / aspect_ratio : yfov;
  34641. var _camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( xfov ), aspect_ratio, camera.perspective.znear || 1, camera.perspective.zfar || 2e6 );
  34642. _camera.name = camera.name;
  34643. return _camera;
  34644. } else if ( camera.type == "orthographic" && camera.orthographic ) {
  34645. var _camera = new THREE.OrthographicCamera( window.innerWidth / - 2, window.innerWidth / 2, window.innerHeight / 2, window.innerHeight / - 2, camera.orthographic.znear, camera.orthographic.zfar );
  34646. _camera.name = camera.name;
  34647. return _camera;
  34648. }
  34649. } );
  34650. };
  34651. GLTFParser.prototype.loadSkins = function () {
  34652. var json = this.json;
  34653. return this._withDependencies( [
  34654. "accessors"
  34655. ] ).then( function ( dependencies ) {
  34656. return _each( json.skins, function ( skin ) {
  34657. var _skin = {
  34658. bindShapeMatrix: new THREE.Matrix4().fromArray( skin.bindShapeMatrix ),
  34659. jointNames: skin.jointNames,
  34660. inverseBindMatrices: dependencies.accessors[ skin.inverseBindMatrices ]
  34661. };
  34662. return _skin;
  34663. } );
  34664. } );
  34665. };
  34666. GLTFParser.prototype.loadAnimations = function () {
  34667. var json = this.json;
  34668. return this._withDependencies( [
  34669. "accessors",
  34670. "nodes"
  34671. ] ).then( function ( dependencies ) {
  34672. return _each( json.animations, function ( animation, animationId ) {
  34673. var interps = [];
  34674. for ( var channelId in animation.channels ) {
  34675. var channel = animation.channels[ channelId ];
  34676. var sampler = animation.samplers[ channel.sampler ];
  34677. if ( sampler && animation.parameters ) {
  34678. var target = channel.target;
  34679. var name = target.id;
  34680. var input = animation.parameters[ sampler.input ];
  34681. var output = animation.parameters[ sampler.output ];
  34682. var inputAccessor = dependencies.accessors[ input ];
  34683. var outputAccessor = dependencies.accessors[ output ];
  34684. var node = dependencies.nodes[ name ];
  34685. if ( node ) {
  34686. var interp = {
  34687. times: inputAccessor.array,
  34688. values: outputAccessor.array,
  34689. target: node,
  34690. type: INTERPOLATION[ sampler.interpolation ],
  34691. name: node.name + '.' + PATH_PROPERTIES[ target.path ]
  34692. };
  34693. interps.push( interp );
  34694. }
  34695. }
  34696. }
  34697. return createAnimation( "animation_" + animationId, interps );
  34698. } );
  34699. } );
  34700. };
  34701. GLTFParser.prototype.loadNodes = function () {
  34702. var json = this.json;
  34703. var scope = this;
  34704. return _each( json.nodes, function ( node ) {
  34705. var matrix = new THREE.Matrix4();
  34706. var _node;
  34707. if ( node.jointName ) {
  34708. _node = new THREE.Bone();
  34709. _node.jointName = node.jointName;
  34710. } else {
  34711. _node = new THREE.Object3D();
  34712. }
  34713. _node.name = node.name;
  34714. _node.matrixAutoUpdate = false;
  34715. if ( node.matrix !== undefined ) {
  34716. matrix.fromArray( node.matrix );
  34717. _node.applyMatrix( matrix );
  34718. } else {
  34719. if ( node.translation !== undefined ) {
  34720. _node.position.fromArray( node.translation );
  34721. }
  34722. if ( node.rotation !== undefined ) {
  34723. _node.quaternion.fromArray( node.rotation );
  34724. }
  34725. if ( node.scale !== undefined ) {
  34726. _node.scale.fromArray( node.scale );
  34727. }
  34728. }
  34729. return _node;
  34730. } ).then( function ( __nodes ) {
  34731. return scope._withDependencies( [
  34732. "meshes",
  34733. "skins",
  34734. "cameras",
  34735. "extensions"
  34736. ] ).then( function ( dependencies ) {
  34737. return _each( __nodes, function ( _node, nodeId ) {
  34738. var node = json.nodes[ nodeId ];
  34739. if ( node.meshes !== undefined ) {
  34740. for ( var meshId in node.meshes ) {
  34741. var mesh = node.meshes[ meshId ];
  34742. var group = dependencies.meshes[ mesh ];
  34743. for ( var childrenId in group.children ) {
  34744. var child = group.children[ childrenId ];
  34745. // clone Mesh to add to _node
  34746. var originalMaterial = child.material;
  34747. var originalGeometry = child.geometry;
  34748. var material;
  34749. if ( originalMaterial.isDeferredShaderMaterial ) {
  34750. originalMaterial = material = originalMaterial.create();
  34751. } else {
  34752. material = originalMaterial;
  34753. }
  34754. child = new THREE.Mesh( originalGeometry, material );
  34755. child.castShadow = true;
  34756. var skinEntry;
  34757. if ( node.skin ) {
  34758. skinEntry = dependencies.skins[ node.skin ];
  34759. }
  34760. // Replace Mesh with SkinnedMesh in library
  34761. if ( skinEntry ) {
  34762. var geometry = originalGeometry;
  34763. var material = originalMaterial;
  34764. material.skinning = true;
  34765. child = new THREE.SkinnedMesh( geometry, material, false );
  34766. child.castShadow = true;
  34767. var bones = [];
  34768. var boneInverses = [];
  34769. var keys = Object.keys( __nodes );
  34770. for ( var i = 0, l = skinEntry.jointNames.length; i < l; i ++ ) {
  34771. var jointId = skinEntry.jointNames[ i ];
  34772. var jointNode;
  34773. for ( var j = 0, jl = keys.length; j < jl; j ++ ) {
  34774. var n = __nodes[ keys[ j ] ];
  34775. if ( n.jointName === jointId ) {
  34776. jointNode = n;
  34777. break;
  34778. }
  34779. }
  34780. if ( jointNode ) {
  34781. jointNode.skin = child;
  34782. bones.push( jointNode );
  34783. var m = skinEntry.inverseBindMatrices.array;
  34784. var mat = new THREE.Matrix4().fromArray( m, i * 16 );
  34785. boneInverses.push( mat );
  34786. } else {
  34787. console.warn( "WARNING: joint: ''" + jointId + "' could not be found" );
  34788. }
  34789. }
  34790. child.bind( new THREE.Skeleton( bones, boneInverses, false ), skinEntry.bindShapeMatrix );
  34791. }
  34792. _node.add( child );
  34793. }
  34794. }
  34795. }
  34796. if ( node.camera !== undefined ) {
  34797. var camera = dependencies.cameras[ node.camera ];
  34798. _node.add( camera );
  34799. }
  34800. if ( node.extensions && node.extensions.KHR_materials_common && node.extensions.KHR_materials_common.light ) {
  34801. var light = dependencies.extensions.KHR_materials_common.lights[ node.extensions.KHR_materials_common.light ];
  34802. _node.add( light );
  34803. }
  34804. return _node;
  34805. } );
  34806. } );
  34807. } );
  34808. };
  34809. GLTFParser.prototype.loadExtensions = function () {
  34810. var json = this.json;
  34811. return _each( json.extensions, function ( extension, extensionId ) {
  34812. switch ( extensionId ) {
  34813. case "KHR_materials_common":
  34814. var extensionNode = {
  34815. lights: {}
  34816. };
  34817. var lights = extension.lights;
  34818. for ( var lightId in lights ) {
  34819. var light = lights[ lightId ];
  34820. var lightNode;
  34821. var lightParams = light[ light.type ];
  34822. var color = new THREE.Color().fromArray( lightParams.color );
  34823. switch ( light.type ) {
  34824. case "directional":
  34825. lightNode = new THREE.DirectionalLight( color );
  34826. lightNode.position.set( 0, 0, 1 );
  34827. break;
  34828. case "point":
  34829. lightNode = new THREE.PointLight( color );
  34830. break;
  34831. case "spot ":
  34832. lightNode = new THREE.SpotLight( color );
  34833. lightNode.position.set( 0, 0, 1 );
  34834. break;
  34835. case "ambient":
  34836. lightNode = new THREE.AmbientLight( color );
  34837. break;
  34838. }
  34839. if ( lightNode ) {
  34840. extensionNode.lights[ lightId ] = lightNode;
  34841. }
  34842. }
  34843. return extensionNode;
  34844. break;
  34845. }
  34846. } );
  34847. };
  34848. GLTFParser.prototype.loadScenes = function () {
  34849. var json = this.json;
  34850. // scene node hierachy builder
  34851. function buildNodeHierachy( nodeId, parentObject, allNodes ) {
  34852. var _node = allNodes[ nodeId ];
  34853. parentObject.add( _node );
  34854. var node = json.nodes[ nodeId ];
  34855. if ( node.children ) {
  34856. var children = node.children;
  34857. for ( var i = 0, l = children.length; i < l; i ++ ) {
  34858. var child = children[ i ];
  34859. buildNodeHierachy( child, _node, allNodes );
  34860. }
  34861. }
  34862. }
  34863. return this._withDependencies( [
  34864. "nodes"
  34865. ] ).then( function ( dependencies ) {
  34866. return _each( json.scenes, function ( scene ) {
  34867. var _scene = new THREE.Scene();
  34868. _scene.name = scene.name;
  34869. var nodes = scene.nodes;
  34870. for ( var i = 0, l = nodes.length; i < l; i ++ ) {
  34871. var nodeId = nodes[ i ];
  34872. buildNodeHierachy( nodeId, _scene, dependencies.nodes );
  34873. }
  34874. _scene.traverse( function ( child ) {
  34875. // Register raw material meshes with GLTFLoader.Shaders
  34876. if ( child.material && child.material.isRawShaderMaterial ) {
  34877. var xshader = new GLTFShader( child, dependencies.nodes );
  34878. GLTFLoader.Shaders.add( child.uuid, xshader );
  34879. }
  34880. } );
  34881. return _scene;
  34882. } );
  34883. } );
  34884. };
  34885. return GLTFLoader;
  34886. } )();
  34887. },{}],46:[function(_dereq_,module,exports){
  34888. /**
  34889. * Loads a Wavefront .mtl file specifying materials
  34890. *
  34891. * @author angelxuanchang
  34892. */
  34893. THREE.MTLLoader = function( manager ) {
  34894. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  34895. };
  34896. Object.assign( THREE.MTLLoader.prototype, THREE.EventDispatcher.prototype, {
  34897. /**
  34898. * Loads and parses a MTL asset from a URL.
  34899. *
  34900. * @param {String} url - URL to the MTL file.
  34901. * @param {Function} [onLoad] - Callback invoked with the loaded object.
  34902. * @param {Function} [onProgress] - Callback for download progress.
  34903. * @param {Function} [onError] - Callback for download errors.
  34904. *
  34905. * @see setPath setTexturePath
  34906. *
  34907. * @note In order for relative texture references to resolve correctly
  34908. * you must call setPath and/or setTexturePath explicitly prior to load.
  34909. */
  34910. load: function ( url, onLoad, onProgress, onError ) {
  34911. var scope = this;
  34912. var loader = new THREE.FileLoader( this.manager );
  34913. loader.setPath( this.path );
  34914. loader.load( url, function ( text ) {
  34915. onLoad( scope.parse( text ) );
  34916. }, onProgress, onError );
  34917. },
  34918. /**
  34919. * Set base path for resolving references.
  34920. * If set this path will be prepended to each loaded and found reference.
  34921. *
  34922. * @see setTexturePath
  34923. * @param {String} path
  34924. *
  34925. * @example
  34926. * mtlLoader.setPath( 'assets/obj/' );
  34927. * mtlLoader.load( 'my.mtl', ... );
  34928. */
  34929. setPath: function ( path ) {
  34930. this.path = path;
  34931. },
  34932. /**
  34933. * Set base path for resolving texture references.
  34934. * If set this path will be prepended found texture reference.
  34935. * If not set and setPath is, it will be used as texture base path.
  34936. *
  34937. * @see setPath
  34938. * @param {String} path
  34939. *
  34940. * @example
  34941. * mtlLoader.setPath( 'assets/obj/' );
  34942. * mtlLoader.setTexturePath( 'assets/textures/' );
  34943. * mtlLoader.load( 'my.mtl', ... );
  34944. */
  34945. setTexturePath: function( path ) {
  34946. this.texturePath = path;
  34947. },
  34948. setBaseUrl: function( path ) {
  34949. console.warn( 'THREE.MTLLoader: .setBaseUrl() is deprecated. Use .setTexturePath( path ) for texture path or .setPath( path ) for general base path instead.' );
  34950. this.setTexturePath( path );
  34951. },
  34952. setCrossOrigin: function ( value ) {
  34953. this.crossOrigin = value;
  34954. },
  34955. setMaterialOptions: function ( value ) {
  34956. this.materialOptions = value;
  34957. },
  34958. /**
  34959. * Parses a MTL file.
  34960. *
  34961. * @param {String} text - Content of MTL file
  34962. * @return {THREE.MTLLoader.MaterialCreator}
  34963. *
  34964. * @see setPath setTexturePath
  34965. *
  34966. * @note In order for relative texture references to resolve correctly
  34967. * you must call setPath and/or setTexturePath explicitly prior to parse.
  34968. */
  34969. parse: function ( text ) {
  34970. var lines = text.split( '\n' );
  34971. var info = {};
  34972. var delimiter_pattern = /\s+/;
  34973. var materialsInfo = {};
  34974. for ( var i = 0; i < lines.length; i ++ ) {
  34975. var line = lines[ i ];
  34976. line = line.trim();
  34977. if ( line.length === 0 || line.charAt( 0 ) === '#' ) {
  34978. // Blank line or comment ignore
  34979. continue;
  34980. }
  34981. var pos = line.indexOf( ' ' );
  34982. var key = ( pos >= 0 ) ? line.substring( 0, pos ) : line;
  34983. key = key.toLowerCase();
  34984. var value = ( pos >= 0 ) ? line.substring( pos + 1 ) : '';
  34985. value = value.trim();
  34986. if ( key === 'newmtl' ) {
  34987. // New material
  34988. info = { name: value };
  34989. materialsInfo[ value ] = info;
  34990. } else if ( info ) {
  34991. if ( key === 'ka' || key === 'kd' || key === 'ks' ) {
  34992. var ss = value.split( delimiter_pattern, 3 );
  34993. info[ key ] = [ parseFloat( ss[ 0 ] ), parseFloat( ss[ 1 ] ), parseFloat( ss[ 2 ] ) ];
  34994. } else {
  34995. info[ key ] = value;
  34996. }
  34997. }
  34998. }
  34999. var materialCreator = new THREE.MTLLoader.MaterialCreator( this.texturePath || this.path, this.materialOptions );
  35000. materialCreator.setCrossOrigin( this.crossOrigin );
  35001. materialCreator.setManager( this.manager );
  35002. materialCreator.setMaterials( materialsInfo );
  35003. return materialCreator;
  35004. }
  35005. } );
  35006. /**
  35007. * Create a new THREE-MTLLoader.MaterialCreator
  35008. * @param baseUrl - Url relative to which textures are loaded
  35009. * @param options - Set of options on how to construct the materials
  35010. * side: Which side to apply the material
  35011. * THREE.FrontSide (default), THREE.BackSide, THREE.DoubleSide
  35012. * wrap: What type of wrapping to apply for textures
  35013. * THREE.RepeatWrapping (default), THREE.ClampToEdgeWrapping, THREE.MirroredRepeatWrapping
  35014. * normalizeRGB: RGBs need to be normalized to 0-1 from 0-255
  35015. * Default: false, assumed to be already normalized
  35016. * ignoreZeroRGBs: Ignore values of RGBs (Ka,Kd,Ks) that are all 0's
  35017. * Default: false
  35018. * @constructor
  35019. */
  35020. THREE.MTLLoader.MaterialCreator = function( baseUrl, options ) {
  35021. this.baseUrl = baseUrl || '';
  35022. this.options = options;
  35023. this.materialsInfo = {};
  35024. this.materials = {};
  35025. this.materialsArray = [];
  35026. this.nameLookup = {};
  35027. this.side = ( this.options && this.options.side ) ? this.options.side : THREE.FrontSide;
  35028. this.wrap = ( this.options && this.options.wrap ) ? this.options.wrap : THREE.RepeatWrapping;
  35029. };
  35030. THREE.MTLLoader.MaterialCreator.prototype = {
  35031. constructor: THREE.MTLLoader.MaterialCreator,
  35032. setCrossOrigin: function ( value ) {
  35033. this.crossOrigin = value;
  35034. },
  35035. setManager: function ( value ) {
  35036. this.manager = value;
  35037. },
  35038. setMaterials: function( materialsInfo ) {
  35039. this.materialsInfo = this.convert( materialsInfo );
  35040. this.materials = {};
  35041. this.materialsArray = [];
  35042. this.nameLookup = {};
  35043. },
  35044. convert: function( materialsInfo ) {
  35045. if ( ! this.options ) return materialsInfo;
  35046. var converted = {};
  35047. for ( var mn in materialsInfo ) {
  35048. // Convert materials info into normalized form based on options
  35049. var mat = materialsInfo[ mn ];
  35050. var covmat = {};
  35051. converted[ mn ] = covmat;
  35052. for ( var prop in mat ) {
  35053. var save = true;
  35054. var value = mat[ prop ];
  35055. var lprop = prop.toLowerCase();
  35056. switch ( lprop ) {
  35057. case 'kd':
  35058. case 'ka':
  35059. case 'ks':
  35060. // Diffuse color (color under white light) using RGB values
  35061. if ( this.options && this.options.normalizeRGB ) {
  35062. value = [ value[ 0 ] / 255, value[ 1 ] / 255, value[ 2 ] / 255 ];
  35063. }
  35064. if ( this.options && this.options.ignoreZeroRGBs ) {
  35065. if ( value[ 0 ] === 0 && value[ 1 ] === 0 && value[ 2 ] === 0 ) {
  35066. // ignore
  35067. save = false;
  35068. }
  35069. }
  35070. break;
  35071. default:
  35072. break;
  35073. }
  35074. if ( save ) {
  35075. covmat[ lprop ] = value;
  35076. }
  35077. }
  35078. }
  35079. return converted;
  35080. },
  35081. preload: function () {
  35082. for ( var mn in this.materialsInfo ) {
  35083. this.create( mn );
  35084. }
  35085. },
  35086. getIndex: function( materialName ) {
  35087. return this.nameLookup[ materialName ];
  35088. },
  35089. getAsArray: function() {
  35090. var index = 0;
  35091. for ( var mn in this.materialsInfo ) {
  35092. this.materialsArray[ index ] = this.create( mn );
  35093. this.nameLookup[ mn ] = index;
  35094. index ++;
  35095. }
  35096. return this.materialsArray;
  35097. },
  35098. create: function ( materialName ) {
  35099. if ( this.materials[ materialName ] === undefined ) {
  35100. this.createMaterial_( materialName );
  35101. }
  35102. return this.materials[ materialName ];
  35103. },
  35104. createMaterial_: function ( materialName ) {
  35105. // Create material
  35106. var scope = this;
  35107. var mat = this.materialsInfo[ materialName ];
  35108. var params = {
  35109. name: materialName,
  35110. side: this.side
  35111. };
  35112. var resolveURL = function ( baseUrl, url ) {
  35113. if ( typeof url !== 'string' || url === '' )
  35114. return '';
  35115. // Absolute URL
  35116. if ( /^https?:\/\//i.test( url ) ) {
  35117. return url;
  35118. }
  35119. return baseUrl + url;
  35120. };
  35121. function setMapForType ( mapType, value ) {
  35122. if ( params[ mapType ] ) return; // Keep the first encountered texture
  35123. var texParams = scope.getTextureParams( value, params );
  35124. var map = scope.loadTexture( resolveURL( scope.baseUrl, texParams.url ) );
  35125. map.repeat.copy( texParams.scale );
  35126. map.offset.copy( texParams.offset );
  35127. map.wrapS = scope.wrap;
  35128. map.wrapT = scope.wrap;
  35129. params[ mapType ] = map;
  35130. }
  35131. for ( var prop in mat ) {
  35132. var value = mat[ prop ];
  35133. if ( value === '' ) continue;
  35134. switch ( prop.toLowerCase() ) {
  35135. // Ns is material specular exponent
  35136. case 'kd':
  35137. // Diffuse color (color under white light) using RGB values
  35138. params.color = new THREE.Color().fromArray( value );
  35139. break;
  35140. case 'ks':
  35141. // Specular color (color when light is reflected from shiny surface) using RGB values
  35142. params.specular = new THREE.Color().fromArray( value );
  35143. break;
  35144. case 'map_kd':
  35145. // Diffuse texture map
  35146. setMapForType( "map", value );
  35147. break;
  35148. case 'map_ks':
  35149. // Specular map
  35150. setMapForType( "specularMap", value );
  35151. break;
  35152. case 'map_bump':
  35153. case 'bump':
  35154. // Bump texture map
  35155. setMapForType( "bumpMap", value );
  35156. break;
  35157. case 'ns':
  35158. // The specular exponent (defines the focus of the specular highlight)
  35159. // A high exponent results in a tight, concentrated highlight. Ns values normally range from 0 to 1000.
  35160. params.shininess = parseFloat( value );
  35161. break;
  35162. case 'd':
  35163. if ( value < 1 ) {
  35164. params.opacity = value;
  35165. params.transparent = true;
  35166. }
  35167. break;
  35168. case 'Tr':
  35169. if ( value > 0 ) {
  35170. params.opacity = 1 - value;
  35171. params.transparent = true;
  35172. }
  35173. break;
  35174. default:
  35175. break;
  35176. }
  35177. }
  35178. this.materials[ materialName ] = new THREE.MeshPhongMaterial( params );
  35179. return this.materials[ materialName ];
  35180. },
  35181. getTextureParams: function( value, matParams ) {
  35182. var texParams = {
  35183. scale: new THREE.Vector2( 1, 1 ),
  35184. offset: new THREE.Vector2( 0, 0 )
  35185. };
  35186. var items = value.split(/\s+/);
  35187. var pos;
  35188. pos = items.indexOf('-bm');
  35189. if (pos >= 0) {
  35190. matParams.bumpScale = parseFloat( items[pos+1] );
  35191. items.splice( pos, 2 );
  35192. }
  35193. pos = items.indexOf('-s');
  35194. if (pos >= 0) {
  35195. texParams.scale.set( parseFloat( items[pos+1] ), parseFloat( items[pos+2] ) );
  35196. items.splice( pos, 4 ); // we expect 3 parameters here!
  35197. }
  35198. pos = items.indexOf('-o');
  35199. if (pos >= 0) {
  35200. texParams.offset.set( parseFloat( items[pos+1] ), parseFloat( items[pos+2] ) );
  35201. items.splice( pos, 4 ); // we expect 3 parameters here!
  35202. }
  35203. texParams.url = items.join(' ').trim();
  35204. return texParams;
  35205. },
  35206. loadTexture: function ( url, mapping, onLoad, onProgress, onError ) {
  35207. var texture;
  35208. var loader = THREE.Loader.Handlers.get( url );
  35209. var manager = ( this.manager !== undefined ) ? this.manager : THREE.DefaultLoadingManager;
  35210. if ( loader === null ) {
  35211. loader = new THREE.TextureLoader( manager );
  35212. }
  35213. if ( loader.setCrossOrigin ) loader.setCrossOrigin( this.crossOrigin );
  35214. texture = loader.load( url, onLoad, onProgress, onError );
  35215. if ( mapping !== undefined ) texture.mapping = mapping;
  35216. return texture;
  35217. }
  35218. };
  35219. },{}],47:[function(_dereq_,module,exports){
  35220. /**
  35221. * @author mrdoob / http://mrdoob.com/
  35222. */
  35223. THREE.OBJLoader = function ( manager ) {
  35224. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  35225. this.materials = null;
  35226. this.regexp = {
  35227. // v float float float
  35228. vertex_pattern : /^v\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35229. // vn float float float
  35230. normal_pattern : /^vn\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35231. // vt float float
  35232. uv_pattern : /^vt\s+([\d|\.|\+|\-|e|E]+)\s+([\d|\.|\+|\-|e|E]+)/,
  35233. // f vertex vertex vertex
  35234. face_vertex : /^f\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)(?:\s+(-?\d+))?/,
  35235. // f vertex/uv vertex/uv vertex/uv
  35236. face_vertex_uv : /^f\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+))?/,
  35237. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35238. face_vertex_uv_normal : /^f\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)\s+(-?\d+)\/(-?\d+)\/(-?\d+)(?:\s+(-?\d+)\/(-?\d+)\/(-?\d+))?/,
  35239. // f vertex//normal vertex//normal vertex//normal
  35240. face_vertex_normal : /^f\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)\s+(-?\d+)\/\/(-?\d+)(?:\s+(-?\d+)\/\/(-?\d+))?/,
  35241. // o object_name | g group_name
  35242. object_pattern : /^[og]\s*(.+)?/,
  35243. // s boolean
  35244. smoothing_pattern : /^s\s+(\d+|on|off)/,
  35245. // mtllib file_reference
  35246. material_library_pattern : /^mtllib /,
  35247. // usemtl material_name
  35248. material_use_pattern : /^usemtl /
  35249. };
  35250. };
  35251. THREE.OBJLoader.prototype = {
  35252. constructor: THREE.OBJLoader,
  35253. load: function ( url, onLoad, onProgress, onError ) {
  35254. var scope = this;
  35255. var loader = new THREE.FileLoader( scope.manager );
  35256. loader.setPath( this.path );
  35257. loader.load( url, function ( text ) {
  35258. onLoad( scope.parse( text ) );
  35259. }, onProgress, onError );
  35260. },
  35261. setPath: function ( value ) {
  35262. this.path = value;
  35263. },
  35264. setMaterials: function ( materials ) {
  35265. this.materials = materials;
  35266. },
  35267. _createParserState : function () {
  35268. var state = {
  35269. objects : [],
  35270. object : {},
  35271. vertices : [],
  35272. normals : [],
  35273. uvs : [],
  35274. materialLibraries : [],
  35275. startObject: function ( name, fromDeclaration ) {
  35276. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  35277. // file. We need to use it for the first parsed g/o to keep things in sync.
  35278. if ( this.object && this.object.fromDeclaration === false ) {
  35279. this.object.name = name;
  35280. this.object.fromDeclaration = ( fromDeclaration !== false );
  35281. return;
  35282. }
  35283. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  35284. if ( this.object && typeof this.object._finalize === 'function' ) {
  35285. this.object._finalize( true );
  35286. }
  35287. this.object = {
  35288. name : name || '',
  35289. fromDeclaration : ( fromDeclaration !== false ),
  35290. geometry : {
  35291. vertices : [],
  35292. normals : [],
  35293. uvs : []
  35294. },
  35295. materials : [],
  35296. smooth : true,
  35297. startMaterial : function( name, libraries ) {
  35298. var previous = this._finalize( false );
  35299. // New usemtl declaration overwrites an inherited material, except if faces were declared
  35300. // after the material, then it must be preserved for proper MultiMaterial continuation.
  35301. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  35302. this.materials.splice( previous.index, 1 );
  35303. }
  35304. var material = {
  35305. index : this.materials.length,
  35306. name : name || '',
  35307. mtllib : ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  35308. smooth : ( previous !== undefined ? previous.smooth : this.smooth ),
  35309. groupStart : ( previous !== undefined ? previous.groupEnd : 0 ),
  35310. groupEnd : -1,
  35311. groupCount : -1,
  35312. inherited : false,
  35313. clone : function( index ) {
  35314. var cloned = {
  35315. index : ( typeof index === 'number' ? index : this.index ),
  35316. name : this.name,
  35317. mtllib : this.mtllib,
  35318. smooth : this.smooth,
  35319. groupStart : 0,
  35320. groupEnd : -1,
  35321. groupCount : -1,
  35322. inherited : false
  35323. };
  35324. cloned.clone = this.clone.bind(cloned);
  35325. return cloned;
  35326. }
  35327. };
  35328. this.materials.push( material );
  35329. return material;
  35330. },
  35331. currentMaterial : function() {
  35332. if ( this.materials.length > 0 ) {
  35333. return this.materials[ this.materials.length - 1 ];
  35334. }
  35335. return undefined;
  35336. },
  35337. _finalize : function( end ) {
  35338. var lastMultiMaterial = this.currentMaterial();
  35339. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === -1 ) {
  35340. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  35341. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  35342. lastMultiMaterial.inherited = false;
  35343. }
  35344. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  35345. if ( end && this.materials.length > 1 ) {
  35346. for ( var mi = this.materials.length - 1; mi >= 0; mi-- ) {
  35347. if ( this.materials[mi].groupCount <= 0 ) {
  35348. this.materials.splice( mi, 1 );
  35349. }
  35350. }
  35351. }
  35352. // Guarantee at least one empty material, this makes the creation later more straight forward.
  35353. if ( end && this.materials.length === 0 ) {
  35354. this.materials.push({
  35355. name : '',
  35356. smooth : this.smooth
  35357. });
  35358. }
  35359. return lastMultiMaterial;
  35360. }
  35361. };
  35362. // Inherit previous objects material.
  35363. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  35364. // If a usemtl declaration is encountered while this new object is being parsed, it will
  35365. // overwrite the inherited material. Exception being that there was already face declarations
  35366. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  35367. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === "function" ) {
  35368. var declared = previousMaterial.clone( 0 );
  35369. declared.inherited = true;
  35370. this.object.materials.push( declared );
  35371. }
  35372. this.objects.push( this.object );
  35373. },
  35374. finalize : function() {
  35375. if ( this.object && typeof this.object._finalize === 'function' ) {
  35376. this.object._finalize( true );
  35377. }
  35378. },
  35379. parseVertexIndex: function ( value, len ) {
  35380. var index = parseInt( value, 10 );
  35381. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35382. },
  35383. parseNormalIndex: function ( value, len ) {
  35384. var index = parseInt( value, 10 );
  35385. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  35386. },
  35387. parseUVIndex: function ( value, len ) {
  35388. var index = parseInt( value, 10 );
  35389. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  35390. },
  35391. addVertex: function ( a, b, c ) {
  35392. var src = this.vertices;
  35393. var dst = this.object.geometry.vertices;
  35394. dst.push( src[ a + 0 ] );
  35395. dst.push( src[ a + 1 ] );
  35396. dst.push( src[ a + 2 ] );
  35397. dst.push( src[ b + 0 ] );
  35398. dst.push( src[ b + 1 ] );
  35399. dst.push( src[ b + 2 ] );
  35400. dst.push( src[ c + 0 ] );
  35401. dst.push( src[ c + 1 ] );
  35402. dst.push( src[ c + 2 ] );
  35403. },
  35404. addVertexLine: function ( a ) {
  35405. var src = this.vertices;
  35406. var dst = this.object.geometry.vertices;
  35407. dst.push( src[ a + 0 ] );
  35408. dst.push( src[ a + 1 ] );
  35409. dst.push( src[ a + 2 ] );
  35410. },
  35411. addNormal : function ( a, b, c ) {
  35412. var src = this.normals;
  35413. var dst = this.object.geometry.normals;
  35414. dst.push( src[ a + 0 ] );
  35415. dst.push( src[ a + 1 ] );
  35416. dst.push( src[ a + 2 ] );
  35417. dst.push( src[ b + 0 ] );
  35418. dst.push( src[ b + 1 ] );
  35419. dst.push( src[ b + 2 ] );
  35420. dst.push( src[ c + 0 ] );
  35421. dst.push( src[ c + 1 ] );
  35422. dst.push( src[ c + 2 ] );
  35423. },
  35424. addUV: function ( a, b, c ) {
  35425. var src = this.uvs;
  35426. var dst = this.object.geometry.uvs;
  35427. dst.push( src[ a + 0 ] );
  35428. dst.push( src[ a + 1 ] );
  35429. dst.push( src[ b + 0 ] );
  35430. dst.push( src[ b + 1 ] );
  35431. dst.push( src[ c + 0 ] );
  35432. dst.push( src[ c + 1 ] );
  35433. },
  35434. addUVLine: function ( a ) {
  35435. var src = this.uvs;
  35436. var dst = this.object.geometry.uvs;
  35437. dst.push( src[ a + 0 ] );
  35438. dst.push( src[ a + 1 ] );
  35439. },
  35440. addFace: function ( a, b, c, d, ua, ub, uc, ud, na, nb, nc, nd ) {
  35441. var vLen = this.vertices.length;
  35442. var ia = this.parseVertexIndex( a, vLen );
  35443. var ib = this.parseVertexIndex( b, vLen );
  35444. var ic = this.parseVertexIndex( c, vLen );
  35445. var id;
  35446. if ( d === undefined ) {
  35447. this.addVertex( ia, ib, ic );
  35448. } else {
  35449. id = this.parseVertexIndex( d, vLen );
  35450. this.addVertex( ia, ib, id );
  35451. this.addVertex( ib, ic, id );
  35452. }
  35453. if ( ua !== undefined ) {
  35454. var uvLen = this.uvs.length;
  35455. ia = this.parseUVIndex( ua, uvLen );
  35456. ib = this.parseUVIndex( ub, uvLen );
  35457. ic = this.parseUVIndex( uc, uvLen );
  35458. if ( d === undefined ) {
  35459. this.addUV( ia, ib, ic );
  35460. } else {
  35461. id = this.parseUVIndex( ud, uvLen );
  35462. this.addUV( ia, ib, id );
  35463. this.addUV( ib, ic, id );
  35464. }
  35465. }
  35466. if ( na !== undefined ) {
  35467. // Normals are many times the same. If so, skip function call and parseInt.
  35468. var nLen = this.normals.length;
  35469. ia = this.parseNormalIndex( na, nLen );
  35470. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  35471. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  35472. if ( d === undefined ) {
  35473. this.addNormal( ia, ib, ic );
  35474. } else {
  35475. id = this.parseNormalIndex( nd, nLen );
  35476. this.addNormal( ia, ib, id );
  35477. this.addNormal( ib, ic, id );
  35478. }
  35479. }
  35480. },
  35481. addLineGeometry: function ( vertices, uvs ) {
  35482. this.object.geometry.type = 'Line';
  35483. var vLen = this.vertices.length;
  35484. var uvLen = this.uvs.length;
  35485. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  35486. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  35487. }
  35488. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  35489. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  35490. }
  35491. }
  35492. };
  35493. state.startObject( '', false );
  35494. return state;
  35495. },
  35496. parse: function ( text ) {
  35497. console.time( 'OBJLoader' );
  35498. var state = this._createParserState();
  35499. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  35500. // This is faster than String.split with regex that splits on both
  35501. text = text.replace( /\r\n/g, '\n' );
  35502. }
  35503. if ( text.indexOf( '\\\n' ) !== - 1) {
  35504. // join lines separated by a line continuation character (\)
  35505. text = text.replace( /\\\n/g, '' );
  35506. }
  35507. var lines = text.split( '\n' );
  35508. var line = '', lineFirstChar = '', lineSecondChar = '';
  35509. var lineLength = 0;
  35510. var result = [];
  35511. // Faster to just trim left side of the line. Use if available.
  35512. var trimLeft = ( typeof ''.trimLeft === 'function' );
  35513. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  35514. line = lines[ i ];
  35515. line = trimLeft ? line.trimLeft() : line.trim();
  35516. lineLength = line.length;
  35517. if ( lineLength === 0 ) continue;
  35518. lineFirstChar = line.charAt( 0 );
  35519. // @todo invoke passed in handler if any
  35520. if ( lineFirstChar === '#' ) continue;
  35521. if ( lineFirstChar === 'v' ) {
  35522. lineSecondChar = line.charAt( 1 );
  35523. if ( lineSecondChar === ' ' && ( result = this.regexp.vertex_pattern.exec( line ) ) !== null ) {
  35524. // 0 1 2 3
  35525. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35526. state.vertices.push(
  35527. parseFloat( result[ 1 ] ),
  35528. parseFloat( result[ 2 ] ),
  35529. parseFloat( result[ 3 ] )
  35530. );
  35531. } else if ( lineSecondChar === 'n' && ( result = this.regexp.normal_pattern.exec( line ) ) !== null ) {
  35532. // 0 1 2 3
  35533. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  35534. state.normals.push(
  35535. parseFloat( result[ 1 ] ),
  35536. parseFloat( result[ 2 ] ),
  35537. parseFloat( result[ 3 ] )
  35538. );
  35539. } else if ( lineSecondChar === 't' && ( result = this.regexp.uv_pattern.exec( line ) ) !== null ) {
  35540. // 0 1 2
  35541. // ["vt 0.1 0.2", "0.1", "0.2"]
  35542. state.uvs.push(
  35543. parseFloat( result[ 1 ] ),
  35544. parseFloat( result[ 2 ] )
  35545. );
  35546. } else {
  35547. throw new Error( "Unexpected vertex/normal/uv line: '" + line + "'" );
  35548. }
  35549. } else if ( lineFirstChar === "f" ) {
  35550. if ( ( result = this.regexp.face_vertex_uv_normal.exec( line ) ) !== null ) {
  35551. // f vertex/uv/normal vertex/uv/normal vertex/uv/normal
  35552. // 0 1 2 3 4 5 6 7 8 9 10 11 12
  35553. // ["f 1/1/1 2/2/2 3/3/3", "1", "1", "1", "2", "2", "2", "3", "3", "3", undefined, undefined, undefined]
  35554. state.addFace(
  35555. result[ 1 ], result[ 4 ], result[ 7 ], result[ 10 ],
  35556. result[ 2 ], result[ 5 ], result[ 8 ], result[ 11 ],
  35557. result[ 3 ], result[ 6 ], result[ 9 ], result[ 12 ]
  35558. );
  35559. } else if ( ( result = this.regexp.face_vertex_uv.exec( line ) ) !== null ) {
  35560. // f vertex/uv vertex/uv vertex/uv
  35561. // 0 1 2 3 4 5 6 7 8
  35562. // ["f 1/1 2/2 3/3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35563. state.addFace(
  35564. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35565. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35566. );
  35567. } else if ( ( result = this.regexp.face_vertex_normal.exec( line ) ) !== null ) {
  35568. // f vertex//normal vertex//normal vertex//normal
  35569. // 0 1 2 3 4 5 6 7 8
  35570. // ["f 1//1 2//2 3//3", "1", "1", "2", "2", "3", "3", undefined, undefined]
  35571. state.addFace(
  35572. result[ 1 ], result[ 3 ], result[ 5 ], result[ 7 ],
  35573. undefined, undefined, undefined, undefined,
  35574. result[ 2 ], result[ 4 ], result[ 6 ], result[ 8 ]
  35575. );
  35576. } else if ( ( result = this.regexp.face_vertex.exec( line ) ) !== null ) {
  35577. // f vertex vertex vertex
  35578. // 0 1 2 3 4
  35579. // ["f 1 2 3", "1", "2", "3", undefined]
  35580. state.addFace(
  35581. result[ 1 ], result[ 2 ], result[ 3 ], result[ 4 ]
  35582. );
  35583. } else {
  35584. throw new Error( "Unexpected face line: '" + line + "'" );
  35585. }
  35586. } else if ( lineFirstChar === "l" ) {
  35587. var lineParts = line.substring( 1 ).trim().split( " " );
  35588. var lineVertices = [], lineUVs = [];
  35589. if ( line.indexOf( "/" ) === - 1 ) {
  35590. lineVertices = lineParts;
  35591. } else {
  35592. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  35593. var parts = lineParts[ li ].split( "/" );
  35594. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  35595. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  35596. }
  35597. }
  35598. state.addLineGeometry( lineVertices, lineUVs );
  35599. } else if ( ( result = this.regexp.object_pattern.exec( line ) ) !== null ) {
  35600. // o object_name
  35601. // or
  35602. // g group_name
  35603. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  35604. // var name = result[ 0 ].substr( 1 ).trim();
  35605. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  35606. state.startObject( name );
  35607. } else if ( this.regexp.material_use_pattern.test( line ) ) {
  35608. // material
  35609. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  35610. } else if ( this.regexp.material_library_pattern.test( line ) ) {
  35611. // mtl file
  35612. state.materialLibraries.push( line.substring( 7 ).trim() );
  35613. } else if ( ( result = this.regexp.smoothing_pattern.exec( line ) ) !== null ) {
  35614. // smooth shading
  35615. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  35616. // but does not define a usemtl for each face set.
  35617. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  35618. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  35619. // where explicit usemtl defines geometry groups.
  35620. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  35621. var value = result[ 1 ].trim().toLowerCase();
  35622. state.object.smooth = ( value === '1' || value === 'on' );
  35623. var material = state.object.currentMaterial();
  35624. if ( material ) {
  35625. material.smooth = state.object.smooth;
  35626. }
  35627. } else {
  35628. // Handle null terminated files without exception
  35629. if ( line === '\0' ) continue;
  35630. throw new Error( "Unexpected line: '" + line + "'" );
  35631. }
  35632. }
  35633. state.finalize();
  35634. var container = new THREE.Group();
  35635. container.materialLibraries = [].concat( state.materialLibraries );
  35636. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  35637. var object = state.objects[ i ];
  35638. var geometry = object.geometry;
  35639. var materials = object.materials;
  35640. var isLine = ( geometry.type === 'Line' );
  35641. // Skip o/g line declarations that did not follow with any faces
  35642. if ( geometry.vertices.length === 0 ) continue;
  35643. var buffergeometry = new THREE.BufferGeometry();
  35644. buffergeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( geometry.vertices ), 3 ) );
  35645. if ( geometry.normals.length > 0 ) {
  35646. buffergeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( geometry.normals ), 3 ) );
  35647. } else {
  35648. buffergeometry.computeVertexNormals();
  35649. }
  35650. if ( geometry.uvs.length > 0 ) {
  35651. buffergeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( geometry.uvs ), 2 ) );
  35652. }
  35653. // Create materials
  35654. var createdMaterials = [];
  35655. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  35656. var sourceMaterial = materials[mi];
  35657. var material = undefined;
  35658. if ( this.materials !== null ) {
  35659. material = this.materials.create( sourceMaterial.name );
  35660. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  35661. if ( isLine && material && ! ( material instanceof THREE.LineBasicMaterial ) ) {
  35662. var materialLine = new THREE.LineBasicMaterial();
  35663. materialLine.copy( material );
  35664. material = materialLine;
  35665. }
  35666. }
  35667. if ( ! material ) {
  35668. material = ( ! isLine ? new THREE.MeshPhongMaterial() : new THREE.LineBasicMaterial() );
  35669. material.name = sourceMaterial.name;
  35670. }
  35671. material.shading = sourceMaterial.smooth ? THREE.SmoothShading : THREE.FlatShading;
  35672. createdMaterials.push(material);
  35673. }
  35674. // Create mesh
  35675. var mesh;
  35676. if ( createdMaterials.length > 1 ) {
  35677. for ( var mi = 0, miLen = materials.length; mi < miLen ; mi++ ) {
  35678. var sourceMaterial = materials[mi];
  35679. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  35680. }
  35681. var multiMaterial = new THREE.MultiMaterial( createdMaterials );
  35682. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, multiMaterial ) : new THREE.LineSegments( buffergeometry, multiMaterial ) );
  35683. } else {
  35684. mesh = ( ! isLine ? new THREE.Mesh( buffergeometry, createdMaterials[ 0 ] ) : new THREE.LineSegments( buffergeometry, createdMaterials[ 0 ] ) );
  35685. }
  35686. mesh.name = object.name;
  35687. container.add( mesh );
  35688. }
  35689. console.timeEnd( 'OBJLoader' );
  35690. return container;
  35691. }
  35692. };
  35693. },{}],48:[function(_dereq_,module,exports){
  35694. exports = module.exports = trim;
  35695. function trim(str){
  35696. return str.replace(/^\s*|\s*$/g, '');
  35697. }
  35698. exports.left = function(str){
  35699. return str.replace(/^\s*/, '');
  35700. };
  35701. exports.right = function(str){
  35702. return str.replace(/\s*$/, '');
  35703. };
  35704. },{}],49:[function(_dereq_,module,exports){
  35705. /**
  35706. * Tween.js - Licensed under the MIT license
  35707. * https://github.com/sole/tween.js
  35708. * ----------------------------------------------
  35709. *
  35710. * See https://github.com/sole/tween.js/graphs/contributors for the full list of contributors.
  35711. * Thank you all, you're awesome!
  35712. */
  35713. // performance.now polyfill
  35714. ( function ( root ) {
  35715. if ( 'performance' in root === false ) {
  35716. root.performance = {};
  35717. }
  35718. // IE 8
  35719. Date.now = ( Date.now || function () {
  35720. return new Date().getTime();
  35721. } );
  35722. if ( 'now' in root.performance === false ) {
  35723. var offset = root.performance.timing && root.performance.timing.navigationStart ? performance.timing.navigationStart
  35724. : Date.now();
  35725. root.performance.now = function () {
  35726. return Date.now() - offset;
  35727. };
  35728. }
  35729. } )( this );
  35730. var TWEEN = TWEEN || ( function () {
  35731. var _tweens = [];
  35732. return {
  35733. REVISION: '14',
  35734. getAll: function () {
  35735. return _tweens;
  35736. },
  35737. removeAll: function () {
  35738. _tweens = [];
  35739. },
  35740. add: function ( tween ) {
  35741. _tweens.push( tween );
  35742. },
  35743. remove: function ( tween ) {
  35744. var i = _tweens.indexOf( tween );
  35745. if ( i !== -1 ) {
  35746. _tweens.splice( i, 1 );
  35747. }
  35748. },
  35749. update: function ( time ) {
  35750. if ( _tweens.length === 0 ) return false;
  35751. var i = 0;
  35752. time = time !== undefined ? time : window.performance.now();
  35753. while ( i < _tweens.length ) {
  35754. if ( _tweens[ i ].update( time ) ) {
  35755. i++;
  35756. } else {
  35757. _tweens.splice( i, 1 );
  35758. }
  35759. }
  35760. return true;
  35761. }
  35762. };
  35763. } )();
  35764. TWEEN.Tween = function ( object ) {
  35765. var _object = object;
  35766. var _valuesStart = {};
  35767. var _valuesEnd = {};
  35768. var _valuesStartRepeat = {};
  35769. var _duration = 1000;
  35770. var _repeat = 0;
  35771. var _yoyo = false;
  35772. var _isPlaying = false;
  35773. var _reversed = false;
  35774. var _delayTime = 0;
  35775. var _startTime = null;
  35776. var _easingFunction = TWEEN.Easing.Linear.None;
  35777. var _interpolationFunction = TWEEN.Interpolation.Linear;
  35778. var _chainedTweens = [];
  35779. var _onStartCallback = null;
  35780. var _onStartCallbackFired = false;
  35781. var _onUpdateCallback = null;
  35782. var _onCompleteCallback = null;
  35783. var _onStopCallback = null;
  35784. // Set all starting values present on the target object
  35785. for ( var field in object ) {
  35786. _valuesStart[ field ] = parseFloat(object[field], 10);
  35787. }
  35788. this.to = function ( properties, duration ) {
  35789. if ( duration !== undefined ) {
  35790. _duration = duration;
  35791. }
  35792. _valuesEnd = properties;
  35793. return this;
  35794. };
  35795. this.start = function ( time ) {
  35796. TWEEN.add( this );
  35797. _isPlaying = true;
  35798. _onStartCallbackFired = false;
  35799. _startTime = time !== undefined ? time : window.performance.now();
  35800. _startTime += _delayTime;
  35801. for ( var property in _valuesEnd ) {
  35802. // check if an Array was provided as property value
  35803. if ( _valuesEnd[ property ] instanceof Array ) {
  35804. if ( _valuesEnd[ property ].length === 0 ) {
  35805. continue;
  35806. }
  35807. // create a local copy of the Array with the start value at the front
  35808. _valuesEnd[ property ] = [ _object[ property ] ].concat( _valuesEnd[ property ] );
  35809. }
  35810. _valuesStart[ property ] = _object[ property ];
  35811. if( ( _valuesStart[ property ] instanceof Array ) === false ) {
  35812. _valuesStart[ property ] *= 1.0; // Ensures we're using numbers, not strings
  35813. }
  35814. _valuesStartRepeat[ property ] = _valuesStart[ property ] || 0;
  35815. }
  35816. return this;
  35817. };
  35818. this.stop = function () {
  35819. if ( !_isPlaying ) {
  35820. return this;
  35821. }
  35822. TWEEN.remove( this );
  35823. _isPlaying = false;
  35824. if ( _onStopCallback !== null ) {
  35825. _onStopCallback.call( _object );
  35826. }
  35827. this.stopChainedTweens();
  35828. return this;
  35829. };
  35830. this.stopChainedTweens = function () {
  35831. for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) {
  35832. _chainedTweens[ i ].stop();
  35833. }
  35834. };
  35835. this.delay = function ( amount ) {
  35836. _delayTime = amount;
  35837. return this;
  35838. };
  35839. this.repeat = function ( times ) {
  35840. _repeat = times;
  35841. return this;
  35842. };
  35843. this.yoyo = function( yoyo ) {
  35844. _yoyo = yoyo;
  35845. return this;
  35846. };
  35847. this.easing = function ( easing ) {
  35848. _easingFunction = easing;
  35849. return this;
  35850. };
  35851. this.interpolation = function ( interpolation ) {
  35852. _interpolationFunction = interpolation;
  35853. return this;
  35854. };
  35855. this.chain = function () {
  35856. _chainedTweens = arguments;
  35857. return this;
  35858. };
  35859. this.onStart = function ( callback ) {
  35860. _onStartCallback = callback;
  35861. return this;
  35862. };
  35863. this.onUpdate = function ( callback ) {
  35864. _onUpdateCallback = callback;
  35865. return this;
  35866. };
  35867. this.onComplete = function ( callback ) {
  35868. _onCompleteCallback = callback;
  35869. return this;
  35870. };
  35871. this.onStop = function ( callback ) {
  35872. _onStopCallback = callback;
  35873. return this;
  35874. };
  35875. this.update = function ( time ) {
  35876. var property;
  35877. if ( time < _startTime ) {
  35878. return true;
  35879. }
  35880. if ( _onStartCallbackFired === false ) {
  35881. if ( _onStartCallback !== null ) {
  35882. _onStartCallback.call( _object );
  35883. }
  35884. _onStartCallbackFired = true;
  35885. }
  35886. var elapsed = ( time - _startTime ) / _duration;
  35887. elapsed = elapsed > 1 ? 1 : elapsed;
  35888. var value = _easingFunction( elapsed );
  35889. for ( property in _valuesEnd ) {
  35890. var start = _valuesStart[ property ] || 0;
  35891. var end = _valuesEnd[ property ];
  35892. if ( end instanceof Array ) {
  35893. _object[ property ] = _interpolationFunction( end, value );
  35894. } else {
  35895. // Parses relative end values with start as base (e.g.: +10, -3)
  35896. if ( typeof(end) === "string" ) {
  35897. end = start + parseFloat(end, 10);
  35898. }
  35899. // protect against non numeric properties.
  35900. if ( typeof(end) === "number" ) {
  35901. _object[ property ] = start + ( end - start ) * value;
  35902. }
  35903. }
  35904. }
  35905. if ( _onUpdateCallback !== null ) {
  35906. _onUpdateCallback.call( _object, value );
  35907. }
  35908. if ( elapsed == 1 ) {
  35909. if ( _repeat > 0 ) {
  35910. if( isFinite( _repeat ) ) {
  35911. _repeat--;
  35912. }
  35913. // reassign starting values, restart by making startTime = now
  35914. for( property in _valuesStartRepeat ) {
  35915. if ( typeof( _valuesEnd[ property ] ) === "string" ) {
  35916. _valuesStartRepeat[ property ] = _valuesStartRepeat[ property ] + parseFloat(_valuesEnd[ property ], 10);
  35917. }
  35918. if (_yoyo) {
  35919. var tmp = _valuesStartRepeat[ property ];
  35920. _valuesStartRepeat[ property ] = _valuesEnd[ property ];
  35921. _valuesEnd[ property ] = tmp;
  35922. }
  35923. _valuesStart[ property ] = _valuesStartRepeat[ property ];
  35924. }
  35925. if (_yoyo) {
  35926. _reversed = !_reversed;
  35927. }
  35928. _startTime = time + _delayTime;
  35929. return true;
  35930. } else {
  35931. if ( _onCompleteCallback !== null ) {
  35932. _onCompleteCallback.call( _object );
  35933. }
  35934. for ( var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++ ) {
  35935. _chainedTweens[ i ].start( time );
  35936. }
  35937. return false;
  35938. }
  35939. }
  35940. return true;
  35941. };
  35942. };
  35943. TWEEN.Easing = {
  35944. Linear: {
  35945. None: function ( k ) {
  35946. return k;
  35947. }
  35948. },
  35949. Quadratic: {
  35950. In: function ( k ) {
  35951. return k * k;
  35952. },
  35953. Out: function ( k ) {
  35954. return k * ( 2 - k );
  35955. },
  35956. InOut: function ( k ) {
  35957. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  35958. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  35959. }
  35960. },
  35961. Cubic: {
  35962. In: function ( k ) {
  35963. return k * k * k;
  35964. },
  35965. Out: function ( k ) {
  35966. return --k * k * k + 1;
  35967. },
  35968. InOut: function ( k ) {
  35969. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  35970. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  35971. }
  35972. },
  35973. Quartic: {
  35974. In: function ( k ) {
  35975. return k * k * k * k;
  35976. },
  35977. Out: function ( k ) {
  35978. return 1 - ( --k * k * k * k );
  35979. },
  35980. InOut: function ( k ) {
  35981. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  35982. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  35983. }
  35984. },
  35985. Quintic: {
  35986. In: function ( k ) {
  35987. return k * k * k * k * k;
  35988. },
  35989. Out: function ( k ) {
  35990. return --k * k * k * k * k + 1;
  35991. },
  35992. InOut: function ( k ) {
  35993. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  35994. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  35995. }
  35996. },
  35997. Sinusoidal: {
  35998. In: function ( k ) {
  35999. return 1 - Math.cos( k * Math.PI / 2 );
  36000. },
  36001. Out: function ( k ) {
  36002. return Math.sin( k * Math.PI / 2 );
  36003. },
  36004. InOut: function ( k ) {
  36005. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  36006. }
  36007. },
  36008. Exponential: {
  36009. In: function ( k ) {
  36010. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  36011. },
  36012. Out: function ( k ) {
  36013. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  36014. },
  36015. InOut: function ( k ) {
  36016. if ( k === 0 ) return 0;
  36017. if ( k === 1 ) return 1;
  36018. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  36019. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  36020. }
  36021. },
  36022. Circular: {
  36023. In: function ( k ) {
  36024. return 1 - Math.sqrt( 1 - k * k );
  36025. },
  36026. Out: function ( k ) {
  36027. return Math.sqrt( 1 - ( --k * k ) );
  36028. },
  36029. InOut: function ( k ) {
  36030. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  36031. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  36032. }
  36033. },
  36034. Elastic: {
  36035. In: function ( k ) {
  36036. var s, a = 0.1, p = 0.4;
  36037. if ( k === 0 ) return 0;
  36038. if ( k === 1 ) return 1;
  36039. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36040. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36041. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  36042. },
  36043. Out: function ( k ) {
  36044. var s, a = 0.1, p = 0.4;
  36045. if ( k === 0 ) return 0;
  36046. if ( k === 1 ) return 1;
  36047. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36048. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36049. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  36050. },
  36051. InOut: function ( k ) {
  36052. var s, a = 0.1, p = 0.4;
  36053. if ( k === 0 ) return 0;
  36054. if ( k === 1 ) return 1;
  36055. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  36056. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  36057. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  36058. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  36059. }
  36060. },
  36061. Back: {
  36062. In: function ( k ) {
  36063. var s = 1.70158;
  36064. return k * k * ( ( s + 1 ) * k - s );
  36065. },
  36066. Out: function ( k ) {
  36067. var s = 1.70158;
  36068. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  36069. },
  36070. InOut: function ( k ) {
  36071. var s = 1.70158 * 1.525;
  36072. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  36073. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  36074. }
  36075. },
  36076. Bounce: {
  36077. In: function ( k ) {
  36078. return 1 - TWEEN.Easing.Bounce.Out( 1 - k );
  36079. },
  36080. Out: function ( k ) {
  36081. if ( k < ( 1 / 2.75 ) ) {
  36082. return 7.5625 * k * k;
  36083. } else if ( k < ( 2 / 2.75 ) ) {
  36084. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  36085. } else if ( k < ( 2.5 / 2.75 ) ) {
  36086. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  36087. } else {
  36088. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  36089. }
  36090. },
  36091. InOut: function ( k ) {
  36092. if ( k < 0.5 ) return TWEEN.Easing.Bounce.In( k * 2 ) * 0.5;
  36093. return TWEEN.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  36094. }
  36095. }
  36096. };
  36097. TWEEN.Interpolation = {
  36098. Linear: function ( v, k ) {
  36099. var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.Linear;
  36100. if ( k < 0 ) return fn( v[ 0 ], v[ 1 ], f );
  36101. if ( k > 1 ) return fn( v[ m ], v[ m - 1 ], m - f );
  36102. return fn( v[ i ], v[ i + 1 > m ? m : i + 1 ], f - i );
  36103. },
  36104. Bezier: function ( v, k ) {
  36105. var b = 0, n = v.length - 1, pw = Math.pow, bn = TWEEN.Interpolation.Utils.Bernstein, i;
  36106. for ( i = 0; i <= n; i++ ) {
  36107. b += pw( 1 - k, n - i ) * pw( k, i ) * v[ i ] * bn( n, i );
  36108. }
  36109. return b;
  36110. },
  36111. CatmullRom: function ( v, k ) {
  36112. var m = v.length - 1, f = m * k, i = Math.floor( f ), fn = TWEEN.Interpolation.Utils.CatmullRom;
  36113. if ( v[ 0 ] === v[ m ] ) {
  36114. if ( k < 0 ) i = Math.floor( f = m * ( 1 + k ) );
  36115. return fn( v[ ( i - 1 + m ) % m ], v[ i ], v[ ( i + 1 ) % m ], v[ ( i + 2 ) % m ], f - i );
  36116. } else {
  36117. if ( k < 0 ) return v[ 0 ] - ( fn( v[ 0 ], v[ 0 ], v[ 1 ], v[ 1 ], -f ) - v[ 0 ] );
  36118. if ( k > 1 ) return v[ m ] - ( fn( v[ m ], v[ m ], v[ m - 1 ], v[ m - 1 ], f - m ) - v[ m ] );
  36119. 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 );
  36120. }
  36121. },
  36122. Utils: {
  36123. Linear: function ( p0, p1, t ) {
  36124. return ( p1 - p0 ) * t + p0;
  36125. },
  36126. Bernstein: function ( n , i ) {
  36127. var fc = TWEEN.Interpolation.Utils.Factorial;
  36128. return fc( n ) / fc( i ) / fc( n - i );
  36129. },
  36130. Factorial: ( function () {
  36131. var a = [ 1 ];
  36132. return function ( n ) {
  36133. var s = 1, i;
  36134. if ( a[ n ] ) return a[ n ];
  36135. for ( i = n; i > 1; i-- ) s *= i;
  36136. return a[ n ] = s;
  36137. };
  36138. } )(),
  36139. CatmullRom: function ( p0, p1, p2, p3, t ) {
  36140. var v0 = ( p2 - p0 ) * 0.5, v1 = ( p3 - p1 ) * 0.5, t2 = t * t, t3 = t * t2;
  36141. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  36142. }
  36143. }
  36144. };
  36145. // UMD (Universal Module Definition)
  36146. ( function ( root ) {
  36147. if ( typeof define === 'function' && define.amd ) {
  36148. // AMD
  36149. define( [], function () {
  36150. return TWEEN;
  36151. } );
  36152. } else if ( typeof exports === 'object' ) {
  36153. // Node.js
  36154. module.exports = TWEEN;
  36155. } else {
  36156. // Global variable
  36157. root.TWEEN = TWEEN;
  36158. }
  36159. } )( this );
  36160. },{}],50:[function(_dereq_,module,exports){
  36161. (function (global){
  36162. (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.WebVRPolyfill = 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 _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  36163. 'use strict';
  36164. var has = Object.prototype.hasOwnProperty
  36165. , prefix = '~';
  36166. /**
  36167. * Constructor to create a storage for our `EE` objects.
  36168. * An `Events` instance is a plain object whose properties are event names.
  36169. *
  36170. * @constructor
  36171. * @api private
  36172. */
  36173. function Events() {}
  36174. //
  36175. // We try to not inherit from `Object.prototype`. In some engines creating an
  36176. // instance in this way is faster than calling `Object.create(null)` directly.
  36177. // If `Object.create(null)` is not supported we prefix the event names with a
  36178. // character to make sure that the built-in object properties are not
  36179. // overridden or used as an attack vector.
  36180. //
  36181. if (Object.create) {
  36182. Events.prototype = Object.create(null);
  36183. //
  36184. // This hack is needed because the `__proto__` property is still inherited in
  36185. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  36186. //
  36187. if (!new Events().__proto__) prefix = false;
  36188. }
  36189. /**
  36190. * Representation of a single event listener.
  36191. *
  36192. * @param {Function} fn The listener function.
  36193. * @param {Mixed} context The context to invoke the listener with.
  36194. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  36195. * @constructor
  36196. * @api private
  36197. */
  36198. function EE(fn, context, once) {
  36199. this.fn = fn;
  36200. this.context = context;
  36201. this.once = once || false;
  36202. }
  36203. /**
  36204. * Minimal `EventEmitter` interface that is molded against the Node.js
  36205. * `EventEmitter` interface.
  36206. *
  36207. * @constructor
  36208. * @api public
  36209. */
  36210. function EventEmitter() {
  36211. this._events = new Events();
  36212. this._eventsCount = 0;
  36213. }
  36214. /**
  36215. * Return an array listing the events for which the emitter has registered
  36216. * listeners.
  36217. *
  36218. * @returns {Array}
  36219. * @api public
  36220. */
  36221. EventEmitter.prototype.eventNames = function eventNames() {
  36222. var names = []
  36223. , events
  36224. , name;
  36225. if (this._eventsCount === 0) return names;
  36226. for (name in (events = this._events)) {
  36227. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  36228. }
  36229. if (Object.getOwnPropertySymbols) {
  36230. return names.concat(Object.getOwnPropertySymbols(events));
  36231. }
  36232. return names;
  36233. };
  36234. /**
  36235. * Return the listeners registered for a given event.
  36236. *
  36237. * @param {String|Symbol} event The event name.
  36238. * @param {Boolean} exists Only check if there are listeners.
  36239. * @returns {Array|Boolean}
  36240. * @api public
  36241. */
  36242. EventEmitter.prototype.listeners = function listeners(event, exists) {
  36243. var evt = prefix ? prefix + event : event
  36244. , available = this._events[evt];
  36245. if (exists) return !!available;
  36246. if (!available) return [];
  36247. if (available.fn) return [available.fn];
  36248. for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) {
  36249. ee[i] = available[i].fn;
  36250. }
  36251. return ee;
  36252. };
  36253. /**
  36254. * Calls each of the listeners registered for a given event.
  36255. *
  36256. * @param {String|Symbol} event The event name.
  36257. * @returns {Boolean} `true` if the event had listeners, else `false`.
  36258. * @api public
  36259. */
  36260. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  36261. var evt = prefix ? prefix + event : event;
  36262. if (!this._events[evt]) return false;
  36263. var listeners = this._events[evt]
  36264. , len = arguments.length
  36265. , args
  36266. , i;
  36267. if (listeners.fn) {
  36268. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  36269. switch (len) {
  36270. case 1: return listeners.fn.call(listeners.context), true;
  36271. case 2: return listeners.fn.call(listeners.context, a1), true;
  36272. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  36273. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  36274. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  36275. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  36276. }
  36277. for (i = 1, args = new Array(len -1); i < len; i++) {
  36278. args[i - 1] = arguments[i];
  36279. }
  36280. listeners.fn.apply(listeners.context, args);
  36281. } else {
  36282. var length = listeners.length
  36283. , j;
  36284. for (i = 0; i < length; i++) {
  36285. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  36286. switch (len) {
  36287. case 1: listeners[i].fn.call(listeners[i].context); break;
  36288. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  36289. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  36290. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  36291. default:
  36292. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  36293. args[j - 1] = arguments[j];
  36294. }
  36295. listeners[i].fn.apply(listeners[i].context, args);
  36296. }
  36297. }
  36298. }
  36299. return true;
  36300. };
  36301. /**
  36302. * Add a listener for a given event.
  36303. *
  36304. * @param {String|Symbol} event The event name.
  36305. * @param {Function} fn The listener function.
  36306. * @param {Mixed} [context=this] The context to invoke the listener with.
  36307. * @returns {EventEmitter} `this`.
  36308. * @api public
  36309. */
  36310. EventEmitter.prototype.on = function on(event, fn, context) {
  36311. var listener = new EE(fn, context || this)
  36312. , evt = prefix ? prefix + event : event;
  36313. if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
  36314. else if (!this._events[evt].fn) this._events[evt].push(listener);
  36315. else this._events[evt] = [this._events[evt], listener];
  36316. return this;
  36317. };
  36318. /**
  36319. * Add a one-time listener for a given event.
  36320. *
  36321. * @param {String|Symbol} event The event name.
  36322. * @param {Function} fn The listener function.
  36323. * @param {Mixed} [context=this] The context to invoke the listener with.
  36324. * @returns {EventEmitter} `this`.
  36325. * @api public
  36326. */
  36327. EventEmitter.prototype.once = function once(event, fn, context) {
  36328. var listener = new EE(fn, context || this, true)
  36329. , evt = prefix ? prefix + event : event;
  36330. if (!this._events[evt]) this._events[evt] = listener, this._eventsCount++;
  36331. else if (!this._events[evt].fn) this._events[evt].push(listener);
  36332. else this._events[evt] = [this._events[evt], listener];
  36333. return this;
  36334. };
  36335. /**
  36336. * Remove the listeners of a given event.
  36337. *
  36338. * @param {String|Symbol} event The event name.
  36339. * @param {Function} fn Only remove the listeners that match this function.
  36340. * @param {Mixed} context Only remove the listeners that have this context.
  36341. * @param {Boolean} once Only remove one-time listeners.
  36342. * @returns {EventEmitter} `this`.
  36343. * @api public
  36344. */
  36345. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  36346. var evt = prefix ? prefix + event : event;
  36347. if (!this._events[evt]) return this;
  36348. if (!fn) {
  36349. if (--this._eventsCount === 0) this._events = new Events();
  36350. else delete this._events[evt];
  36351. return this;
  36352. }
  36353. var listeners = this._events[evt];
  36354. if (listeners.fn) {
  36355. if (
  36356. listeners.fn === fn
  36357. && (!once || listeners.once)
  36358. && (!context || listeners.context === context)
  36359. ) {
  36360. if (--this._eventsCount === 0) this._events = new Events();
  36361. else delete this._events[evt];
  36362. }
  36363. } else {
  36364. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  36365. if (
  36366. listeners[i].fn !== fn
  36367. || (once && !listeners[i].once)
  36368. || (context && listeners[i].context !== context)
  36369. ) {
  36370. events.push(listeners[i]);
  36371. }
  36372. }
  36373. //
  36374. // Reset the array, or remove it completely if we have no more listeners.
  36375. //
  36376. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  36377. else if (--this._eventsCount === 0) this._events = new Events();
  36378. else delete this._events[evt];
  36379. }
  36380. return this;
  36381. };
  36382. /**
  36383. * Remove all listeners, or those of the specified event.
  36384. *
  36385. * @param {String|Symbol} [event] The event name.
  36386. * @returns {EventEmitter} `this`.
  36387. * @api public
  36388. */
  36389. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  36390. var evt;
  36391. if (event) {
  36392. evt = prefix ? prefix + event : event;
  36393. if (this._events[evt]) {
  36394. if (--this._eventsCount === 0) this._events = new Events();
  36395. else delete this._events[evt];
  36396. }
  36397. } else {
  36398. this._events = new Events();
  36399. this._eventsCount = 0;
  36400. }
  36401. return this;
  36402. };
  36403. //
  36404. // Alias methods names because people roll like that.
  36405. //
  36406. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  36407. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  36408. //
  36409. // This function doesn't apply anymore.
  36410. //
  36411. EventEmitter.prototype.setMaxListeners = function setMaxListeners() {
  36412. return this;
  36413. };
  36414. //
  36415. // Expose the prefix.
  36416. //
  36417. EventEmitter.prefixed = prefix;
  36418. //
  36419. // Allow `EventEmitter` to be imported as module namespace.
  36420. //
  36421. EventEmitter.EventEmitter = EventEmitter;
  36422. //
  36423. // Expose the module.
  36424. //
  36425. if ('undefined' !== typeof module) {
  36426. module.exports = EventEmitter;
  36427. }
  36428. },{}],2:[function(_dereq_,module,exports){
  36429. 'use strict';
  36430. /* eslint-disable no-unused-vars */
  36431. var hasOwnProperty = Object.prototype.hasOwnProperty;
  36432. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  36433. function toObject(val) {
  36434. if (val === null || val === undefined) {
  36435. throw new TypeError('Object.assign cannot be called with null or undefined');
  36436. }
  36437. return Object(val);
  36438. }
  36439. function shouldUseNative() {
  36440. try {
  36441. if (!Object.assign) {
  36442. return false;
  36443. }
  36444. // Detect buggy property enumeration order in older V8 versions.
  36445. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  36446. var test1 = new String('abc'); // eslint-disable-line
  36447. test1[5] = 'de';
  36448. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  36449. return false;
  36450. }
  36451. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  36452. var test2 = {};
  36453. for (var i = 0; i < 10; i++) {
  36454. test2['_' + String.fromCharCode(i)] = i;
  36455. }
  36456. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  36457. return test2[n];
  36458. });
  36459. if (order2.join('') !== '0123456789') {
  36460. return false;
  36461. }
  36462. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  36463. var test3 = {};
  36464. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  36465. test3[letter] = letter;
  36466. });
  36467. if (Object.keys(Object.assign({}, test3)).join('') !==
  36468. 'abcdefghijklmnopqrst') {
  36469. return false;
  36470. }
  36471. return true;
  36472. } catch (e) {
  36473. // We don't expect any of the above to throw, but better to be safe.
  36474. return false;
  36475. }
  36476. }
  36477. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  36478. var from;
  36479. var to = toObject(target);
  36480. var symbols;
  36481. for (var s = 1; s < arguments.length; s++) {
  36482. from = Object(arguments[s]);
  36483. for (var key in from) {
  36484. if (hasOwnProperty.call(from, key)) {
  36485. to[key] = from[key];
  36486. }
  36487. }
  36488. if (Object.getOwnPropertySymbols) {
  36489. symbols = Object.getOwnPropertySymbols(from);
  36490. for (var i = 0; i < symbols.length; i++) {
  36491. if (propIsEnumerable.call(from, symbols[i])) {
  36492. to[symbols[i]] = from[symbols[i]];
  36493. }
  36494. }
  36495. }
  36496. }
  36497. return to;
  36498. };
  36499. },{}],3:[function(_dereq_,module,exports){
  36500. /*
  36501. * Copyright 2015 Google Inc. All Rights Reserved.
  36502. * Licensed under the Apache License, Version 2.0 (the "License");
  36503. * you may not use this file except in compliance with the License.
  36504. * You may obtain a copy of the License at
  36505. *
  36506. * http://www.apache.org/licenses/LICENSE-2.0
  36507. *
  36508. * Unless required by applicable law or agreed to in writing, software
  36509. * distributed under the License is distributed on an "AS IS" BASIS,
  36510. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36511. * See the License for the specific language governing permissions and
  36512. * limitations under the License.
  36513. */
  36514. var Util = _dereq_('./util.js');
  36515. var WakeLock = _dereq_('./wakelock.js');
  36516. // Start at a higher number to reduce chance of conflict.
  36517. var nextDisplayId = 1000;
  36518. var hasShowDeprecationWarning = false;
  36519. var defaultLeftBounds = [0, 0, 0.5, 1];
  36520. var defaultRightBounds = [0.5, 0, 0.5, 1];
  36521. /**
  36522. * The base class for all VR frame data.
  36523. */
  36524. function VRFrameData() {
  36525. this.leftProjectionMatrix = new Float32Array(16);
  36526. this.leftViewMatrix = new Float32Array(16);
  36527. this.rightProjectionMatrix = new Float32Array(16);
  36528. this.rightViewMatrix = new Float32Array(16);
  36529. this.pose = null;
  36530. };
  36531. /**
  36532. * The base class for all VR displays.
  36533. */
  36534. function VRDisplay() {
  36535. this.isPolyfilled = true;
  36536. this.displayId = nextDisplayId++;
  36537. this.displayName = 'webvr-polyfill displayName';
  36538. this.depthNear = 0.01;
  36539. this.depthFar = 10000.0;
  36540. this.isConnected = true;
  36541. this.isPresenting = false;
  36542. this.capabilities = {
  36543. hasPosition: false,
  36544. hasOrientation: false,
  36545. hasExternalDisplay: false,
  36546. canPresent: false,
  36547. maxLayers: 1
  36548. };
  36549. this.stageParameters = null;
  36550. // "Private" members.
  36551. this.waitingForPresent_ = false;
  36552. this.layer_ = null;
  36553. this.fullscreenElement_ = null;
  36554. this.fullscreenWrapper_ = null;
  36555. this.fullscreenElementCachedStyle_ = null;
  36556. this.fullscreenEventTarget_ = null;
  36557. this.fullscreenChangeHandler_ = null;
  36558. this.fullscreenErrorHandler_ = null;
  36559. this.wakelock_ = new WakeLock();
  36560. }
  36561. VRDisplay.prototype.getFrameData = function(frameData) {
  36562. // TODO: Technically this should retain it's value for the duration of a frame
  36563. // but I doubt that's practical to do in javascript.
  36564. return Util.frameDataFromPose(frameData, this.getPose(), this);
  36565. };
  36566. VRDisplay.prototype.getPose = function() {
  36567. // TODO: Technically this should retain it's value for the duration of a frame
  36568. // but I doubt that's practical to do in javascript.
  36569. return this.getImmediatePose();
  36570. };
  36571. VRDisplay.prototype.requestAnimationFrame = function(callback) {
  36572. return window.requestAnimationFrame(callback);
  36573. };
  36574. VRDisplay.prototype.cancelAnimationFrame = function(id) {
  36575. return window.cancelAnimationFrame(id);
  36576. };
  36577. VRDisplay.prototype.wrapForFullscreen = function(element) {
  36578. // Don't wrap in iOS.
  36579. if (Util.isIOS()) {
  36580. return element;
  36581. }
  36582. if (!this.fullscreenWrapper_) {
  36583. this.fullscreenWrapper_ = document.createElement('div');
  36584. var cssProperties = [
  36585. 'height: ' + Math.min(screen.height, screen.width) + 'px !important',
  36586. 'top: 0 !important',
  36587. 'left: 0 !important',
  36588. 'right: 0 !important',
  36589. 'border: 0',
  36590. 'margin: 0',
  36591. 'padding: 0',
  36592. 'z-index: 999999 !important',
  36593. 'position: fixed',
  36594. ];
  36595. this.fullscreenWrapper_.setAttribute('style', cssProperties.join('; ') + ';');
  36596. this.fullscreenWrapper_.classList.add('webvr-polyfill-fullscreen-wrapper');
  36597. }
  36598. if (this.fullscreenElement_ == element) {
  36599. return this.fullscreenWrapper_;
  36600. }
  36601. // Remove any previously applied wrappers
  36602. this.removeFullscreenWrapper();
  36603. this.fullscreenElement_ = element;
  36604. var parent = this.fullscreenElement_.parentElement;
  36605. parent.insertBefore(this.fullscreenWrapper_, this.fullscreenElement_);
  36606. parent.removeChild(this.fullscreenElement_);
  36607. this.fullscreenWrapper_.insertBefore(this.fullscreenElement_, this.fullscreenWrapper_.firstChild);
  36608. this.fullscreenElementCachedStyle_ = this.fullscreenElement_.getAttribute('style');
  36609. var self = this;
  36610. function applyFullscreenElementStyle() {
  36611. if (!self.fullscreenElement_) {
  36612. return;
  36613. }
  36614. var cssProperties = [
  36615. 'position: absolute',
  36616. 'top: 0',
  36617. 'left: 0',
  36618. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  36619. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  36620. 'border: 0',
  36621. 'margin: 0',
  36622. 'padding: 0',
  36623. ];
  36624. self.fullscreenElement_.setAttribute('style', cssProperties.join('; ') + ';');
  36625. }
  36626. applyFullscreenElementStyle();
  36627. return this.fullscreenWrapper_;
  36628. };
  36629. VRDisplay.prototype.removeFullscreenWrapper = function() {
  36630. if (!this.fullscreenElement_) {
  36631. return;
  36632. }
  36633. var element = this.fullscreenElement_;
  36634. if (this.fullscreenElementCachedStyle_) {
  36635. element.setAttribute('style', this.fullscreenElementCachedStyle_);
  36636. } else {
  36637. element.removeAttribute('style');
  36638. }
  36639. this.fullscreenElement_ = null;
  36640. this.fullscreenElementCachedStyle_ = null;
  36641. var parent = this.fullscreenWrapper_.parentElement;
  36642. this.fullscreenWrapper_.removeChild(element);
  36643. parent.insertBefore(element, this.fullscreenWrapper_);
  36644. parent.removeChild(this.fullscreenWrapper_);
  36645. return element;
  36646. };
  36647. VRDisplay.prototype.requestPresent = function(layers) {
  36648. var wasPresenting = this.isPresenting;
  36649. var self = this;
  36650. if (!(layers instanceof Array)) {
  36651. if (!hasShowDeprecationWarning) {
  36652. console.warn("Using a deprecated form of requestPresent. Should pass in an array of VRLayers.");
  36653. hasShowDeprecationWarning = true;
  36654. }
  36655. layers = [layers];
  36656. }
  36657. return new Promise(function(resolve, reject) {
  36658. if (!self.capabilities.canPresent) {
  36659. reject(new Error('VRDisplay is not capable of presenting.'));
  36660. return;
  36661. }
  36662. if (layers.length == 0 || layers.length > self.capabilities.maxLayers) {
  36663. reject(new Error('Invalid number of layers.'));
  36664. return;
  36665. }
  36666. var incomingLayer = layers[0];
  36667. if (!incomingLayer.source) {
  36668. /*
  36669. todo: figure out the correct behavior if the source is not provided.
  36670. see https://github.com/w3c/webvr/issues/58
  36671. */
  36672. resolve();
  36673. return;
  36674. }
  36675. var leftBounds = incomingLayer.leftBounds || defaultLeftBounds;
  36676. var rightBounds = incomingLayer.rightBounds || defaultRightBounds;
  36677. if (wasPresenting) {
  36678. // Already presenting, just changing configuration
  36679. var layer = self.layer_;
  36680. if (layer.source !== incomingLayer.source) {
  36681. layer.source = incomingLayer.source;
  36682. }
  36683. for (var i = 0; i < 4; i++) {
  36684. if (layer.leftBounds[i] !== leftBounds[i]) {
  36685. layer.leftBounds[i] = leftBounds[i];
  36686. }
  36687. if (layer.rightBounds[i] !== rightBounds[i]) {
  36688. layer.rightBounds[i] = rightBounds[i];
  36689. }
  36690. }
  36691. resolve();
  36692. return;
  36693. }
  36694. // Was not already presenting.
  36695. self.layer_ = {
  36696. predistorted: incomingLayer.predistorted,
  36697. source: incomingLayer.source,
  36698. leftBounds: leftBounds.slice(0),
  36699. rightBounds: rightBounds.slice(0)
  36700. };
  36701. self.waitingForPresent_ = false;
  36702. if (self.layer_ && self.layer_.source) {
  36703. var fullscreenElement = self.wrapForFullscreen(self.layer_.source);
  36704. function onFullscreenChange() {
  36705. var actualFullscreenElement = Util.getFullscreenElement();
  36706. self.isPresenting = (fullscreenElement === actualFullscreenElement);
  36707. if (self.isPresenting) {
  36708. if (screen.orientation && screen.orientation.lock) {
  36709. screen.orientation.lock('landscape-primary').catch(function(error){
  36710. console.error('screen.orientation.lock() failed due to', error.message)
  36711. });
  36712. }
  36713. self.waitingForPresent_ = false;
  36714. self.beginPresent_();
  36715. resolve();
  36716. } else {
  36717. if (screen.orientation && screen.orientation.unlock) {
  36718. screen.orientation.unlock();
  36719. }
  36720. self.removeFullscreenWrapper();
  36721. self.wakelock_.release();
  36722. self.endPresent_();
  36723. self.removeFullscreenListeners_();
  36724. }
  36725. self.fireVRDisplayPresentChange_();
  36726. }
  36727. function onFullscreenError() {
  36728. if (!self.waitingForPresent_) {
  36729. return;
  36730. }
  36731. self.removeFullscreenWrapper();
  36732. self.removeFullscreenListeners_();
  36733. self.wakelock_.release();
  36734. self.waitingForPresent_ = false;
  36735. self.isPresenting = false;
  36736. reject(new Error('Unable to present.'));
  36737. }
  36738. self.addFullscreenListeners_(fullscreenElement,
  36739. onFullscreenChange, onFullscreenError);
  36740. if (Util.requestFullscreen(fullscreenElement)) {
  36741. self.wakelock_.request();
  36742. self.waitingForPresent_ = true;
  36743. } else if (Util.isIOS() || Util.isWebViewAndroid()) {
  36744. // *sigh* Just fake it.
  36745. self.wakelock_.request();
  36746. self.isPresenting = true;
  36747. self.beginPresent_();
  36748. self.fireVRDisplayPresentChange_();
  36749. resolve();
  36750. }
  36751. }
  36752. if (!self.waitingForPresent_ && !Util.isIOS()) {
  36753. Util.exitFullscreen();
  36754. reject(new Error('Unable to present.'));
  36755. }
  36756. });
  36757. };
  36758. VRDisplay.prototype.exitPresent = function() {
  36759. var wasPresenting = this.isPresenting;
  36760. var self = this;
  36761. this.isPresenting = false;
  36762. this.layer_ = null;
  36763. this.wakelock_.release();
  36764. return new Promise(function(resolve, reject) {
  36765. if (wasPresenting) {
  36766. if (!Util.exitFullscreen() && Util.isIOS()) {
  36767. self.endPresent_();
  36768. self.fireVRDisplayPresentChange_();
  36769. }
  36770. if(Util.isWebViewAndroid()) {
  36771. self.removeFullscreenWrapper();
  36772. self.removeFullscreenListeners_();
  36773. self.endPresent_();
  36774. self.fireVRDisplayPresentChange_();
  36775. }
  36776. resolve();
  36777. } else {
  36778. reject(new Error('Was not presenting to VRDisplay.'));
  36779. }
  36780. });
  36781. };
  36782. VRDisplay.prototype.getLayers = function() {
  36783. if (this.layer_) {
  36784. return [this.layer_];
  36785. }
  36786. return [];
  36787. };
  36788. VRDisplay.prototype.fireVRDisplayPresentChange_ = function() {
  36789. var event = new CustomEvent('vrdisplaypresentchange', {detail: {display: this}});
  36790. window.dispatchEvent(event);
  36791. };
  36792. VRDisplay.prototype.addFullscreenListeners_ = function(element, changeHandler, errorHandler) {
  36793. this.removeFullscreenListeners_();
  36794. this.fullscreenEventTarget_ = element;
  36795. this.fullscreenChangeHandler_ = changeHandler;
  36796. this.fullscreenErrorHandler_ = errorHandler;
  36797. if (changeHandler) {
  36798. if (document.fullscreenEnabled) {
  36799. element.addEventListener('fullscreenchange', changeHandler, false);
  36800. } else if (document.webkitFullscreenEnabled) {
  36801. element.addEventListener('webkitfullscreenchange', changeHandler, false);
  36802. } else if (document.mozFullScreenEnabled) {
  36803. document.addEventListener('mozfullscreenchange', changeHandler, false);
  36804. } else if (document.msFullscreenEnabled) {
  36805. element.addEventListener('msfullscreenchange', changeHandler, false);
  36806. }
  36807. }
  36808. if (errorHandler) {
  36809. if (document.fullscreenEnabled) {
  36810. element.addEventListener('fullscreenerror', errorHandler, false);
  36811. } else if (document.webkitFullscreenEnabled) {
  36812. element.addEventListener('webkitfullscreenerror', errorHandler, false);
  36813. } else if (document.mozFullScreenEnabled) {
  36814. document.addEventListener('mozfullscreenerror', errorHandler, false);
  36815. } else if (document.msFullscreenEnabled) {
  36816. element.addEventListener('msfullscreenerror', errorHandler, false);
  36817. }
  36818. }
  36819. };
  36820. VRDisplay.prototype.removeFullscreenListeners_ = function() {
  36821. if (!this.fullscreenEventTarget_)
  36822. return;
  36823. var element = this.fullscreenEventTarget_;
  36824. if (this.fullscreenChangeHandler_) {
  36825. var changeHandler = this.fullscreenChangeHandler_;
  36826. element.removeEventListener('fullscreenchange', changeHandler, false);
  36827. element.removeEventListener('webkitfullscreenchange', changeHandler, false);
  36828. document.removeEventListener('mozfullscreenchange', changeHandler, false);
  36829. element.removeEventListener('msfullscreenchange', changeHandler, false);
  36830. }
  36831. if (this.fullscreenErrorHandler_) {
  36832. var errorHandler = this.fullscreenErrorHandler_;
  36833. element.removeEventListener('fullscreenerror', errorHandler, false);
  36834. element.removeEventListener('webkitfullscreenerror', errorHandler, false);
  36835. document.removeEventListener('mozfullscreenerror', errorHandler, false);
  36836. element.removeEventListener('msfullscreenerror', errorHandler, false);
  36837. }
  36838. this.fullscreenEventTarget_ = null;
  36839. this.fullscreenChangeHandler_ = null;
  36840. this.fullscreenErrorHandler_ = null;
  36841. };
  36842. VRDisplay.prototype.beginPresent_ = function() {
  36843. // Override to add custom behavior when presentation begins.
  36844. };
  36845. VRDisplay.prototype.endPresent_ = function() {
  36846. // Override to add custom behavior when presentation ends.
  36847. };
  36848. VRDisplay.prototype.submitFrame = function(pose) {
  36849. // Override to add custom behavior for frame submission.
  36850. };
  36851. VRDisplay.prototype.getEyeParameters = function(whichEye) {
  36852. // Override to return accurate eye parameters if canPresent is true.
  36853. return null;
  36854. };
  36855. /*
  36856. * Deprecated classes
  36857. */
  36858. /**
  36859. * The base class for all VR devices. (Deprecated)
  36860. */
  36861. function VRDevice() {
  36862. this.isPolyfilled = true;
  36863. this.hardwareUnitId = 'webvr-polyfill hardwareUnitId';
  36864. this.deviceId = 'webvr-polyfill deviceId';
  36865. this.deviceName = 'webvr-polyfill deviceName';
  36866. }
  36867. /**
  36868. * The base class for all VR HMD devices. (Deprecated)
  36869. */
  36870. function HMDVRDevice() {
  36871. }
  36872. HMDVRDevice.prototype = new VRDevice();
  36873. /**
  36874. * The base class for all VR position sensor devices. (Deprecated)
  36875. */
  36876. function PositionSensorVRDevice() {
  36877. }
  36878. PositionSensorVRDevice.prototype = new VRDevice();
  36879. module.exports.VRFrameData = VRFrameData;
  36880. module.exports.VRDisplay = VRDisplay;
  36881. module.exports.VRDevice = VRDevice;
  36882. module.exports.HMDVRDevice = HMDVRDevice;
  36883. module.exports.PositionSensorVRDevice = PositionSensorVRDevice;
  36884. },{"./util.js":23,"./wakelock.js":25}],4:[function(_dereq_,module,exports){
  36885. /*
  36886. * Copyright 2016 Google Inc. All Rights Reserved.
  36887. * Licensed under the Apache License, Version 2.0 (the "License");
  36888. * you may not use this file except in compliance with the License.
  36889. * You may obtain a copy of the License at
  36890. *
  36891. * http://www.apache.org/licenses/LICENSE-2.0
  36892. *
  36893. * Unless required by applicable law or agreed to in writing, software
  36894. * distributed under the License is distributed on an "AS IS" BASIS,
  36895. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  36896. * See the License for the specific language governing permissions and
  36897. * limitations under the License.
  36898. */
  36899. var CardboardUI = _dereq_('./cardboard-ui.js');
  36900. var Util = _dereq_('./util.js');
  36901. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  36902. var distortionVS = [
  36903. 'attribute vec2 position;',
  36904. 'attribute vec3 texCoord;',
  36905. 'varying vec2 vTexCoord;',
  36906. 'uniform vec4 viewportOffsetScale[2];',
  36907. 'void main() {',
  36908. ' vec4 viewport = viewportOffsetScale[int(texCoord.z)];',
  36909. ' vTexCoord = (texCoord.xy * viewport.zw) + viewport.xy;',
  36910. ' gl_Position = vec4( position, 1.0, 1.0 );',
  36911. '}',
  36912. ].join('\n');
  36913. var distortionFS = [
  36914. 'precision mediump float;',
  36915. 'uniform sampler2D diffuse;',
  36916. 'varying vec2 vTexCoord;',
  36917. 'void main() {',
  36918. ' gl_FragColor = texture2D(diffuse, vTexCoord);',
  36919. '}',
  36920. ].join('\n');
  36921. /**
  36922. * A mesh-based distorter.
  36923. */
  36924. function CardboardDistorter(gl) {
  36925. this.gl = gl;
  36926. this.ctxAttribs = gl.getContextAttributes();
  36927. this.meshWidth = 20;
  36928. this.meshHeight = 20;
  36929. this.bufferScale = WebVRConfig.BUFFER_SCALE;
  36930. this.bufferWidth = gl.drawingBufferWidth;
  36931. this.bufferHeight = gl.drawingBufferHeight;
  36932. // Patching support
  36933. this.realBindFramebuffer = gl.bindFramebuffer;
  36934. this.realEnable = gl.enable;
  36935. this.realDisable = gl.disable;
  36936. this.realColorMask = gl.colorMask;
  36937. this.realClearColor = gl.clearColor;
  36938. this.realViewport = gl.viewport;
  36939. if (!Util.isIOS()) {
  36940. this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width');
  36941. this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height');
  36942. }
  36943. this.isPatched = false;
  36944. // State tracking
  36945. this.lastBoundFramebuffer = null;
  36946. this.cullFace = false;
  36947. this.depthTest = false;
  36948. this.blend = false;
  36949. this.scissorTest = false;
  36950. this.stencilTest = false;
  36951. this.viewport = [0, 0, 0, 0];
  36952. this.colorMask = [true, true, true, true];
  36953. this.clearColor = [0, 0, 0, 0];
  36954. this.attribs = {
  36955. position: 0,
  36956. texCoord: 1
  36957. };
  36958. this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs);
  36959. this.uniforms = Util.getProgramUniforms(gl, this.program);
  36960. this.viewportOffsetScale = new Float32Array(8);
  36961. this.setTextureBounds();
  36962. this.vertexBuffer = gl.createBuffer();
  36963. this.indexBuffer = gl.createBuffer();
  36964. this.indexCount = 0;
  36965. this.renderTarget = gl.createTexture();
  36966. this.framebuffer = gl.createFramebuffer();
  36967. this.depthStencilBuffer = null;
  36968. this.depthBuffer = null;
  36969. this.stencilBuffer = null;
  36970. if (this.ctxAttribs.depth && this.ctxAttribs.stencil) {
  36971. this.depthStencilBuffer = gl.createRenderbuffer();
  36972. } else if (this.ctxAttribs.depth) {
  36973. this.depthBuffer = gl.createRenderbuffer();
  36974. } else if (this.ctxAttribs.stencil) {
  36975. this.stencilBuffer = gl.createRenderbuffer();
  36976. }
  36977. this.patch();
  36978. this.onResize();
  36979. if (!WebVRConfig.CARDBOARD_UI_DISABLED) {
  36980. this.cardboardUI = new CardboardUI(gl);
  36981. }
  36982. };
  36983. /**
  36984. * Tears down all the resources created by the distorter and removes any
  36985. * patches.
  36986. */
  36987. CardboardDistorter.prototype.destroy = function() {
  36988. var gl = this.gl;
  36989. this.unpatch();
  36990. gl.deleteProgram(this.program);
  36991. gl.deleteBuffer(this.vertexBuffer);
  36992. gl.deleteBuffer(this.indexBuffer);
  36993. gl.deleteTexture(this.renderTarget);
  36994. gl.deleteFramebuffer(this.framebuffer);
  36995. if (this.depthStencilBuffer) {
  36996. gl.deleteRenderbuffer(this.depthStencilBuffer);
  36997. }
  36998. if (this.depthBuffer) {
  36999. gl.deleteRenderbuffer(this.depthBuffer);
  37000. }
  37001. if (this.stencilBuffer) {
  37002. gl.deleteRenderbuffer(this.stencilBuffer);
  37003. }
  37004. if (this.cardboardUI) {
  37005. this.cardboardUI.destroy();
  37006. }
  37007. };
  37008. /**
  37009. * Resizes the backbuffer to match the canvas width and height.
  37010. */
  37011. CardboardDistorter.prototype.onResize = function() {
  37012. var gl = this.gl;
  37013. var self = this;
  37014. var glState = [
  37015. gl.RENDERBUFFER_BINDING,
  37016. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37017. ];
  37018. WGLUPreserveGLState(gl, glState, function(gl) {
  37019. // Bind real backbuffer and clear it once. We don't need to clear it again
  37020. // after that because we're overwriting the same area every frame.
  37021. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37022. // Put things in a good state
  37023. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37024. self.realColorMask.call(gl, true, true, true, true);
  37025. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37026. self.realClearColor.call(gl, 0, 0, 0, 1);
  37027. gl.clear(gl.COLOR_BUFFER_BIT);
  37028. // Now bind and resize the fake backbuffer
  37029. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.framebuffer);
  37030. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37031. gl.texImage2D(gl.TEXTURE_2D, 0, self.ctxAttribs.alpha ? gl.RGBA : gl.RGB,
  37032. self.bufferWidth, self.bufferHeight, 0,
  37033. self.ctxAttribs.alpha ? gl.RGBA : gl.RGB, gl.UNSIGNED_BYTE, null);
  37034. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  37035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  37036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  37037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  37038. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.renderTarget, 0);
  37039. if (self.ctxAttribs.depth && self.ctxAttribs.stencil) {
  37040. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthStencilBuffer);
  37041. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL,
  37042. self.bufferWidth, self.bufferHeight);
  37043. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT,
  37044. gl.RENDERBUFFER, self.depthStencilBuffer);
  37045. } else if (self.ctxAttribs.depth) {
  37046. gl.bindRenderbuffer(gl.RENDERBUFFER, self.depthBuffer);
  37047. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16,
  37048. self.bufferWidth, self.bufferHeight);
  37049. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT,
  37050. gl.RENDERBUFFER, self.depthBuffer);
  37051. } else if (self.ctxAttribs.stencil) {
  37052. gl.bindRenderbuffer(gl.RENDERBUFFER, self.stencilBuffer);
  37053. gl.renderbufferStorage(gl.RENDERBUFFER, gl.STENCIL_INDEX8,
  37054. self.bufferWidth, self.bufferHeight);
  37055. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT,
  37056. gl.RENDERBUFFER, self.stencilBuffer);
  37057. }
  37058. if (!gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE) {
  37059. console.error('Framebuffer incomplete!');
  37060. }
  37061. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37062. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37063. self.realColorMask.apply(gl, self.colorMask);
  37064. self.realViewport.apply(gl, self.viewport);
  37065. self.realClearColor.apply(gl, self.clearColor);
  37066. });
  37067. if (this.cardboardUI) {
  37068. this.cardboardUI.onResize();
  37069. }
  37070. };
  37071. CardboardDistorter.prototype.patch = function() {
  37072. if (this.isPatched) {
  37073. return;
  37074. }
  37075. var self = this;
  37076. var canvas = this.gl.canvas;
  37077. var gl = this.gl;
  37078. if (!Util.isIOS()) {
  37079. canvas.width = Util.getScreenWidth() * this.bufferScale;
  37080. canvas.height = Util.getScreenHeight() * this.bufferScale;
  37081. Object.defineProperty(canvas, 'width', {
  37082. configurable: true,
  37083. enumerable: true,
  37084. get: function() {
  37085. return self.bufferWidth;
  37086. },
  37087. set: function(value) {
  37088. self.bufferWidth = value;
  37089. self.realCanvasWidth.set.call(canvas, value);
  37090. self.onResize();
  37091. }
  37092. });
  37093. Object.defineProperty(canvas, 'height', {
  37094. configurable: true,
  37095. enumerable: true,
  37096. get: function() {
  37097. return self.bufferHeight;
  37098. },
  37099. set: function(value) {
  37100. self.bufferHeight = value;
  37101. self.realCanvasHeight.set.call(canvas, value);
  37102. self.onResize();
  37103. }
  37104. });
  37105. }
  37106. this.lastBoundFramebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  37107. if (this.lastBoundFramebuffer == null) {
  37108. this.lastBoundFramebuffer = this.framebuffer;
  37109. this.gl.bindFramebuffer(gl.FRAMEBUFFER, this.framebuffer);
  37110. }
  37111. this.gl.bindFramebuffer = function(target, framebuffer) {
  37112. self.lastBoundFramebuffer = framebuffer ? framebuffer : self.framebuffer;
  37113. // Silently make calls to bind the default framebuffer bind ours instead.
  37114. self.realBindFramebuffer.call(gl, target, self.lastBoundFramebuffer);
  37115. };
  37116. this.cullFace = gl.getParameter(gl.CULL_FACE);
  37117. this.depthTest = gl.getParameter(gl.DEPTH_TEST);
  37118. this.blend = gl.getParameter(gl.BLEND);
  37119. this.scissorTest = gl.getParameter(gl.SCISSOR_TEST);
  37120. this.stencilTest = gl.getParameter(gl.STENCIL_TEST);
  37121. gl.enable = function(pname) {
  37122. switch (pname) {
  37123. case gl.CULL_FACE: self.cullFace = true; break;
  37124. case gl.DEPTH_TEST: self.depthTest = true; break;
  37125. case gl.BLEND: self.blend = true; break;
  37126. case gl.SCISSOR_TEST: self.scissorTest = true; break;
  37127. case gl.STENCIL_TEST: self.stencilTest = true; break;
  37128. }
  37129. self.realEnable.call(gl, pname);
  37130. };
  37131. gl.disable = function(pname) {
  37132. switch (pname) {
  37133. case gl.CULL_FACE: self.cullFace = false; break;
  37134. case gl.DEPTH_TEST: self.depthTest = false; break;
  37135. case gl.BLEND: self.blend = false; break;
  37136. case gl.SCISSOR_TEST: self.scissorTest = false; break;
  37137. case gl.STENCIL_TEST: self.stencilTest = false; break;
  37138. }
  37139. self.realDisable.call(gl, pname);
  37140. };
  37141. this.colorMask = gl.getParameter(gl.COLOR_WRITEMASK);
  37142. gl.colorMask = function(r, g, b, a) {
  37143. self.colorMask[0] = r;
  37144. self.colorMask[1] = g;
  37145. self.colorMask[2] = b;
  37146. self.colorMask[3] = a;
  37147. self.realColorMask.call(gl, r, g, b, a);
  37148. };
  37149. this.clearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
  37150. gl.clearColor = function(r, g, b, a) {
  37151. self.clearColor[0] = r;
  37152. self.clearColor[1] = g;
  37153. self.clearColor[2] = b;
  37154. self.clearColor[3] = a;
  37155. self.realClearColor.call(gl, r, g, b, a);
  37156. };
  37157. this.viewport = gl.getParameter(gl.VIEWPORT);
  37158. gl.viewport = function(x, y, w, h) {
  37159. self.viewport[0] = x;
  37160. self.viewport[1] = y;
  37161. self.viewport[2] = w;
  37162. self.viewport[3] = h;
  37163. self.realViewport.call(gl, x, y, w, h);
  37164. };
  37165. this.isPatched = true;
  37166. Util.safariCssSizeWorkaround(canvas);
  37167. };
  37168. CardboardDistorter.prototype.unpatch = function() {
  37169. if (!this.isPatched) {
  37170. return;
  37171. }
  37172. var gl = this.gl;
  37173. var canvas = this.gl.canvas;
  37174. if (!Util.isIOS()) {
  37175. Object.defineProperty(canvas, 'width', this.realCanvasWidth);
  37176. Object.defineProperty(canvas, 'height', this.realCanvasHeight);
  37177. }
  37178. canvas.width = this.bufferWidth;
  37179. canvas.height = this.bufferHeight;
  37180. gl.bindFramebuffer = this.realBindFramebuffer;
  37181. gl.enable = this.realEnable;
  37182. gl.disable = this.realDisable;
  37183. gl.colorMask = this.realColorMask;
  37184. gl.clearColor = this.realClearColor;
  37185. gl.viewport = this.realViewport;
  37186. // Check to see if our fake backbuffer is bound and bind the real backbuffer
  37187. // if that's the case.
  37188. if (this.lastBoundFramebuffer == this.framebuffer) {
  37189. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  37190. }
  37191. this.isPatched = false;
  37192. setTimeout(function() {
  37193. Util.safariCssSizeWorkaround(canvas);
  37194. }, 1);
  37195. };
  37196. CardboardDistorter.prototype.setTextureBounds = function(leftBounds, rightBounds) {
  37197. if (!leftBounds) {
  37198. leftBounds = [0, 0, 0.5, 1];
  37199. }
  37200. if (!rightBounds) {
  37201. rightBounds = [0.5, 0, 0.5, 1];
  37202. }
  37203. // Left eye
  37204. this.viewportOffsetScale[0] = leftBounds[0]; // X
  37205. this.viewportOffsetScale[1] = leftBounds[1]; // Y
  37206. this.viewportOffsetScale[2] = leftBounds[2]; // Width
  37207. this.viewportOffsetScale[3] = leftBounds[3]; // Height
  37208. // Right eye
  37209. this.viewportOffsetScale[4] = rightBounds[0]; // X
  37210. this.viewportOffsetScale[5] = rightBounds[1]; // Y
  37211. this.viewportOffsetScale[6] = rightBounds[2]; // Width
  37212. this.viewportOffsetScale[7] = rightBounds[3]; // Height
  37213. };
  37214. /**
  37215. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37216. * backbuffer.
  37217. */
  37218. CardboardDistorter.prototype.submitFrame = function() {
  37219. var gl = this.gl;
  37220. var self = this;
  37221. var glState = [];
  37222. if (!WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37223. glState.push(
  37224. gl.CURRENT_PROGRAM,
  37225. gl.ARRAY_BUFFER_BINDING,
  37226. gl.ELEMENT_ARRAY_BUFFER_BINDING,
  37227. gl.TEXTURE_BINDING_2D, gl.TEXTURE0
  37228. );
  37229. }
  37230. WGLUPreserveGLState(gl, glState, function(gl) {
  37231. // Bind the real default framebuffer
  37232. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, null);
  37233. // Make sure the GL state is in a good place
  37234. if (self.cullFace) { self.realDisable.call(gl, gl.CULL_FACE); }
  37235. if (self.depthTest) { self.realDisable.call(gl, gl.DEPTH_TEST); }
  37236. if (self.blend) { self.realDisable.call(gl, gl.BLEND); }
  37237. if (self.scissorTest) { self.realDisable.call(gl, gl.SCISSOR_TEST); }
  37238. if (self.stencilTest) { self.realDisable.call(gl, gl.STENCIL_TEST); }
  37239. self.realColorMask.call(gl, true, true, true, true);
  37240. self.realViewport.call(gl, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37241. // If the backbuffer has an alpha channel clear every frame so the page
  37242. // doesn't show through.
  37243. if (self.ctxAttribs.alpha || Util.isIOS()) {
  37244. self.realClearColor.call(gl, 0, 0, 0, 1);
  37245. gl.clear(gl.COLOR_BUFFER_BIT);
  37246. }
  37247. // Bind distortion program and mesh
  37248. gl.useProgram(self.program);
  37249. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37250. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37251. gl.enableVertexAttribArray(self.attribs.position);
  37252. gl.enableVertexAttribArray(self.attribs.texCoord);
  37253. gl.vertexAttribPointer(self.attribs.position, 2, gl.FLOAT, false, 20, 0);
  37254. gl.vertexAttribPointer(self.attribs.texCoord, 3, gl.FLOAT, false, 20, 8);
  37255. gl.activeTexture(gl.TEXTURE0);
  37256. gl.uniform1i(self.uniforms.diffuse, 0);
  37257. gl.bindTexture(gl.TEXTURE_2D, self.renderTarget);
  37258. gl.uniform4fv(self.uniforms.viewportOffsetScale, self.viewportOffsetScale);
  37259. // Draws both eyes
  37260. gl.drawElements(gl.TRIANGLES, self.indexCount, gl.UNSIGNED_SHORT, 0);
  37261. if (self.cardboardUI) {
  37262. self.cardboardUI.renderNoState();
  37263. }
  37264. // Bind the fake default framebuffer again
  37265. self.realBindFramebuffer.call(self.gl, gl.FRAMEBUFFER, self.framebuffer);
  37266. // If preserveDrawingBuffer == false clear the framebuffer
  37267. if (!self.ctxAttribs.preserveDrawingBuffer) {
  37268. self.realClearColor.call(gl, 0, 0, 0, 0);
  37269. gl.clear(gl.COLOR_BUFFER_BIT);
  37270. }
  37271. if (!WebVRConfig.DIRTY_SUBMIT_FRAME_BINDINGS) {
  37272. self.realBindFramebuffer.call(gl, gl.FRAMEBUFFER, self.lastBoundFramebuffer);
  37273. }
  37274. // Restore state
  37275. if (self.cullFace) { self.realEnable.call(gl, gl.CULL_FACE); }
  37276. if (self.depthTest) { self.realEnable.call(gl, gl.DEPTH_TEST); }
  37277. if (self.blend) { self.realEnable.call(gl, gl.BLEND); }
  37278. if (self.scissorTest) { self.realEnable.call(gl, gl.SCISSOR_TEST); }
  37279. if (self.stencilTest) { self.realEnable.call(gl, gl.STENCIL_TEST); }
  37280. self.realColorMask.apply(gl, self.colorMask);
  37281. self.realViewport.apply(gl, self.viewport);
  37282. if (self.ctxAttribs.alpha || !self.ctxAttribs.preserveDrawingBuffer) {
  37283. self.realClearColor.apply(gl, self.clearColor);
  37284. }
  37285. });
  37286. // Workaround for the fact that Safari doesn't allow us to patch the canvas
  37287. // width and height correctly. After each submit frame check to see what the
  37288. // real backbuffer size has been set to and resize the fake backbuffer size
  37289. // to match.
  37290. if (Util.isIOS()) {
  37291. var canvas = gl.canvas;
  37292. if (canvas.width != self.bufferWidth || canvas.height != self.bufferHeight) {
  37293. self.bufferWidth = canvas.width;
  37294. self.bufferHeight = canvas.height;
  37295. self.onResize();
  37296. }
  37297. }
  37298. };
  37299. /**
  37300. * Call when the deviceInfo has changed. At this point we need
  37301. * to re-calculate the distortion mesh.
  37302. */
  37303. CardboardDistorter.prototype.updateDeviceInfo = function(deviceInfo) {
  37304. var gl = this.gl;
  37305. var self = this;
  37306. var glState = [gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING];
  37307. WGLUPreserveGLState(gl, glState, function(gl) {
  37308. var vertices = self.computeMeshVertices_(self.meshWidth, self.meshHeight, deviceInfo);
  37309. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37310. gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
  37311. // Indices don't change based on device parameters, so only compute once.
  37312. if (!self.indexCount) {
  37313. var indices = self.computeMeshIndices_(self.meshWidth, self.meshHeight);
  37314. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, self.indexBuffer);
  37315. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
  37316. self.indexCount = indices.length;
  37317. }
  37318. });
  37319. };
  37320. /**
  37321. * Build the distortion mesh vertices.
  37322. * Based on code from the Unity cardboard plugin.
  37323. */
  37324. CardboardDistorter.prototype.computeMeshVertices_ = function(width, height, deviceInfo) {
  37325. var vertices = new Float32Array(2 * width * height * 5);
  37326. var lensFrustum = deviceInfo.getLeftEyeVisibleTanAngles();
  37327. var noLensFrustum = deviceInfo.getLeftEyeNoLensTanAngles();
  37328. var viewport = deviceInfo.getLeftEyeVisibleScreenRect(noLensFrustum);
  37329. var vidx = 0;
  37330. var iidx = 0;
  37331. for (var e = 0; e < 2; e++) {
  37332. for (var j = 0; j < height; j++) {
  37333. for (var i = 0; i < width; i++, vidx++) {
  37334. var u = i / (width - 1);
  37335. var v = j / (height - 1);
  37336. // Grid points regularly spaced in StreoScreen, and barrel distorted in
  37337. // the mesh.
  37338. var s = u;
  37339. var t = v;
  37340. var x = Util.lerp(lensFrustum[0], lensFrustum[2], u);
  37341. var y = Util.lerp(lensFrustum[3], lensFrustum[1], v);
  37342. var d = Math.sqrt(x * x + y * y);
  37343. var r = deviceInfo.distortion.distortInverse(d);
  37344. var p = x * r / d;
  37345. var q = y * r / d;
  37346. u = (p - noLensFrustum[0]) / (noLensFrustum[2] - noLensFrustum[0]);
  37347. v = (q - noLensFrustum[3]) / (noLensFrustum[1] - noLensFrustum[3]);
  37348. // Convert u,v to mesh screen coordinates.
  37349. var aspect = deviceInfo.device.widthMeters / deviceInfo.device.heightMeters;
  37350. // FIXME: The original Unity plugin multiplied U by the aspect ratio
  37351. // and didn't multiply either value by 2, but that seems to get it
  37352. // really close to correct looking for me. I hate this kind of "Don't
  37353. // know why it works" code though, and wold love a more logical
  37354. // explanation of what needs to happen here.
  37355. u = (viewport.x + u * viewport.width - 0.5) * 2.0; //* aspect;
  37356. v = (viewport.y + v * viewport.height - 0.5) * 2.0;
  37357. vertices[(vidx * 5) + 0] = u; // position.x
  37358. vertices[(vidx * 5) + 1] = v; // position.y
  37359. vertices[(vidx * 5) + 2] = s; // texCoord.x
  37360. vertices[(vidx * 5) + 3] = t; // texCoord.y
  37361. vertices[(vidx * 5) + 4] = e; // texCoord.z (viewport index)
  37362. }
  37363. }
  37364. var w = lensFrustum[2] - lensFrustum[0];
  37365. lensFrustum[0] = -(w + lensFrustum[0]);
  37366. lensFrustum[2] = w - lensFrustum[2];
  37367. w = noLensFrustum[2] - noLensFrustum[0];
  37368. noLensFrustum[0] = -(w + noLensFrustum[0]);
  37369. noLensFrustum[2] = w - noLensFrustum[2];
  37370. viewport.x = 1 - (viewport.x + viewport.width);
  37371. }
  37372. return vertices;
  37373. }
  37374. /**
  37375. * Build the distortion mesh indices.
  37376. * Based on code from the Unity cardboard plugin.
  37377. */
  37378. CardboardDistorter.prototype.computeMeshIndices_ = function(width, height) {
  37379. var indices = new Uint16Array(2 * (width - 1) * (height - 1) * 6);
  37380. var halfwidth = width / 2;
  37381. var halfheight = height / 2;
  37382. var vidx = 0;
  37383. var iidx = 0;
  37384. for (var e = 0; e < 2; e++) {
  37385. for (var j = 0; j < height; j++) {
  37386. for (var i = 0; i < width; i++, vidx++) {
  37387. if (i == 0 || j == 0)
  37388. continue;
  37389. // Build a quad. Lower right and upper left quadrants have quads with
  37390. // the triangle diagonal flipped to get the vignette to interpolate
  37391. // correctly.
  37392. if ((i <= halfwidth) == (j <= halfheight)) {
  37393. // Quad diagonal lower left to upper right.
  37394. indices[iidx++] = vidx;
  37395. indices[iidx++] = vidx - width - 1;
  37396. indices[iidx++] = vidx - width;
  37397. indices[iidx++] = vidx - width - 1;
  37398. indices[iidx++] = vidx;
  37399. indices[iidx++] = vidx - 1;
  37400. } else {
  37401. // Quad diagonal upper left to lower right.
  37402. indices[iidx++] = vidx - 1;
  37403. indices[iidx++] = vidx - width;
  37404. indices[iidx++] = vidx;
  37405. indices[iidx++] = vidx - width;
  37406. indices[iidx++] = vidx - 1;
  37407. indices[iidx++] = vidx - width - 1;
  37408. }
  37409. }
  37410. }
  37411. }
  37412. return indices;
  37413. };
  37414. CardboardDistorter.prototype.getOwnPropertyDescriptor_ = function(proto, attrName) {
  37415. var descriptor = Object.getOwnPropertyDescriptor(proto, attrName);
  37416. // In some cases (ahem... Safari), the descriptor returns undefined get and
  37417. // set fields. In this case, we need to create a synthetic property
  37418. // descriptor. This works around some of the issues in
  37419. // https://github.com/borismus/webvr-polyfill/issues/46
  37420. if (descriptor.get === undefined || descriptor.set === undefined) {
  37421. descriptor.configurable = true;
  37422. descriptor.enumerable = true;
  37423. descriptor.get = function() {
  37424. return this.getAttribute(attrName);
  37425. };
  37426. descriptor.set = function(val) {
  37427. this.setAttribute(attrName, val);
  37428. };
  37429. }
  37430. return descriptor;
  37431. };
  37432. module.exports = CardboardDistorter;
  37433. },{"./cardboard-ui.js":5,"./deps/wglu-preserve-state.js":7,"./util.js":23}],5:[function(_dereq_,module,exports){
  37434. /*
  37435. * Copyright 2016 Google Inc. All Rights Reserved.
  37436. * Licensed under the Apache License, Version 2.0 (the "License");
  37437. * you may not use this file except in compliance with the License.
  37438. * You may obtain a copy of the License at
  37439. *
  37440. * http://www.apache.org/licenses/LICENSE-2.0
  37441. *
  37442. * Unless required by applicable law or agreed to in writing, software
  37443. * distributed under the License is distributed on an "AS IS" BASIS,
  37444. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37445. * See the License for the specific language governing permissions and
  37446. * limitations under the License.
  37447. */
  37448. var Util = _dereq_('./util.js');
  37449. var WGLUPreserveGLState = _dereq_('./deps/wglu-preserve-state.js');
  37450. var uiVS = [
  37451. 'attribute vec2 position;',
  37452. 'uniform mat4 projectionMat;',
  37453. 'void main() {',
  37454. ' gl_Position = projectionMat * vec4( position, -1.0, 1.0 );',
  37455. '}',
  37456. ].join('\n');
  37457. var uiFS = [
  37458. 'precision mediump float;',
  37459. 'uniform vec4 color;',
  37460. 'void main() {',
  37461. ' gl_FragColor = color;',
  37462. '}',
  37463. ].join('\n');
  37464. var DEG2RAD = Math.PI/180.0;
  37465. // The gear has 6 identical sections, each spanning 60 degrees.
  37466. var kAnglePerGearSection = 60;
  37467. // Half-angle of the span of the outer rim.
  37468. var kOuterRimEndAngle = 12;
  37469. // Angle between the middle of the outer rim and the start of the inner rim.
  37470. var kInnerRimBeginAngle = 20;
  37471. // Distance from center to outer rim, normalized so that the entire model
  37472. // fits in a [-1, 1] x [-1, 1] square.
  37473. var kOuterRadius = 1;
  37474. // Distance from center to depressed rim, in model units.
  37475. var kMiddleRadius = 0.75;
  37476. // Radius of the inner hollow circle, in model units.
  37477. var kInnerRadius = 0.3125;
  37478. // Center line thickness in DP.
  37479. var kCenterLineThicknessDp = 4;
  37480. // Button width in DP.
  37481. var kButtonWidthDp = 28;
  37482. // Factor to scale the touch area that responds to the touch.
  37483. var kTouchSlopFactor = 1.5;
  37484. var Angles = [
  37485. 0, kOuterRimEndAngle, kInnerRimBeginAngle,
  37486. kAnglePerGearSection - kInnerRimBeginAngle,
  37487. kAnglePerGearSection - kOuterRimEndAngle
  37488. ];
  37489. /**
  37490. * Renders the alignment line and "options" gear. It is assumed that the canvas
  37491. * this is rendered into covers the entire screen (or close to it.)
  37492. */
  37493. function CardboardUI(gl) {
  37494. this.gl = gl;
  37495. this.attribs = {
  37496. position: 0
  37497. };
  37498. this.program = Util.linkProgram(gl, uiVS, uiFS, this.attribs);
  37499. this.uniforms = Util.getProgramUniforms(gl, this.program);
  37500. this.vertexBuffer = gl.createBuffer();
  37501. this.gearOffset = 0;
  37502. this.gearVertexCount = 0;
  37503. this.arrowOffset = 0;
  37504. this.arrowVertexCount = 0;
  37505. this.projMat = new Float32Array(16);
  37506. this.listener = null;
  37507. this.onResize();
  37508. };
  37509. /**
  37510. * Tears down all the resources created by the UI renderer.
  37511. */
  37512. CardboardUI.prototype.destroy = function() {
  37513. var gl = this.gl;
  37514. if (this.listener) {
  37515. gl.canvas.removeEventListener('click', this.listener, false);
  37516. }
  37517. gl.deleteProgram(this.program);
  37518. gl.deleteBuffer(this.vertexBuffer);
  37519. };
  37520. /**
  37521. * Adds a listener to clicks on the gear and back icons
  37522. */
  37523. CardboardUI.prototype.listen = function(optionsCallback, backCallback) {
  37524. var canvas = this.gl.canvas;
  37525. this.listener = function(event) {
  37526. var midline = canvas.clientWidth / 2;
  37527. var buttonSize = kButtonWidthDp * kTouchSlopFactor;
  37528. // Check to see if the user clicked on (or around) the gear icon
  37529. if (event.clientX > midline - buttonSize &&
  37530. event.clientX < midline + buttonSize &&
  37531. event.clientY > canvas.clientHeight - buttonSize) {
  37532. optionsCallback(event);
  37533. }
  37534. // Check to see if the user clicked on (or around) the back icon
  37535. else if (event.clientX < buttonSize && event.clientY < buttonSize) {
  37536. backCallback(event);
  37537. }
  37538. };
  37539. canvas.addEventListener('click', this.listener, false);
  37540. };
  37541. /**
  37542. * Builds the UI mesh.
  37543. */
  37544. CardboardUI.prototype.onResize = function() {
  37545. var gl = this.gl;
  37546. var self = this;
  37547. var glState = [
  37548. gl.ARRAY_BUFFER_BINDING
  37549. ];
  37550. WGLUPreserveGLState(gl, glState, function(gl) {
  37551. var vertices = [];
  37552. var midline = gl.drawingBufferWidth / 2;
  37553. // Assumes your canvas width and height is scaled proportionately.
  37554. // TODO(smus): The following causes buttons to become huge on iOS, but seems
  37555. // like the right thing to do. For now, added a hack. But really, investigate why.
  37556. var dps = (gl.drawingBufferWidth / (screen.width * window.devicePixelRatio));
  37557. if (!Util.isIOS()) {
  37558. dps *= window.devicePixelRatio;
  37559. }
  37560. var lineWidth = kCenterLineThicknessDp * dps / 2;
  37561. var buttonSize = kButtonWidthDp * kTouchSlopFactor * dps;
  37562. var buttonScale = kButtonWidthDp * dps / 2;
  37563. var buttonBorder = ((kButtonWidthDp * kTouchSlopFactor) - kButtonWidthDp) * dps;
  37564. // Build centerline
  37565. vertices.push(midline - lineWidth, buttonSize);
  37566. vertices.push(midline - lineWidth, gl.drawingBufferHeight);
  37567. vertices.push(midline + lineWidth, buttonSize);
  37568. vertices.push(midline + lineWidth, gl.drawingBufferHeight);
  37569. // Build gear
  37570. self.gearOffset = (vertices.length / 2);
  37571. function addGearSegment(theta, r) {
  37572. var angle = (90 - theta) * DEG2RAD;
  37573. var x = Math.cos(angle);
  37574. var y = Math.sin(angle);
  37575. vertices.push(kInnerRadius * x * buttonScale + midline, kInnerRadius * y * buttonScale + buttonScale);
  37576. vertices.push(r * x * buttonScale + midline, r * y * buttonScale + buttonScale);
  37577. }
  37578. for (var i = 0; i <= 6; i++) {
  37579. var segmentTheta = i * kAnglePerGearSection;
  37580. addGearSegment(segmentTheta, kOuterRadius);
  37581. addGearSegment(segmentTheta + kOuterRimEndAngle, kOuterRadius);
  37582. addGearSegment(segmentTheta + kInnerRimBeginAngle, kMiddleRadius);
  37583. addGearSegment(segmentTheta + (kAnglePerGearSection - kInnerRimBeginAngle), kMiddleRadius);
  37584. addGearSegment(segmentTheta + (kAnglePerGearSection - kOuterRimEndAngle), kOuterRadius);
  37585. }
  37586. self.gearVertexCount = (vertices.length / 2) - self.gearOffset;
  37587. // Build back arrow
  37588. self.arrowOffset = (vertices.length / 2);
  37589. function addArrowVertex(x, y) {
  37590. vertices.push(buttonBorder + x, gl.drawingBufferHeight - buttonBorder - y);
  37591. }
  37592. var angledLineWidth = lineWidth / Math.sin(45 * DEG2RAD);
  37593. addArrowVertex(0, buttonScale);
  37594. addArrowVertex(buttonScale, 0);
  37595. addArrowVertex(buttonScale + angledLineWidth, angledLineWidth);
  37596. addArrowVertex(angledLineWidth, buttonScale + angledLineWidth);
  37597. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37598. addArrowVertex(0, buttonScale);
  37599. addArrowVertex(buttonScale, buttonScale * 2);
  37600. addArrowVertex(buttonScale + angledLineWidth, (buttonScale * 2) - angledLineWidth);
  37601. addArrowVertex(angledLineWidth, buttonScale - angledLineWidth);
  37602. addArrowVertex(0, buttonScale);
  37603. addArrowVertex(angledLineWidth, buttonScale - lineWidth);
  37604. addArrowVertex(kButtonWidthDp * dps, buttonScale - lineWidth);
  37605. addArrowVertex(angledLineWidth, buttonScale + lineWidth);
  37606. addArrowVertex(kButtonWidthDp * dps, buttonScale + lineWidth);
  37607. self.arrowVertexCount = (vertices.length / 2) - self.arrowOffset;
  37608. // Buffer data
  37609. gl.bindBuffer(gl.ARRAY_BUFFER, self.vertexBuffer);
  37610. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  37611. });
  37612. };
  37613. /**
  37614. * Performs distortion pass on the injected backbuffer, rendering it to the real
  37615. * backbuffer.
  37616. */
  37617. CardboardUI.prototype.render = function() {
  37618. var gl = this.gl;
  37619. var self = this;
  37620. var glState = [
  37621. gl.CULL_FACE,
  37622. gl.DEPTH_TEST,
  37623. gl.BLEND,
  37624. gl.SCISSOR_TEST,
  37625. gl.STENCIL_TEST,
  37626. gl.COLOR_WRITEMASK,
  37627. gl.VIEWPORT,
  37628. gl.CURRENT_PROGRAM,
  37629. gl.ARRAY_BUFFER_BINDING
  37630. ];
  37631. WGLUPreserveGLState(gl, glState, function(gl) {
  37632. // Make sure the GL state is in a good place
  37633. gl.disable(gl.CULL_FACE);
  37634. gl.disable(gl.DEPTH_TEST);
  37635. gl.disable(gl.BLEND);
  37636. gl.disable(gl.SCISSOR_TEST);
  37637. gl.disable(gl.STENCIL_TEST);
  37638. gl.colorMask(true, true, true, true);
  37639. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37640. self.renderNoState();
  37641. });
  37642. };
  37643. CardboardUI.prototype.renderNoState = function() {
  37644. var gl = this.gl;
  37645. // Bind distortion program and mesh
  37646. gl.useProgram(this.program);
  37647. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  37648. gl.enableVertexAttribArray(this.attribs.position);
  37649. gl.vertexAttribPointer(this.attribs.position, 2, gl.FLOAT, false, 8, 0);
  37650. gl.uniform4f(this.uniforms.color, 1.0, 1.0, 1.0, 1.0);
  37651. Util.orthoMatrix(this.projMat, 0, gl.drawingBufferWidth, 0, gl.drawingBufferHeight, 0.1, 1024.0);
  37652. gl.uniformMatrix4fv(this.uniforms.projectionMat, false, this.projMat);
  37653. // Draws UI element
  37654. gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
  37655. gl.drawArrays(gl.TRIANGLE_STRIP, this.gearOffset, this.gearVertexCount);
  37656. gl.drawArrays(gl.TRIANGLE_STRIP, this.arrowOffset, this.arrowVertexCount);
  37657. };
  37658. module.exports = CardboardUI;
  37659. },{"./deps/wglu-preserve-state.js":7,"./util.js":23}],6:[function(_dereq_,module,exports){
  37660. /*
  37661. * Copyright 2016 Google Inc. All Rights Reserved.
  37662. * Licensed under the Apache License, Version 2.0 (the "License");
  37663. * you may not use this file except in compliance with the License.
  37664. * You may obtain a copy of the License at
  37665. *
  37666. * http://www.apache.org/licenses/LICENSE-2.0
  37667. *
  37668. * Unless required by applicable law or agreed to in writing, software
  37669. * distributed under the License is distributed on an "AS IS" BASIS,
  37670. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  37671. * See the License for the specific language governing permissions and
  37672. * limitations under the License.
  37673. */
  37674. var CardboardDistorter = _dereq_('./cardboard-distorter.js');
  37675. var CardboardUI = _dereq_('./cardboard-ui.js');
  37676. var DeviceInfo = _dereq_('./device-info.js');
  37677. var Dpdb = _dereq_('./dpdb/dpdb.js');
  37678. var FusionPoseSensor = _dereq_('./sensor-fusion/fusion-pose-sensor.js');
  37679. var RotateInstructions = _dereq_('./rotate-instructions.js');
  37680. var ViewerSelector = _dereq_('./viewer-selector.js');
  37681. var VRDisplay = _dereq_('./base.js').VRDisplay;
  37682. var Util = _dereq_('./util.js');
  37683. var Eye = {
  37684. LEFT: 'left',
  37685. RIGHT: 'right'
  37686. };
  37687. /**
  37688. * VRDisplay based on mobile device parameters and DeviceMotion APIs.
  37689. */
  37690. function CardboardVRDisplay() {
  37691. this.displayName = 'Cardboard VRDisplay (webvr-polyfill)';
  37692. this.capabilities.hasOrientation = true;
  37693. this.capabilities.canPresent = true;
  37694. // "Private" members.
  37695. this.bufferScale_ = WebVRConfig.BUFFER_SCALE;
  37696. this.poseSensor_ = new FusionPoseSensor();
  37697. this.distorter_ = null;
  37698. this.cardboardUI_ = null;
  37699. this.dpdb_ = new Dpdb(true, this.onDeviceParamsUpdated_.bind(this));
  37700. this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams());
  37701. this.viewerSelector_ = new ViewerSelector();
  37702. this.viewerSelector_.on('change', this.onViewerChanged_.bind(this));
  37703. // Set the correct initial viewer.
  37704. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer());
  37705. if (!WebVRConfig.ROTATE_INSTRUCTIONS_DISABLED) {
  37706. this.rotateInstructions_ = new RotateInstructions();
  37707. }
  37708. if (Util.isIOS()) {
  37709. // Listen for resize events to workaround this awful Safari bug.
  37710. window.addEventListener('resize', this.onResize_.bind(this));
  37711. }
  37712. }
  37713. CardboardVRDisplay.prototype = new VRDisplay();
  37714. CardboardVRDisplay.prototype.getImmediatePose = function() {
  37715. return {
  37716. position: this.poseSensor_.getPosition(),
  37717. orientation: this.poseSensor_.getOrientation(),
  37718. linearVelocity: null,
  37719. linearAcceleration: null,
  37720. angularVelocity: null,
  37721. angularAcceleration: null
  37722. };
  37723. };
  37724. CardboardVRDisplay.prototype.resetPose = function() {
  37725. this.poseSensor_.resetPose();
  37726. };
  37727. CardboardVRDisplay.prototype.getEyeParameters = function(whichEye) {
  37728. var offset = [this.deviceInfo_.viewer.interLensDistance * 0.5, 0.0, 0.0];
  37729. var fieldOfView;
  37730. // TODO: FoV can be a little expensive to compute. Cache when device params change.
  37731. if (whichEye == Eye.LEFT) {
  37732. offset[0] *= -1.0;
  37733. fieldOfView = this.deviceInfo_.getFieldOfViewLeftEye();
  37734. } else if (whichEye == Eye.RIGHT) {
  37735. fieldOfView = this.deviceInfo_.getFieldOfViewRightEye();
  37736. } else {
  37737. console.error('Invalid eye provided: %s', whichEye);
  37738. return null;
  37739. }
  37740. return {
  37741. fieldOfView: fieldOfView,
  37742. offset: offset,
  37743. // TODO: Should be able to provide better values than these.
  37744. renderWidth: this.deviceInfo_.device.width * 0.5 * this.bufferScale_,
  37745. renderHeight: this.deviceInfo_.device.height * this.bufferScale_,
  37746. };
  37747. };
  37748. CardboardVRDisplay.prototype.onDeviceParamsUpdated_ = function(newParams) {
  37749. if (Util.isDebug()) {
  37750. console.log('DPDB reported that device params were updated.');
  37751. }
  37752. this.deviceInfo_.updateDeviceParams(newParams);
  37753. if (this.distorter_) {
  37754. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37755. }
  37756. };
  37757. CardboardVRDisplay.prototype.updateBounds_ = function () {
  37758. if (this.layer_ && this.distorter_ && (this.layer_.leftBounds || this.layer_.rightBounds)) {
  37759. this.distorter_.setTextureBounds(this.layer_.leftBounds, this.layer_.rightBounds);
  37760. }
  37761. };
  37762. CardboardVRDisplay.prototype.beginPresent_ = function() {
  37763. var gl = this.layer_.source.getContext('webgl');
  37764. if (!gl)
  37765. gl = this.layer_.source.getContext('experimental-webgl');
  37766. if (!gl)
  37767. gl = this.layer_.source.getContext('webgl2');
  37768. if (!gl)
  37769. return; // Can't do distortion without a WebGL context.
  37770. // Provides a way to opt out of distortion
  37771. if (this.layer_.predistorted) {
  37772. if (!WebVRConfig.CARDBOARD_UI_DISABLED) {
  37773. gl.canvas.width = Util.getScreenWidth() * this.bufferScale_;
  37774. gl.canvas.height = Util.getScreenHeight() * this.bufferScale_;
  37775. this.cardboardUI_ = new CardboardUI(gl);
  37776. }
  37777. } else {
  37778. // Create a new distorter for the target context
  37779. this.distorter_ = new CardboardDistorter(gl);
  37780. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37781. this.cardboardUI_ = this.distorter_.cardboardUI;
  37782. }
  37783. if (this.cardboardUI_) {
  37784. this.cardboardUI_.listen(function(e) {
  37785. // Options clicked.
  37786. this.viewerSelector_.show(this.layer_.source.parentElement);
  37787. e.stopPropagation();
  37788. e.preventDefault();
  37789. }.bind(this), function(e) {
  37790. // Back clicked.
  37791. this.exitPresent();
  37792. e.stopPropagation();
  37793. e.preventDefault();
  37794. }.bind(this));
  37795. }
  37796. if (this.rotateInstructions_) {
  37797. if (Util.isLandscapeMode() && Util.isMobile()) {
  37798. // In landscape mode, temporarily show the "put into Cardboard"
  37799. // interstitial. Otherwise, do the default thing.
  37800. this.rotateInstructions_.showTemporarily(3000, this.layer_.source.parentElement);
  37801. } else {
  37802. this.rotateInstructions_.update();
  37803. }
  37804. }
  37805. // Listen for orientation change events in order to show interstitial.
  37806. this.orientationHandler = this.onOrientationChange_.bind(this);
  37807. window.addEventListener('orientationchange', this.orientationHandler);
  37808. // Listen for present display change events in order to update distorter dimensions
  37809. this.vrdisplaypresentchangeHandler = this.updateBounds_.bind(this);
  37810. window.addEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37811. // Fire this event initially, to give geometry-distortion clients the chance
  37812. // to do something custom.
  37813. this.fireVRDisplayDeviceParamsChange_();
  37814. };
  37815. CardboardVRDisplay.prototype.endPresent_ = function() {
  37816. if (this.distorter_) {
  37817. this.distorter_.destroy();
  37818. this.distorter_ = null;
  37819. }
  37820. if (this.cardboardUI_) {
  37821. this.cardboardUI_.destroy();
  37822. this.cardboardUI_ = null;
  37823. }
  37824. if (this.rotateInstructions_) {
  37825. this.rotateInstructions_.hide();
  37826. }
  37827. this.viewerSelector_.hide();
  37828. window.removeEventListener('orientationchange', this.orientationHandler);
  37829. window.removeEventListener('vrdisplaypresentchange', this.vrdisplaypresentchangeHandler);
  37830. };
  37831. CardboardVRDisplay.prototype.submitFrame = function(pose) {
  37832. if (this.distorter_) {
  37833. this.distorter_.submitFrame();
  37834. } else if (this.cardboardUI_ && this.layer_) {
  37835. // Hack for predistorted: true.
  37836. var canvas = this.layer_.source.getContext('webgl').canvas;
  37837. if (canvas.width != this.lastWidth || canvas.height != this.lastHeight) {
  37838. this.cardboardUI_.onResize();
  37839. }
  37840. this.lastWidth = canvas.width;
  37841. this.lastHeight = canvas.height;
  37842. // Render the Cardboard UI.
  37843. this.cardboardUI_.render();
  37844. }
  37845. };
  37846. CardboardVRDisplay.prototype.onOrientationChange_ = function(e) {
  37847. // Hide the viewer selector.
  37848. this.viewerSelector_.hide();
  37849. // Update the rotate instructions.
  37850. if (this.rotateInstructions_) {
  37851. this.rotateInstructions_.update();
  37852. }
  37853. this.onResize_();
  37854. };
  37855. CardboardVRDisplay.prototype.onResize_ = function(e) {
  37856. if (this.layer_) {
  37857. var gl = this.layer_.source.getContext('webgl');
  37858. // Size the CSS canvas.
  37859. // Added padding on right and bottom because iPhone 5 will not
  37860. // hide the URL bar unless content is bigger than the screen.
  37861. // This will not be visible as long as the container element (e.g. body)
  37862. // is set to 'overflow: hidden'.
  37863. var cssProperties = [
  37864. 'position: absolute',
  37865. 'top: 0',
  37866. 'left: 0',
  37867. 'width: ' + Math.max(screen.width, screen.height) + 'px',
  37868. 'height: ' + Math.min(screen.height, screen.width) + 'px',
  37869. 'border: 0',
  37870. 'margin: 0',
  37871. 'padding: 0 10px 10px 0',
  37872. ];
  37873. gl.canvas.setAttribute('style', cssProperties.join('; ') + ';');
  37874. Util.safariCssSizeWorkaround(gl.canvas);
  37875. }
  37876. };
  37877. CardboardVRDisplay.prototype.onViewerChanged_ = function(viewer) {
  37878. this.deviceInfo_.setViewer(viewer);
  37879. if (this.distorter_) {
  37880. // Update the distortion appropriately.
  37881. this.distorter_.updateDeviceInfo(this.deviceInfo_);
  37882. }
  37883. // Fire a new event containing viewer and device parameters for clients that
  37884. // want to implement their own geometry-based distortion.
  37885. this.fireVRDisplayDeviceParamsChange_();
  37886. };
  37887. CardboardVRDisplay.prototype.fireVRDisplayDeviceParamsChange_ = function() {
  37888. var event = new CustomEvent('vrdisplaydeviceparamschange', {
  37889. detail: {
  37890. vrdisplay: this,
  37891. deviceInfo: this.deviceInfo_,
  37892. }
  37893. });
  37894. window.dispatchEvent(event);
  37895. };
  37896. module.exports = CardboardVRDisplay;
  37897. },{"./base.js":3,"./cardboard-distorter.js":4,"./cardboard-ui.js":5,"./device-info.js":8,"./dpdb/dpdb.js":13,"./rotate-instructions.js":17,"./sensor-fusion/fusion-pose-sensor.js":19,"./util.js":23,"./viewer-selector.js":24}],7:[function(_dereq_,module,exports){
  37898. /*
  37899. Copyright (c) 2016, Brandon Jones.
  37900. Permission is hereby granted, free of charge, to any person obtaining a copy
  37901. of this software and associated documentation files (the "Software"), to deal
  37902. in the Software without restriction, including without limitation the rights
  37903. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  37904. copies of the Software, and to permit persons to whom the Software is
  37905. furnished to do so, subject to the following conditions:
  37906. The above copyright notice and this permission notice shall be included in
  37907. all copies or substantial portions of the Software.
  37908. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37909. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  37910. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  37911. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  37912. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  37913. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  37914. THE SOFTWARE.
  37915. */
  37916. /*
  37917. Caches specified GL state, runs a callback, and restores the cached state when
  37918. done.
  37919. Example usage:
  37920. var savedState = [
  37921. gl.ARRAY_BUFFER_BINDING,
  37922. // TEXTURE_BINDING_2D or _CUBE_MAP must always be followed by the texure unit.
  37923. gl.TEXTURE_BINDING_2D, gl.TEXTURE0,
  37924. gl.CLEAR_COLOR,
  37925. ];
  37926. // After this call the array buffer, texture unit 0, active texture, and clear
  37927. // color will be restored. The viewport will remain changed, however, because
  37928. // gl.VIEWPORT was not included in the savedState list.
  37929. WGLUPreserveGLState(gl, savedState, function(gl) {
  37930. gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
  37931. gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
  37932. gl.bufferData(gl.ARRAY_BUFFER, ....);
  37933. gl.activeTexture(gl.TEXTURE0);
  37934. gl.bindTexture(gl.TEXTURE_2D, texture);
  37935. gl.texImage2D(gl.TEXTURE_2D, ...);
  37936. gl.clearColor(1, 0, 0, 1);
  37937. gl.clear(gl.COLOR_BUFFER_BIT);
  37938. });
  37939. Note that this is not intended to be fast. Managing state in your own code to
  37940. avoid redundant state setting and querying will always be faster. This function
  37941. is most useful for cases where you may not have full control over the WebGL
  37942. calls being made, such as tooling or effect injectors.
  37943. */
  37944. function WGLUPreserveGLState(gl, bindings, callback) {
  37945. if (!bindings) {
  37946. callback(gl);
  37947. return;
  37948. }
  37949. var boundValues = [];
  37950. var activeTexture = null;
  37951. for (var i = 0; i < bindings.length; ++i) {
  37952. var binding = bindings[i];
  37953. switch (binding) {
  37954. case gl.TEXTURE_BINDING_2D:
  37955. case gl.TEXTURE_BINDING_CUBE_MAP:
  37956. var textureUnit = bindings[++i];
  37957. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31) {
  37958. console.error("TEXTURE_BINDING_2D or TEXTURE_BINDING_CUBE_MAP must be followed by a valid texture unit");
  37959. boundValues.push(null, null);
  37960. break;
  37961. }
  37962. if (!activeTexture) {
  37963. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37964. }
  37965. gl.activeTexture(textureUnit);
  37966. boundValues.push(gl.getParameter(binding), null);
  37967. break;
  37968. case gl.ACTIVE_TEXTURE:
  37969. activeTexture = gl.getParameter(gl.ACTIVE_TEXTURE);
  37970. boundValues.push(null);
  37971. break;
  37972. default:
  37973. boundValues.push(gl.getParameter(binding));
  37974. break;
  37975. }
  37976. }
  37977. callback(gl);
  37978. for (var i = 0; i < bindings.length; ++i) {
  37979. var binding = bindings[i];
  37980. var boundValue = boundValues[i];
  37981. switch (binding) {
  37982. case gl.ACTIVE_TEXTURE:
  37983. break; // Ignore this binding, since we special-case it to happen last.
  37984. case gl.ARRAY_BUFFER_BINDING:
  37985. gl.bindBuffer(gl.ARRAY_BUFFER, boundValue);
  37986. break;
  37987. case gl.COLOR_CLEAR_VALUE:
  37988. gl.clearColor(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37989. break;
  37990. case gl.COLOR_WRITEMASK:
  37991. gl.colorMask(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  37992. break;
  37993. case gl.CURRENT_PROGRAM:
  37994. gl.useProgram(boundValue);
  37995. break;
  37996. case gl.ELEMENT_ARRAY_BUFFER_BINDING:
  37997. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, boundValue);
  37998. break;
  37999. case gl.FRAMEBUFFER_BINDING:
  38000. gl.bindFramebuffer(gl.FRAMEBUFFER, boundValue);
  38001. break;
  38002. case gl.RENDERBUFFER_BINDING:
  38003. gl.bindRenderbuffer(gl.RENDERBUFFER, boundValue);
  38004. break;
  38005. case gl.TEXTURE_BINDING_2D:
  38006. var textureUnit = bindings[++i];
  38007. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38008. break;
  38009. gl.activeTexture(textureUnit);
  38010. gl.bindTexture(gl.TEXTURE_2D, boundValue);
  38011. break;
  38012. case gl.TEXTURE_BINDING_CUBE_MAP:
  38013. var textureUnit = bindings[++i];
  38014. if (textureUnit < gl.TEXTURE0 || textureUnit > gl.TEXTURE31)
  38015. break;
  38016. gl.activeTexture(textureUnit);
  38017. gl.bindTexture(gl.TEXTURE_CUBE_MAP, boundValue);
  38018. break;
  38019. case gl.VIEWPORT:
  38020. gl.viewport(boundValue[0], boundValue[1], boundValue[2], boundValue[3]);
  38021. break;
  38022. case gl.BLEND:
  38023. case gl.CULL_FACE:
  38024. case gl.DEPTH_TEST:
  38025. case gl.SCISSOR_TEST:
  38026. case gl.STENCIL_TEST:
  38027. if (boundValue) {
  38028. gl.enable(binding);
  38029. } else {
  38030. gl.disable(binding);
  38031. }
  38032. break;
  38033. default:
  38034. console.log("No GL restore behavior for 0x" + binding.toString(16));
  38035. break;
  38036. }
  38037. if (activeTexture) {
  38038. gl.activeTexture(activeTexture);
  38039. }
  38040. }
  38041. }
  38042. module.exports = WGLUPreserveGLState;
  38043. },{}],8:[function(_dereq_,module,exports){
  38044. /*
  38045. * Copyright 2015 Google Inc. All Rights Reserved.
  38046. * Licensed under the Apache License, Version 2.0 (the "License");
  38047. * you may not use this file except in compliance with the License.
  38048. * You may obtain a copy of the License at
  38049. *
  38050. * http://www.apache.org/licenses/LICENSE-2.0
  38051. *
  38052. * Unless required by applicable law or agreed to in writing, software
  38053. * distributed under the License is distributed on an "AS IS" BASIS,
  38054. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38055. * See the License for the specific language governing permissions and
  38056. * limitations under the License.
  38057. */
  38058. var Distortion = _dereq_('./distortion/distortion.js');
  38059. var MathUtil = _dereq_('./math-util.js');
  38060. var Util = _dereq_('./util.js');
  38061. function Device(params) {
  38062. this.width = params.width || Util.getScreenWidth();
  38063. this.height = params.height || Util.getScreenHeight();
  38064. this.widthMeters = params.widthMeters;
  38065. this.heightMeters = params.heightMeters;
  38066. this.bevelMeters = params.bevelMeters;
  38067. }
  38068. // Fallback Android device (based on Nexus 5 measurements) for use when
  38069. // we can't recognize an Android device.
  38070. var DEFAULT_ANDROID = new Device({
  38071. widthMeters: 0.110,
  38072. heightMeters: 0.062,
  38073. bevelMeters: 0.004
  38074. });
  38075. // Fallback iOS device (based on iPhone6) for use when
  38076. // we can't recognize an Android device.
  38077. var DEFAULT_IOS = new Device({
  38078. widthMeters: 0.1038,
  38079. heightMeters: 0.0584,
  38080. bevelMeters: 0.004
  38081. });
  38082. var Viewers = {
  38083. CardboardV1: new CardboardViewer({
  38084. id: 'CardboardV1',
  38085. label: 'Cardboard I/O 2014',
  38086. fov: 40,
  38087. interLensDistance: 0.060,
  38088. baselineLensDistance: 0.035,
  38089. screenLensDistance: 0.042,
  38090. distortionCoefficients: [0.441, 0.156],
  38091. inverseCoefficients: [-0.4410035, 0.42756155, -0.4804439, 0.5460139,
  38092. -0.58821183, 0.5733938, -0.48303202, 0.33299083, -0.17573841,
  38093. 0.0651772, -0.01488963, 0.001559834]
  38094. }),
  38095. CardboardV2: new CardboardViewer({
  38096. id: 'CardboardV2',
  38097. label: 'Cardboard I/O 2015',
  38098. fov: 60,
  38099. interLensDistance: 0.064,
  38100. baselineLensDistance: 0.035,
  38101. screenLensDistance: 0.039,
  38102. distortionCoefficients: [0.34, 0.55],
  38103. inverseCoefficients: [-0.33836704, -0.18162185, 0.862655, -1.2462051,
  38104. 1.0560602, -0.58208317, 0.21609078, -0.05444823, 0.009177956,
  38105. -9.904169E-4, 6.183535E-5, -1.6981803E-6]
  38106. })
  38107. };
  38108. var DEFAULT_LEFT_CENTER = {x: 0.5, y: 0.5};
  38109. var DEFAULT_RIGHT_CENTER = {x: 0.5, y: 0.5};
  38110. /**
  38111. * Manages information about the device and the viewer.
  38112. *
  38113. * deviceParams indicates the parameters of the device to use (generally
  38114. * obtained from dpdb.getDeviceParams()). Can be null to mean no device
  38115. * params were found.
  38116. */
  38117. function DeviceInfo(deviceParams) {
  38118. this.viewer = Viewers.CardboardV2;
  38119. this.updateDeviceParams(deviceParams);
  38120. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38121. }
  38122. DeviceInfo.prototype.updateDeviceParams = function(deviceParams) {
  38123. this.device = this.determineDevice_(deviceParams) || this.device;
  38124. };
  38125. DeviceInfo.prototype.getDevice = function() {
  38126. return this.device;
  38127. };
  38128. DeviceInfo.prototype.setViewer = function(viewer) {
  38129. this.viewer = viewer;
  38130. this.distortion = new Distortion(this.viewer.distortionCoefficients);
  38131. };
  38132. DeviceInfo.prototype.determineDevice_ = function(deviceParams) {
  38133. if (!deviceParams) {
  38134. // No parameters, so use a default.
  38135. if (Util.isIOS()) {
  38136. console.warn('Using fallback iOS device measurements.');
  38137. return DEFAULT_IOS;
  38138. } else {
  38139. console.warn('Using fallback Android device measurements.');
  38140. return DEFAULT_ANDROID;
  38141. }
  38142. }
  38143. // Compute device screen dimensions based on deviceParams.
  38144. var METERS_PER_INCH = 0.0254;
  38145. var metersPerPixelX = METERS_PER_INCH / deviceParams.xdpi;
  38146. var metersPerPixelY = METERS_PER_INCH / deviceParams.ydpi;
  38147. var width = Util.getScreenWidth();
  38148. var height = Util.getScreenHeight();
  38149. return new Device({
  38150. widthMeters: metersPerPixelX * width,
  38151. heightMeters: metersPerPixelY * height,
  38152. bevelMeters: deviceParams.bevelMm * 0.001,
  38153. });
  38154. };
  38155. /**
  38156. * Calculates field of view for the left eye.
  38157. */
  38158. DeviceInfo.prototype.getDistortedFieldOfViewLeftEye = function() {
  38159. var viewer = this.viewer;
  38160. var device = this.device;
  38161. var distortion = this.distortion;
  38162. // Device.height and device.width for device in portrait mode, so transpose.
  38163. var eyeToScreenDistance = viewer.screenLensDistance;
  38164. var outerDist = (device.widthMeters - viewer.interLensDistance) / 2;
  38165. var innerDist = viewer.interLensDistance / 2;
  38166. var bottomDist = viewer.baselineLensDistance - device.bevelMeters;
  38167. var topDist = device.heightMeters - bottomDist;
  38168. var outerAngle = MathUtil.radToDeg * Math.atan(
  38169. distortion.distort(outerDist / eyeToScreenDistance));
  38170. var innerAngle = MathUtil.radToDeg * Math.atan(
  38171. distortion.distort(innerDist / eyeToScreenDistance));
  38172. var bottomAngle = MathUtil.radToDeg * Math.atan(
  38173. distortion.distort(bottomDist / eyeToScreenDistance));
  38174. var topAngle = MathUtil.radToDeg * Math.atan(
  38175. distortion.distort(topDist / eyeToScreenDistance));
  38176. return {
  38177. leftDegrees: Math.min(outerAngle, viewer.fov),
  38178. rightDegrees: Math.min(innerAngle, viewer.fov),
  38179. downDegrees: Math.min(bottomAngle, viewer.fov),
  38180. upDegrees: Math.min(topAngle, viewer.fov)
  38181. };
  38182. };
  38183. /**
  38184. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38185. * current device and screen parameters.
  38186. */
  38187. DeviceInfo.prototype.getLeftEyeVisibleTanAngles = function() {
  38188. var viewer = this.viewer;
  38189. var device = this.device;
  38190. var distortion = this.distortion;
  38191. // Tan-angles from the max FOV.
  38192. var fovLeft = Math.tan(-MathUtil.degToRad * viewer.fov);
  38193. var fovTop = Math.tan(MathUtil.degToRad * viewer.fov);
  38194. var fovRight = Math.tan(MathUtil.degToRad * viewer.fov);
  38195. var fovBottom = Math.tan(-MathUtil.degToRad * viewer.fov);
  38196. // Viewport size.
  38197. var halfWidth = device.widthMeters / 4;
  38198. var halfHeight = device.heightMeters / 2;
  38199. // Viewport center, measured from left lens position.
  38200. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38201. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38202. var centerY = -verticalLensOffset;
  38203. var centerZ = viewer.screenLensDistance;
  38204. // Tan-angles of the viewport edges, as seen through the lens.
  38205. var screenLeft = distortion.distort((centerX - halfWidth) / centerZ);
  38206. var screenTop = distortion.distort((centerY + halfHeight) / centerZ);
  38207. var screenRight = distortion.distort((centerX + halfWidth) / centerZ);
  38208. var screenBottom = distortion.distort((centerY - halfHeight) / centerZ);
  38209. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38210. var result = new Float32Array(4);
  38211. result[0] = Math.max(fovLeft, screenLeft);
  38212. result[1] = Math.min(fovTop, screenTop);
  38213. result[2] = Math.min(fovRight, screenRight);
  38214. result[3] = Math.max(fovBottom, screenBottom);
  38215. return result;
  38216. };
  38217. /**
  38218. * Calculates the tan-angles from the maximum FOV for the left eye for the
  38219. * current device and screen parameters, assuming no lenses.
  38220. */
  38221. DeviceInfo.prototype.getLeftEyeNoLensTanAngles = function() {
  38222. var viewer = this.viewer;
  38223. var device = this.device;
  38224. var distortion = this.distortion;
  38225. var result = new Float32Array(4);
  38226. // Tan-angles from the max FOV.
  38227. var fovLeft = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38228. var fovTop = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38229. var fovRight = distortion.distortInverse(Math.tan(MathUtil.degToRad * viewer.fov));
  38230. var fovBottom = distortion.distortInverse(Math.tan(-MathUtil.degToRad * viewer.fov));
  38231. // Viewport size.
  38232. var halfWidth = device.widthMeters / 4;
  38233. var halfHeight = device.heightMeters / 2;
  38234. // Viewport center, measured from left lens position.
  38235. var verticalLensOffset = (viewer.baselineLensDistance - device.bevelMeters - halfHeight);
  38236. var centerX = viewer.interLensDistance / 2 - halfWidth;
  38237. var centerY = -verticalLensOffset;
  38238. var centerZ = viewer.screenLensDistance;
  38239. // Tan-angles of the viewport edges, as seen through the lens.
  38240. var screenLeft = (centerX - halfWidth) / centerZ;
  38241. var screenTop = (centerY + halfHeight) / centerZ;
  38242. var screenRight = (centerX + halfWidth) / centerZ;
  38243. var screenBottom = (centerY - halfHeight) / centerZ;
  38244. // Compare the two sets of tan-angles and take the value closer to zero on each side.
  38245. result[0] = Math.max(fovLeft, screenLeft);
  38246. result[1] = Math.min(fovTop, screenTop);
  38247. result[2] = Math.min(fovRight, screenRight);
  38248. result[3] = Math.max(fovBottom, screenBottom);
  38249. return result;
  38250. };
  38251. /**
  38252. * Calculates the screen rectangle visible from the left eye for the
  38253. * current device and screen parameters.
  38254. */
  38255. DeviceInfo.prototype.getLeftEyeVisibleScreenRect = function(undistortedFrustum) {
  38256. var viewer = this.viewer;
  38257. var device = this.device;
  38258. var dist = viewer.screenLensDistance;
  38259. var eyeX = (device.widthMeters - viewer.interLensDistance) / 2;
  38260. var eyeY = viewer.baselineLensDistance - device.bevelMeters;
  38261. var left = (undistortedFrustum[0] * dist + eyeX) / device.widthMeters;
  38262. var top = (undistortedFrustum[1] * dist + eyeY) / device.heightMeters;
  38263. var right = (undistortedFrustum[2] * dist + eyeX) / device.widthMeters;
  38264. var bottom = (undistortedFrustum[3] * dist + eyeY) / device.heightMeters;
  38265. return {
  38266. x: left,
  38267. y: bottom,
  38268. width: right - left,
  38269. height: top - bottom
  38270. };
  38271. };
  38272. DeviceInfo.prototype.getFieldOfViewLeftEye = function(opt_isUndistorted) {
  38273. return opt_isUndistorted ? this.getUndistortedFieldOfViewLeftEye() :
  38274. this.getDistortedFieldOfViewLeftEye();
  38275. };
  38276. DeviceInfo.prototype.getFieldOfViewRightEye = function(opt_isUndistorted) {
  38277. var fov = this.getFieldOfViewLeftEye(opt_isUndistorted);
  38278. return {
  38279. leftDegrees: fov.rightDegrees,
  38280. rightDegrees: fov.leftDegrees,
  38281. upDegrees: fov.upDegrees,
  38282. downDegrees: fov.downDegrees
  38283. };
  38284. };
  38285. /**
  38286. * Calculates undistorted field of view for the left eye.
  38287. */
  38288. DeviceInfo.prototype.getUndistortedFieldOfViewLeftEye = function() {
  38289. var p = this.getUndistortedParams_();
  38290. return {
  38291. leftDegrees: MathUtil.radToDeg * Math.atan(p.outerDist),
  38292. rightDegrees: MathUtil.radToDeg * Math.atan(p.innerDist),
  38293. downDegrees: MathUtil.radToDeg * Math.atan(p.bottomDist),
  38294. upDegrees: MathUtil.radToDeg * Math.atan(p.topDist)
  38295. };
  38296. };
  38297. DeviceInfo.prototype.getUndistortedViewportLeftEye = function() {
  38298. var p = this.getUndistortedParams_();
  38299. var viewer = this.viewer;
  38300. var device = this.device;
  38301. // Distances stored in local variables are in tan-angle units unless otherwise
  38302. // noted.
  38303. var eyeToScreenDistance = viewer.screenLensDistance;
  38304. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38305. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38306. var xPxPerTanAngle = device.width / screenWidth;
  38307. var yPxPerTanAngle = device.height / screenHeight;
  38308. var x = Math.round((p.eyePosX - p.outerDist) * xPxPerTanAngle);
  38309. var y = Math.round((p.eyePosY - p.bottomDist) * yPxPerTanAngle);
  38310. return {
  38311. x: x,
  38312. y: y,
  38313. width: Math.round((p.eyePosX + p.innerDist) * xPxPerTanAngle) - x,
  38314. height: Math.round((p.eyePosY + p.topDist) * yPxPerTanAngle) - y
  38315. };
  38316. };
  38317. DeviceInfo.prototype.getUndistortedParams_ = function() {
  38318. var viewer = this.viewer;
  38319. var device = this.device;
  38320. var distortion = this.distortion;
  38321. // Most of these variables in tan-angle units.
  38322. var eyeToScreenDistance = viewer.screenLensDistance;
  38323. var halfLensDistance = viewer.interLensDistance / 2 / eyeToScreenDistance;
  38324. var screenWidth = device.widthMeters / eyeToScreenDistance;
  38325. var screenHeight = device.heightMeters / eyeToScreenDistance;
  38326. var eyePosX = screenWidth / 2 - halfLensDistance;
  38327. var eyePosY = (viewer.baselineLensDistance - device.bevelMeters) / eyeToScreenDistance;
  38328. var maxFov = viewer.fov;
  38329. var viewerMax = distortion.distortInverse(Math.tan(MathUtil.degToRad * maxFov));
  38330. var outerDist = Math.min(eyePosX, viewerMax);
  38331. var innerDist = Math.min(halfLensDistance, viewerMax);
  38332. var bottomDist = Math.min(eyePosY, viewerMax);
  38333. var topDist = Math.min(screenHeight - eyePosY, viewerMax);
  38334. return {
  38335. outerDist: outerDist,
  38336. innerDist: innerDist,
  38337. topDist: topDist,
  38338. bottomDist: bottomDist,
  38339. eyePosX: eyePosX,
  38340. eyePosY: eyePosY
  38341. };
  38342. };
  38343. function CardboardViewer(params) {
  38344. // A machine readable ID.
  38345. this.id = params.id;
  38346. // A human readable label.
  38347. this.label = params.label;
  38348. // Field of view in degrees (per side).
  38349. this.fov = params.fov;
  38350. // Distance between lens centers in meters.
  38351. this.interLensDistance = params.interLensDistance;
  38352. // Distance between viewer baseline and lens center in meters.
  38353. this.baselineLensDistance = params.baselineLensDistance;
  38354. // Screen-to-lens distance in meters.
  38355. this.screenLensDistance = params.screenLensDistance;
  38356. // Distortion coefficients.
  38357. this.distortionCoefficients = params.distortionCoefficients;
  38358. // Inverse distortion coefficients.
  38359. // TODO: Calculate these from distortionCoefficients in the future.
  38360. this.inverseCoefficients = params.inverseCoefficients;
  38361. }
  38362. // Export viewer information.
  38363. DeviceInfo.Viewers = Viewers;
  38364. module.exports = DeviceInfo;
  38365. },{"./distortion/distortion.js":10,"./math-util.js":15,"./util.js":23}],9:[function(_dereq_,module,exports){
  38366. /*
  38367. * Copyright 2016 Google Inc. All Rights Reserved.
  38368. * Licensed under the Apache License, Version 2.0 (the "License");
  38369. * you may not use this file except in compliance with the License.
  38370. * You may obtain a copy of the License at
  38371. *
  38372. * http://www.apache.org/licenses/LICENSE-2.0
  38373. *
  38374. * Unless required by applicable law or agreed to in writing, software
  38375. * distributed under the License is distributed on an "AS IS" BASIS,
  38376. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38377. * See the License for the specific language governing permissions and
  38378. * limitations under the License.
  38379. */
  38380. var VRDisplay = _dereq_('./base.js').VRDisplay;
  38381. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  38382. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  38383. /**
  38384. * Wraps a VRDisplay and exposes it as a HMDVRDevice
  38385. */
  38386. function VRDisplayHMDDevice(display) {
  38387. this.display = display;
  38388. this.hardwareUnitId = display.displayId;
  38389. this.deviceId = 'webvr-polyfill:HMD:' + display.displayId;
  38390. this.deviceName = display.displayName + ' (HMD)';
  38391. }
  38392. VRDisplayHMDDevice.prototype = new HMDVRDevice();
  38393. VRDisplayHMDDevice.prototype.getEyeParameters = function(whichEye) {
  38394. var eyeParameters = this.display.getEyeParameters(whichEye);
  38395. return {
  38396. currentFieldOfView: eyeParameters.fieldOfView,
  38397. maximumFieldOfView: eyeParameters.fieldOfView,
  38398. minimumFieldOfView: eyeParameters.fieldOfView,
  38399. recommendedFieldOfView: eyeParameters.fieldOfView,
  38400. eyeTranslation: { x: eyeParameters.offset[0], y: eyeParameters.offset[1], z: eyeParameters.offset[2] },
  38401. renderRect: {
  38402. x: (whichEye == 'right') ? eyeParameters.renderWidth : 0,
  38403. y: 0,
  38404. width: eyeParameters.renderWidth,
  38405. height: eyeParameters.renderHeight
  38406. }
  38407. };
  38408. };
  38409. VRDisplayHMDDevice.prototype.setFieldOfView =
  38410. function(opt_fovLeft, opt_fovRight, opt_zNear, opt_zFar) {
  38411. // Not supported. getEyeParameters reports that the min, max, and recommended
  38412. // FoV is all the same, so no adjustment can be made.
  38413. };
  38414. // TODO: Need to hook requestFullscreen to see if a wrapped VRDisplay was passed
  38415. // in as an option. If so we should prevent the default fullscreen behavior and
  38416. // call VRDisplay.requestPresent instead.
  38417. /**
  38418. * Wraps a VRDisplay and exposes it as a PositionSensorVRDevice
  38419. */
  38420. function VRDisplayPositionSensorDevice(display) {
  38421. this.display = display;
  38422. this.hardwareUnitId = display.displayId;
  38423. this.deviceId = 'webvr-polyfill:PositionSensor: ' + display.displayId;
  38424. this.deviceName = display.displayName + ' (PositionSensor)';
  38425. }
  38426. VRDisplayPositionSensorDevice.prototype = new PositionSensorVRDevice();
  38427. VRDisplayPositionSensorDevice.prototype.getState = function() {
  38428. var pose = this.display.getPose();
  38429. return {
  38430. position: pose.position ? { x: pose.position[0], y: pose.position[1], z: pose.position[2] } : null,
  38431. orientation: pose.orientation ? { x: pose.orientation[0], y: pose.orientation[1], z: pose.orientation[2], w: pose.orientation[3] } : null,
  38432. linearVelocity: null,
  38433. linearAcceleration: null,
  38434. angularVelocity: null,
  38435. angularAcceleration: null
  38436. };
  38437. };
  38438. VRDisplayPositionSensorDevice.prototype.resetState = function() {
  38439. return this.positionDevice.resetPose();
  38440. };
  38441. module.exports.VRDisplayHMDDevice = VRDisplayHMDDevice;
  38442. module.exports.VRDisplayPositionSensorDevice = VRDisplayPositionSensorDevice;
  38443. },{"./base.js":3}],10:[function(_dereq_,module,exports){
  38444. /**
  38445. * TODO(smus): Implement coefficient inversion.
  38446. */
  38447. function Distortion(coefficients) {
  38448. this.coefficients = coefficients;
  38449. }
  38450. /**
  38451. * Calculates the inverse distortion for a radius.
  38452. * </p><p>
  38453. * Allows to compute the original undistorted radius from a distorted one.
  38454. * See also getApproximateInverseDistortion() for a faster but potentially
  38455. * less accurate method.
  38456. *
  38457. * @param {Number} radius Distorted radius from the lens center in tan-angle units.
  38458. * @return {Number} The undistorted radius in tan-angle units.
  38459. */
  38460. Distortion.prototype.distortInverse = function(radius) {
  38461. // Secant method.
  38462. var r0 = 0;
  38463. var r1 = 1;
  38464. var dr0 = radius - this.distort(r0);
  38465. while (Math.abs(r1 - r0) > 0.0001 /** 0.1mm */) {
  38466. var dr1 = radius - this.distort(r1);
  38467. var r2 = r1 - dr1 * ((r1 - r0) / (dr1 - dr0));
  38468. r0 = r1;
  38469. r1 = r2;
  38470. dr0 = dr1;
  38471. }
  38472. return r1;
  38473. };
  38474. /**
  38475. * Distorts a radius by its distortion factor from the center of the lenses.
  38476. *
  38477. * @param {Number} radius Radius from the lens center in tan-angle units.
  38478. * @return {Number} The distorted radius in tan-angle units.
  38479. */
  38480. Distortion.prototype.distort = function(radius) {
  38481. var r2 = radius * radius;
  38482. var ret = 0;
  38483. for (var i = 0; i < this.coefficients.length; i++) {
  38484. ret = r2 * (ret + this.coefficients[i]);
  38485. }
  38486. return (ret + 1) * radius;
  38487. };
  38488. // Functions below roughly ported from
  38489. // https://github.com/googlesamples/cardboard-unity/blob/master/Cardboard/Scripts/CardboardProfile.cs#L412
  38490. // Solves a small linear equation via destructive gaussian
  38491. // elimination and back substitution. This isn't generic numeric
  38492. // code, it's just a quick hack to work with the generally
  38493. // well-behaved symmetric matrices for least-squares fitting.
  38494. // Not intended for reuse.
  38495. //
  38496. // @param a Input positive definite symmetrical matrix. Destroyed
  38497. // during calculation.
  38498. // @param y Input right-hand-side values. Destroyed during calculation.
  38499. // @return Resulting x value vector.
  38500. //
  38501. Distortion.prototype.solveLinear_ = function(a, y) {
  38502. var n = a.length;
  38503. // Gaussian elimination (no row exchange) to triangular matrix.
  38504. // The input matrix is a A^T A product which should be a positive
  38505. // definite symmetrical matrix, and if I remember my linear
  38506. // algebra right this implies that the pivots will be nonzero and
  38507. // calculations sufficiently accurate without needing row
  38508. // exchange.
  38509. for (var j = 0; j < n - 1; ++j) {
  38510. for (var k = j + 1; k < n; ++k) {
  38511. var p = a[j][k] / a[j][j];
  38512. for (var i = j + 1; i < n; ++i) {
  38513. a[i][k] -= p * a[i][j];
  38514. }
  38515. y[k] -= p * y[j];
  38516. }
  38517. }
  38518. // From this point on, only the matrix elements a[j][i] with i>=j are
  38519. // valid. The elimination doesn't fill in eliminated 0 values.
  38520. var x = new Array(n);
  38521. // Back substitution.
  38522. for (var j = n - 1; j >= 0; --j) {
  38523. var v = y[j];
  38524. for (var i = j + 1; i < n; ++i) {
  38525. v -= a[i][j] * x[i];
  38526. }
  38527. x[j] = v / a[j][j];
  38528. }
  38529. return x;
  38530. };
  38531. // Solves a least-squares matrix equation. Given the equation A * x = y, calculate the
  38532. // least-square fit x = inverse(A * transpose(A)) * transpose(A) * y. The way this works
  38533. // is that, while A is typically not a square matrix (and hence not invertible), A * transpose(A)
  38534. // is always square. That is:
  38535. // A * x = y
  38536. // transpose(A) * (A * x) = transpose(A) * y <- multiply both sides by transpose(A)
  38537. // (transpose(A) * A) * x = transpose(A) * y <- associativity
  38538. // x = inverse(transpose(A) * A) * transpose(A) * y <- solve for x
  38539. // Matrix A's row count (first index) must match y's value count. A's column count (second index)
  38540. // determines the length of the result vector x.
  38541. Distortion.prototype.solveLeastSquares_ = function(matA, vecY) {
  38542. var i, j, k, sum;
  38543. var numSamples = matA.length;
  38544. var numCoefficients = matA[0].length;
  38545. if (numSamples != vecY.Length) {
  38546. throw new Error("Matrix / vector dimension mismatch");
  38547. }
  38548. // Calculate transpose(A) * A
  38549. var matATA = new Array(numCoefficients);
  38550. for (k = 0; k < numCoefficients; ++k) {
  38551. matATA[k] = new Array(numCoefficients);
  38552. for (j = 0; j < numCoefficients; ++j) {
  38553. sum = 0;
  38554. for (i = 0; i < numSamples; ++i) {
  38555. sum += matA[j][i] * matA[k][i];
  38556. }
  38557. matATA[k][j] = sum;
  38558. }
  38559. }
  38560. // Calculate transpose(A) * y
  38561. var vecATY = new Array(numCoefficients);
  38562. for (j = 0; j < numCoefficients; ++j) {
  38563. sum = 0;
  38564. for (i = 0; i < numSamples; ++i) {
  38565. sum += matA[j][i] * vecY[i];
  38566. }
  38567. vecATY[j] = sum;
  38568. }
  38569. // Now solve (A * transpose(A)) * x = transpose(A) * y.
  38570. return this.solveLinear_(matATA, vecATY);
  38571. };
  38572. /// Calculates an approximate inverse to the given radial distortion parameters.
  38573. Distortion.prototype.approximateInverse = function(maxRadius, numSamples) {
  38574. maxRadius = maxRadius || 1;
  38575. numSamples = numSamples || 100;
  38576. var numCoefficients = 6;
  38577. var i, j;
  38578. // R + K1*R^3 + K2*R^5 = r, with R = rp = distort(r)
  38579. // Repeating for numSamples:
  38580. // [ R0^3, R0^5 ] * [ K1 ] = [ r0 - R0 ]
  38581. // [ R1^3, R1^5 ] [ K2 ] [ r1 - R1 ]
  38582. // [ R2^3, R2^5 ] [ r2 - R2 ]
  38583. // [ etc... ] [ etc... ]
  38584. // That is:
  38585. // matA * [K1, K2] = y
  38586. // Solve:
  38587. // [K1, K2] = inverse(transpose(matA) * matA) * transpose(matA) * y
  38588. var matA = new Array(numCoefficients);
  38589. for (j = 0; j < numCoefficients; ++j) {
  38590. matA[j] = new Array(numSamples);
  38591. }
  38592. var vecY = new Array(numSamples);
  38593. for (i = 0; i < numSamples; ++i) {
  38594. var r = maxRadius * (i + 1) / numSamples;
  38595. var rp = this.distort(r);
  38596. var v = rp;
  38597. for (j = 0; j < numCoefficients; ++j) {
  38598. v *= rp * rp;
  38599. matA[j][i] = v;
  38600. }
  38601. vecY[i] = r - rp;
  38602. }
  38603. var inverseCoefficients = this.solveLeastSquares_(matA, vecY);
  38604. return new Distortion(inverseCoefficients);
  38605. };
  38606. module.exports = Distortion;
  38607. },{}],11:[function(_dereq_,module,exports){
  38608. /*
  38609. * Copyright 2015 Google Inc. All Rights Reserved.
  38610. * Licensed under the Apache License, Version 2.0 (the "License");
  38611. * you may not use this file except in compliance with the License.
  38612. * You may obtain a copy of the License at
  38613. *
  38614. * http://www.apache.org/licenses/LICENSE-2.0
  38615. *
  38616. * Unless required by applicable law or agreed to in writing, software
  38617. * distributed under the License is distributed on an "AS IS" BASIS,
  38618. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  38619. * See the License for the specific language governing permissions and
  38620. * limitations under the License.
  38621. */
  38622. /**
  38623. * DPDB cache.
  38624. */
  38625. var DPDB_CACHE = {
  38626. "format": 1,
  38627. "last_updated": "2016-01-20T00:18:35Z",
  38628. "devices": [
  38629. {
  38630. "type": "android",
  38631. "rules": [
  38632. { "mdmh": "asus/*/Nexus 7/*" },
  38633. { "ua": "Nexus 7" }
  38634. ],
  38635. "dpi": [ 320.8, 323.0 ],
  38636. "bw": 3,
  38637. "ac": 500
  38638. },
  38639. {
  38640. "type": "android",
  38641. "rules": [
  38642. { "mdmh": "asus/*/ASUS_Z00AD/*" },
  38643. { "ua": "ASUS_Z00AD" }
  38644. ],
  38645. "dpi": [ 403.0, 404.6 ],
  38646. "bw": 3,
  38647. "ac": 1000
  38648. },
  38649. {
  38650. "type": "android",
  38651. "rules": [
  38652. { "mdmh": "Google//Pixel XL/" },
  38653. { "ua": "Pixel XL" }
  38654. ],
  38655. "dpi": [537.9, 533],
  38656. "bw": 3,
  38657. "ac": 1000
  38658. },
  38659. {
  38660. "type": "android",
  38661. "rules": [
  38662. { "mdmh": "HTC/*/HTC6435LVW/*" },
  38663. { "ua": "HTC6435LVW" }
  38664. ],
  38665. "dpi": [ 449.7, 443.3 ],
  38666. "bw": 3,
  38667. "ac": 1000
  38668. },
  38669. {
  38670. "type": "android",
  38671. "rules": [
  38672. { "mdmh": "HTC/*/HTC One XL/*" },
  38673. { "ua": "HTC One XL" }
  38674. ],
  38675. "dpi": [ 315.3, 314.6 ],
  38676. "bw": 3,
  38677. "ac": 1000
  38678. },
  38679. {
  38680. "type": "android",
  38681. "rules": [
  38682. { "mdmh": "htc/*/Nexus 9/*" },
  38683. { "ua": "Nexus 9" }
  38684. ],
  38685. "dpi": 289.0,
  38686. "bw": 3,
  38687. "ac": 500
  38688. },
  38689. {
  38690. "type": "android",
  38691. "rules": [
  38692. { "mdmh": "HTC/*/HTC One M9/*" },
  38693. { "ua": "HTC One M9" }
  38694. ],
  38695. "dpi": [ 442.5, 443.3 ],
  38696. "bw": 3,
  38697. "ac": 500
  38698. },
  38699. {
  38700. "type": "android",
  38701. "rules": [
  38702. { "mdmh": "HTC/*/HTC One_M8/*" },
  38703. { "ua": "HTC One_M8" }
  38704. ],
  38705. "dpi": [ 449.7, 447.4 ],
  38706. "bw": 3,
  38707. "ac": 500
  38708. },
  38709. {
  38710. "type": "android",
  38711. "rules": [
  38712. { "mdmh": "HTC/*/HTC One/*" },
  38713. { "ua": "HTC One" }
  38714. ],
  38715. "dpi": 472.8,
  38716. "bw": 3,
  38717. "ac": 1000
  38718. },
  38719. {
  38720. "type": "android",
  38721. "rules": [
  38722. { "mdmh": "Huawei/*/Nexus 6P/*" },
  38723. { "ua": "Nexus 6P" }
  38724. ],
  38725. "dpi": [ 515.1, 518.0 ],
  38726. "bw": 3,
  38727. "ac": 1000
  38728. },
  38729. {
  38730. "type": "android",
  38731. "rules": [
  38732. { "mdmh": "LGE/*/Nexus 5X/*" },
  38733. { "ua": "Nexus 5X" }
  38734. ],
  38735. "dpi": [ 422.0, 419.9 ],
  38736. "bw": 3,
  38737. "ac": 1000
  38738. },
  38739. {
  38740. "type": "android",
  38741. "rules": [
  38742. { "mdmh": "LGE/*/LGMS345/*" },
  38743. { "ua": "LGMS345" }
  38744. ],
  38745. "dpi": [ 221.7, 219.1 ],
  38746. "bw": 3,
  38747. "ac": 500
  38748. },
  38749. {
  38750. "type": "android",
  38751. "rules": [
  38752. { "mdmh": "LGE/*/LG-D800/*" },
  38753. { "ua": "LG-D800" }
  38754. ],
  38755. "dpi": [ 422.0, 424.1 ],
  38756. "bw": 3,
  38757. "ac": 500
  38758. },
  38759. {
  38760. "type": "android",
  38761. "rules": [
  38762. { "mdmh": "LGE/*/LG-D850/*" },
  38763. { "ua": "LG-D850" }
  38764. ],
  38765. "dpi": [ 537.9, 541.9 ],
  38766. "bw": 3,
  38767. "ac": 500
  38768. },
  38769. {
  38770. "type": "android",
  38771. "rules": [
  38772. { "mdmh": "LGE/*/VS985 4G/*" },
  38773. { "ua": "VS985 4G" }
  38774. ],
  38775. "dpi": [ 537.9, 535.6 ],
  38776. "bw": 3,
  38777. "ac": 1000
  38778. },
  38779. {
  38780. "type": "android",
  38781. "rules": [
  38782. { "mdmh": "LGE/*/Nexus 5/*" },
  38783. { "ua": "Nexus 5 " }
  38784. ],
  38785. "dpi": [ 442.4, 444.8 ],
  38786. "bw": 3,
  38787. "ac": 1000
  38788. },
  38789. {
  38790. "type": "android",
  38791. "rules": [
  38792. { "mdmh": "LGE/*/Nexus 4/*" },
  38793. { "ua": "Nexus 4" }
  38794. ],
  38795. "dpi": [ 319.8, 318.4 ],
  38796. "bw": 3,
  38797. "ac": 1000
  38798. },
  38799. {
  38800. "type": "android",
  38801. "rules": [
  38802. { "mdmh": "LGE/*/LG-P769/*" },
  38803. { "ua": "LG-P769" }
  38804. ],
  38805. "dpi": [ 240.6, 247.5 ],
  38806. "bw": 3,
  38807. "ac": 1000
  38808. },
  38809. {
  38810. "type": "android",
  38811. "rules": [
  38812. { "mdmh": "LGE/*/LGMS323/*" },
  38813. { "ua": "LGMS323" }
  38814. ],
  38815. "dpi": [ 206.6, 204.6 ],
  38816. "bw": 3,
  38817. "ac": 1000
  38818. },
  38819. {
  38820. "type": "android",
  38821. "rules": [
  38822. { "mdmh": "LGE/*/LGLS996/*" },
  38823. { "ua": "LGLS996" }
  38824. ],
  38825. "dpi": [ 403.4, 401.5 ],
  38826. "bw": 3,
  38827. "ac": 1000
  38828. },
  38829. {
  38830. "type": "android",
  38831. "rules": [
  38832. { "mdmh": "Micromax/*/4560MMX/*" },
  38833. { "ua": "4560MMX" }
  38834. ],
  38835. "dpi": [ 240.0, 219.4 ],
  38836. "bw": 3,
  38837. "ac": 1000
  38838. },
  38839. {
  38840. "type": "android",
  38841. "rules": [
  38842. { "mdmh": "Micromax/*/A250/*" },
  38843. { "ua": "Micromax A250" }
  38844. ],
  38845. "dpi": [ 480.0, 446.4 ],
  38846. "bw": 3,
  38847. "ac": 1000
  38848. },
  38849. {
  38850. "type": "android",
  38851. "rules": [
  38852. { "mdmh": "Micromax/*/Micromax AQ4501/*" },
  38853. { "ua": "Micromax AQ4501" }
  38854. ],
  38855. "dpi": 240.0,
  38856. "bw": 3,
  38857. "ac": 500
  38858. },
  38859. {
  38860. "type": "android",
  38861. "rules": [
  38862. { "mdmh": "motorola/*/DROID RAZR/*" },
  38863. { "ua": "DROID RAZR" }
  38864. ],
  38865. "dpi": [ 368.1, 256.7 ],
  38866. "bw": 3,
  38867. "ac": 1000
  38868. },
  38869. {
  38870. "type": "android",
  38871. "rules": [
  38872. { "mdmh": "motorola/*/XT830C/*" },
  38873. { "ua": "XT830C" }
  38874. ],
  38875. "dpi": [ 254.0, 255.9 ],
  38876. "bw": 3,
  38877. "ac": 1000
  38878. },
  38879. {
  38880. "type": "android",
  38881. "rules": [
  38882. { "mdmh": "motorola/*/XT1021/*" },
  38883. { "ua": "XT1021" }
  38884. ],
  38885. "dpi": [ 254.0, 256.7 ],
  38886. "bw": 3,
  38887. "ac": 500
  38888. },
  38889. {
  38890. "type": "android",
  38891. "rules": [
  38892. { "mdmh": "motorola/*/XT1023/*" },
  38893. { "ua": "XT1023" }
  38894. ],
  38895. "dpi": [ 254.0, 256.7 ],
  38896. "bw": 3,
  38897. "ac": 500
  38898. },
  38899. {
  38900. "type": "android",
  38901. "rules": [
  38902. { "mdmh": "motorola/*/XT1028/*" },
  38903. { "ua": "XT1028" }
  38904. ],
  38905. "dpi": [ 326.6, 327.6 ],
  38906. "bw": 3,
  38907. "ac": 1000
  38908. },
  38909. {
  38910. "type": "android",
  38911. "rules": [
  38912. { "mdmh": "motorola/*/XT1034/*" },
  38913. { "ua": "XT1034" }
  38914. ],
  38915. "dpi": [ 326.6, 328.4 ],
  38916. "bw": 3,
  38917. "ac": 500
  38918. },
  38919. {
  38920. "type": "android",
  38921. "rules": [
  38922. { "mdmh": "motorola/*/XT1053/*" },
  38923. { "ua": "XT1053" }
  38924. ],
  38925. "dpi": [ 315.3, 316.1 ],
  38926. "bw": 3,
  38927. "ac": 1000
  38928. },
  38929. {
  38930. "type": "android",
  38931. "rules": [
  38932. { "mdmh": "motorola/*/XT1562/*" },
  38933. { "ua": "XT1562" }
  38934. ],
  38935. "dpi": [ 403.4, 402.7 ],
  38936. "bw": 3,
  38937. "ac": 1000
  38938. },
  38939. {
  38940. "type": "android",
  38941. "rules": [
  38942. { "mdmh": "motorola/*/Nexus 6/*" },
  38943. { "ua": "Nexus 6 " }
  38944. ],
  38945. "dpi": [ 494.3, 489.7 ],
  38946. "bw": 3,
  38947. "ac": 1000
  38948. },
  38949. {
  38950. "type": "android",
  38951. "rules": [
  38952. { "mdmh": "motorola/*/XT1063/*" },
  38953. { "ua": "XT1063" }
  38954. ],
  38955. "dpi": [ 295.0, 296.6 ],
  38956. "bw": 3,
  38957. "ac": 1000
  38958. },
  38959. {
  38960. "type": "android",
  38961. "rules": [
  38962. { "mdmh": "motorola/*/XT1064/*" },
  38963. { "ua": "XT1064" }
  38964. ],
  38965. "dpi": [ 295.0, 295.6 ],
  38966. "bw": 3,
  38967. "ac": 500
  38968. },
  38969. {
  38970. "type": "android",
  38971. "rules": [
  38972. { "mdmh": "motorola/*/XT1092/*" },
  38973. { "ua": "XT1092" }
  38974. ],
  38975. "dpi": [ 422.0, 424.1 ],
  38976. "bw": 3,
  38977. "ac": 500
  38978. },
  38979. {
  38980. "type": "android",
  38981. "rules": [
  38982. { "mdmh": "motorola/*/XT1095/*" },
  38983. { "ua": "XT1095" }
  38984. ],
  38985. "dpi": [ 422.0, 423.4 ],
  38986. "bw": 3,
  38987. "ac": 1000
  38988. },
  38989. {
  38990. "type": "android",
  38991. "rules": [
  38992. { "mdmh": "motorola/*/G4/*" },
  38993. { "ua": "Moto G (4)" }
  38994. ],
  38995. "dpi": 401.0,
  38996. "bw": 4,
  38997. "ac": 1000
  38998. },
  38999. {
  39000. "type": "android",
  39001. "rules": [
  39002. { "mdmh": "OnePlus/*/A0001/*" },
  39003. { "ua": "A0001" }
  39004. ],
  39005. "dpi": [ 403.4, 401.0 ],
  39006. "bw": 3,
  39007. "ac": 1000
  39008. },
  39009. {
  39010. "type": "android",
  39011. "rules": [
  39012. { "mdmh": "OnePlus/*/ONE E1005/*" },
  39013. { "ua": "ONE E1005" }
  39014. ],
  39015. "dpi": [ 442.4, 441.4 ],
  39016. "bw": 3,
  39017. "ac": 1000
  39018. },
  39019. {
  39020. "type": "android",
  39021. "rules": [
  39022. { "mdmh": "OnePlus/*/ONE A2005/*" },
  39023. { "ua": "ONE A2005" }
  39024. ],
  39025. "dpi": [ 391.9, 405.4 ],
  39026. "bw": 3,
  39027. "ac": 1000
  39028. },
  39029. {
  39030. "type": "android",
  39031. "rules": [
  39032. { "mdmh": "OPPO/*/X909/*" },
  39033. { "ua": "X909" }
  39034. ],
  39035. "dpi": [ 442.4, 444.1 ],
  39036. "bw": 3,
  39037. "ac": 1000
  39038. },
  39039. {
  39040. "type": "android",
  39041. "rules": [
  39042. { "mdmh": "samsung/*/GT-I9082/*" },
  39043. { "ua": "GT-I9082" }
  39044. ],
  39045. "dpi": [ 184.7, 185.4 ],
  39046. "bw": 3,
  39047. "ac": 1000
  39048. },
  39049. {
  39050. "type": "android",
  39051. "rules": [
  39052. { "mdmh": "samsung/*/SM-G360P/*" },
  39053. { "ua": "SM-G360P" }
  39054. ],
  39055. "dpi": [ 196.7, 205.4 ],
  39056. "bw": 3,
  39057. "ac": 1000
  39058. },
  39059. {
  39060. "type": "android",
  39061. "rules": [
  39062. { "mdmh": "samsung/*/Nexus S/*" },
  39063. { "ua": "Nexus S" }
  39064. ],
  39065. "dpi": [ 234.5, 229.8 ],
  39066. "bw": 3,
  39067. "ac": 1000
  39068. },
  39069. {
  39070. "type": "android",
  39071. "rules": [
  39072. { "mdmh": "samsung/*/GT-I9300/*" },
  39073. { "ua": "GT-I9300" }
  39074. ],
  39075. "dpi": [ 304.8, 303.9 ],
  39076. "bw": 5,
  39077. "ac": 500
  39078. },
  39079. {
  39080. "type": "android",
  39081. "rules": [
  39082. { "mdmh": "samsung/*/SM-T230NU/*" },
  39083. { "ua": "SM-T230NU" }
  39084. ],
  39085. "dpi": 216.0,
  39086. "bw": 3,
  39087. "ac": 500
  39088. },
  39089. {
  39090. "type": "android",
  39091. "rules": [
  39092. { "mdmh": "samsung/*/SGH-T399/*" },
  39093. { "ua": "SGH-T399" }
  39094. ],
  39095. "dpi": [ 217.7, 231.4 ],
  39096. "bw": 3,
  39097. "ac": 1000
  39098. },
  39099. {
  39100. "type": "android",
  39101. "rules": [
  39102. { "mdmh": "samsung/*/SM-N9005/*" },
  39103. { "ua": "SM-N9005" }
  39104. ],
  39105. "dpi": [ 386.4, 387.0 ],
  39106. "bw": 3,
  39107. "ac": 500
  39108. },
  39109. {
  39110. "type": "android",
  39111. "rules": [
  39112. { "mdmh": "samsung/*/SAMSUNG-SM-N900A/*" },
  39113. { "ua": "SAMSUNG-SM-N900A" }
  39114. ],
  39115. "dpi": [ 386.4, 387.7 ],
  39116. "bw": 3,
  39117. "ac": 1000
  39118. },
  39119. {
  39120. "type": "android",
  39121. "rules": [
  39122. { "mdmh": "samsung/*/GT-I9500/*" },
  39123. { "ua": "GT-I9500" }
  39124. ],
  39125. "dpi": [ 442.5, 443.3 ],
  39126. "bw": 3,
  39127. "ac": 500
  39128. },
  39129. {
  39130. "type": "android",
  39131. "rules": [
  39132. { "mdmh": "samsung/*/GT-I9505/*" },
  39133. { "ua": "GT-I9505" }
  39134. ],
  39135. "dpi": 439.4,
  39136. "bw": 4,
  39137. "ac": 1000
  39138. },
  39139. {
  39140. "type": "android",
  39141. "rules": [
  39142. { "mdmh": "samsung/*/SM-G900F/*" },
  39143. { "ua": "SM-G900F" }
  39144. ],
  39145. "dpi": [ 415.6, 431.6 ],
  39146. "bw": 5,
  39147. "ac": 1000
  39148. },
  39149. {
  39150. "type": "android",
  39151. "rules": [
  39152. { "mdmh": "samsung/*/SM-G900M/*" },
  39153. { "ua": "SM-G900M" }
  39154. ],
  39155. "dpi": [ 415.6, 431.6 ],
  39156. "bw": 5,
  39157. "ac": 1000
  39158. },
  39159. {
  39160. "type": "android",
  39161. "rules": [
  39162. { "mdmh": "samsung/*/SM-G800F/*" },
  39163. { "ua": "SM-G800F" }
  39164. ],
  39165. "dpi": 326.8,
  39166. "bw": 3,
  39167. "ac": 1000
  39168. },
  39169. {
  39170. "type": "android",
  39171. "rules": [
  39172. { "mdmh": "samsung/*/SM-G906S/*" },
  39173. { "ua": "SM-G906S" }
  39174. ],
  39175. "dpi": [ 562.7, 572.4 ],
  39176. "bw": 3,
  39177. "ac": 1000
  39178. },
  39179. {
  39180. "type": "android",
  39181. "rules": [
  39182. { "mdmh": "samsung/*/GT-I9300/*" },
  39183. { "ua": "GT-I9300" }
  39184. ],
  39185. "dpi": [ 306.7, 304.8 ],
  39186. "bw": 5,
  39187. "ac": 1000
  39188. },
  39189. {
  39190. "type": "android",
  39191. "rules": [
  39192. { "mdmh": "samsung/*/SM-T535/*" },
  39193. { "ua": "SM-T535" }
  39194. ],
  39195. "dpi": [ 142.6, 136.4 ],
  39196. "bw": 3,
  39197. "ac": 500
  39198. },
  39199. {
  39200. "type": "android",
  39201. "rules": [
  39202. { "mdmh": "samsung/*/SM-N920C/*" },
  39203. { "ua": "SM-N920C" }
  39204. ],
  39205. "dpi": [ 515.1, 518.4 ],
  39206. "bw": 3,
  39207. "ac": 1000
  39208. },
  39209. {
  39210. "type": "android",
  39211. "rules": [
  39212. { "mdmh": "samsung/*/GT-I9300I/*" },
  39213. { "ua": "GT-I9300I" }
  39214. ],
  39215. "dpi": [ 304.8, 305.8 ],
  39216. "bw": 3,
  39217. "ac": 1000
  39218. },
  39219. {
  39220. "type": "android",
  39221. "rules": [
  39222. { "mdmh": "samsung/*/GT-I9195/*" },
  39223. { "ua": "GT-I9195" }
  39224. ],
  39225. "dpi": [ 249.4, 256.7 ],
  39226. "bw": 3,
  39227. "ac": 500
  39228. },
  39229. {
  39230. "type": "android",
  39231. "rules": [
  39232. { "mdmh": "samsung/*/SPH-L520/*" },
  39233. { "ua": "SPH-L520" }
  39234. ],
  39235. "dpi": [ 249.4, 255.9 ],
  39236. "bw": 3,
  39237. "ac": 1000
  39238. },
  39239. {
  39240. "type": "android",
  39241. "rules": [
  39242. { "mdmh": "samsung/*/SAMSUNG-SGH-I717/*" },
  39243. { "ua": "SAMSUNG-SGH-I717" }
  39244. ],
  39245. "dpi": 285.8,
  39246. "bw": 3,
  39247. "ac": 1000
  39248. },
  39249. {
  39250. "type": "android",
  39251. "rules": [
  39252. { "mdmh": "samsung/*/SPH-D710/*" },
  39253. { "ua": "SPH-D710" }
  39254. ],
  39255. "dpi": [ 217.7, 204.2 ],
  39256. "bw": 3,
  39257. "ac": 1000
  39258. },
  39259. {
  39260. "type": "android",
  39261. "rules": [
  39262. { "mdmh": "samsung/*/GT-N7100/*" },
  39263. { "ua": "GT-N7100" }
  39264. ],
  39265. "dpi": 265.1,
  39266. "bw": 3,
  39267. "ac": 1000
  39268. },
  39269. {
  39270. "type": "android",
  39271. "rules": [
  39272. { "mdmh": "samsung/*/SCH-I605/*" },
  39273. { "ua": "SCH-I605" }
  39274. ],
  39275. "dpi": 265.1,
  39276. "bw": 3,
  39277. "ac": 1000
  39278. },
  39279. {
  39280. "type": "android",
  39281. "rules": [
  39282. { "mdmh": "samsung/*/Galaxy Nexus/*" },
  39283. { "ua": "Galaxy Nexus" }
  39284. ],
  39285. "dpi": [ 315.3, 314.2 ],
  39286. "bw": 3,
  39287. "ac": 1000
  39288. },
  39289. {
  39290. "type": "android",
  39291. "rules": [
  39292. { "mdmh": "samsung/*/SM-N910H/*" },
  39293. { "ua": "SM-N910H" }
  39294. ],
  39295. "dpi": [ 515.1, 518.0 ],
  39296. "bw": 3,
  39297. "ac": 1000
  39298. },
  39299. {
  39300. "type": "android",
  39301. "rules": [
  39302. { "mdmh": "samsung/*/SM-N910C/*" },
  39303. { "ua": "SM-N910C" }
  39304. ],
  39305. "dpi": [ 515.2, 520.2 ],
  39306. "bw": 3,
  39307. "ac": 500
  39308. },
  39309. {
  39310. "type": "android",
  39311. "rules": [
  39312. { "mdmh": "samsung/*/SM-G130M/*" },
  39313. { "ua": "SM-G130M" }
  39314. ],
  39315. "dpi": [ 165.9, 164.8 ],
  39316. "bw": 3,
  39317. "ac": 500
  39318. },
  39319. {
  39320. "type": "android",
  39321. "rules": [
  39322. { "mdmh": "samsung/*/SM-G928I/*" },
  39323. { "ua": "SM-G928I" }
  39324. ],
  39325. "dpi": [ 515.1, 518.4 ],
  39326. "bw": 3,
  39327. "ac": 1000
  39328. },
  39329. {
  39330. "type": "android",
  39331. "rules": [
  39332. { "mdmh": "samsung/*/SM-G920F/*" },
  39333. { "ua": "SM-G920F" }
  39334. ],
  39335. "dpi": 580.6,
  39336. "bw": 3,
  39337. "ac": 500
  39338. },
  39339. {
  39340. "type": "android",
  39341. "rules": [
  39342. { "mdmh": "samsung/*/SM-G920P/*" },
  39343. { "ua": "SM-G920P" }
  39344. ],
  39345. "dpi": [ 522.5, 577.0 ],
  39346. "bw": 3,
  39347. "ac": 1000
  39348. },
  39349. {
  39350. "type": "android",
  39351. "rules": [
  39352. { "mdmh": "samsung/*/SM-G925F/*" },
  39353. { "ua": "SM-G925F" }
  39354. ],
  39355. "dpi": 580.6,
  39356. "bw": 3,
  39357. "ac": 500
  39358. },
  39359. {
  39360. "type": "android",
  39361. "rules": [
  39362. { "mdmh": "samsung/*/SM-G925V/*" },
  39363. { "ua": "SM-G925V" }
  39364. ],
  39365. "dpi": [ 522.5, 576.6 ],
  39366. "bw": 3,
  39367. "ac": 1000
  39368. },
  39369. {
  39370. "type": "android",
  39371. "rules": [
  39372. { "mdmh": "samsung/*/SM-G935F/*" },
  39373. { "ua": "SM-G935F" }
  39374. ],
  39375. "dpi": 534,
  39376. "bw": 3,
  39377. "ac": 500
  39378. },
  39379. {
  39380. "type": "android",
  39381. "rules": [
  39382. { "mdmh": "Sony/*/C6903/*" },
  39383. { "ua": "C6903" }
  39384. ],
  39385. "dpi": [ 442.5, 443.3 ],
  39386. "bw": 3,
  39387. "ac": 500
  39388. },
  39389. {
  39390. "type": "android",
  39391. "rules": [
  39392. { "mdmh": "Sony/*/D6653/*" },
  39393. { "ua": "D6653" }
  39394. ],
  39395. "dpi": [ 428.6, 427.6 ],
  39396. "bw": 3,
  39397. "ac": 1000
  39398. },
  39399. {
  39400. "type": "android",
  39401. "rules": [
  39402. { "mdmh": "Sony/*/E6653/*" },
  39403. { "ua": "E6653" }
  39404. ],
  39405. "dpi": [ 428.6, 425.7 ],
  39406. "bw": 3,
  39407. "ac": 1000
  39408. },
  39409. {
  39410. "type": "android",
  39411. "rules": [
  39412. { "mdmh": "Sony/*/E6853/*" },
  39413. { "ua": "E6853" }
  39414. ],
  39415. "dpi": [ 403.4, 401.9 ],
  39416. "bw": 3,
  39417. "ac": 1000
  39418. },
  39419. {
  39420. "type": "android",
  39421. "rules": [
  39422. { "mdmh": "Sony/*/SGP321/*" },
  39423. { "ua": "SGP321" }
  39424. ],
  39425. "dpi": [ 224.7, 224.1 ],
  39426. "bw": 3,
  39427. "ac": 500
  39428. },
  39429. {
  39430. "type": "android",
  39431. "rules": [
  39432. { "mdmh": "TCT/*/ALCATEL ONE TOUCH Fierce/*" },
  39433. { "ua": "ALCATEL ONE TOUCH Fierce" }
  39434. ],
  39435. "dpi": [ 240.0, 247.5 ],
  39436. "bw": 3,
  39437. "ac": 1000
  39438. },
  39439. {
  39440. "type": "android",
  39441. "rules": [
  39442. { "mdmh": "THL/*/thl 5000/*" },
  39443. { "ua": "thl 5000" }
  39444. ],
  39445. "dpi": [ 480.0, 443.3 ],
  39446. "bw": 3,
  39447. "ac": 1000
  39448. },
  39449. {
  39450. "type": "android",
  39451. "rules": [
  39452. { "mdmh": "ZTE/*/ZTE Blade L2/*" },
  39453. { "ua": "ZTE Blade L2" }
  39454. ],
  39455. "dpi": 240.0,
  39456. "bw": 3,
  39457. "ac": 500
  39458. },
  39459. {
  39460. "type": "ios",
  39461. "rules": [ { "res": [ 640, 960 ] } ],
  39462. "dpi": [ 325.1, 328.4 ],
  39463. "bw": 4,
  39464. "ac": 1000
  39465. },
  39466. {
  39467. "type": "ios",
  39468. "rules": [ { "res": [ 640, 1136 ] } ],
  39469. "dpi": [ 317.1, 320.2 ],
  39470. "bw": 3,
  39471. "ac": 1000
  39472. },
  39473. {
  39474. "type": "ios",
  39475. "rules": [ { "res": [ 750, 1334 ] } ],
  39476. "dpi": 326.4,
  39477. "bw": 4,
  39478. "ac": 1000
  39479. },
  39480. {
  39481. "type": "ios",
  39482. "rules": [ { "res": [ 1242, 2208 ] } ],
  39483. "dpi": [ 453.6, 458.4 ],
  39484. "bw": 4,
  39485. "ac": 1000
  39486. },
  39487. {
  39488. "type": "ios",
  39489. "rules": [ { "res": [ 1125, 2001 ] } ],
  39490. "dpi": [ 410.9, 415.4 ],
  39491. "bw": 4,
  39492. "ac": 1000
  39493. }
  39494. ]};
  39495. module.exports = DPDB_CACHE;
  39496. },{}],12:[function(_dereq_,module,exports){
  39497. module.exports={
  39498. "format":1,
  39499. "last_updated":"2017-01-12T08:41:55Z",
  39500. "devices":[
  39501. {
  39502. "type":"android",
  39503. "rules":[
  39504. {
  39505. "mdmh":"asus/*/Nexus 7/*"
  39506. },
  39507. {
  39508. "ua":"Nexus 7"
  39509. }
  39510. ],
  39511. "dpi":[
  39512. 320.8,
  39513. 323
  39514. ],
  39515. "bw":3,
  39516. "ac":500
  39517. },
  39518. {
  39519. "type":"android",
  39520. "rules":[
  39521. {
  39522. "mdmh":"asus/*/ASUS_Z00AD/*"
  39523. },
  39524. {
  39525. "ua":"ASUS_Z00AD"
  39526. }
  39527. ],
  39528. "dpi":[
  39529. 403,
  39530. 404.6
  39531. ],
  39532. "bw":3,
  39533. "ac":1000
  39534. },
  39535. {
  39536. "type": "android",
  39537. "rules": [
  39538. {
  39539. "mdmh": "Google//Pixel XL/"
  39540. },
  39541. {
  39542. "ua": "Pixel XL"
  39543. }
  39544. ],
  39545. "dpi": [
  39546. 537.9,
  39547. 533
  39548. ],
  39549. "bw": 3,
  39550. "ac": 1000
  39551. },
  39552. {
  39553. "type":"android",
  39554. "rules":[
  39555. {
  39556. "mdmh":"HTC/*/HTC6435LVW/*"
  39557. },
  39558. {
  39559. "ua":"HTC6435LVW"
  39560. }
  39561. ],
  39562. "dpi":[
  39563. 449.7,
  39564. 443.3
  39565. ],
  39566. "bw":3,
  39567. "ac":1000
  39568. },
  39569. {
  39570. "type":"android",
  39571. "rules":[
  39572. {
  39573. "mdmh":"HTC/*/HTC One XL/*"
  39574. },
  39575. {
  39576. "ua":"HTC One XL"
  39577. }
  39578. ],
  39579. "dpi":[
  39580. 315.3,
  39581. 314.6
  39582. ],
  39583. "bw":3,
  39584. "ac":1000
  39585. },
  39586. {
  39587. "type":"android",
  39588. "rules":[
  39589. {
  39590. "mdmh":"htc/*/Nexus 9/*"
  39591. },
  39592. {
  39593. "ua":"Nexus 9"
  39594. }
  39595. ],
  39596. "dpi":289,
  39597. "bw":3,
  39598. "ac":500
  39599. },
  39600. {
  39601. "type":"android",
  39602. "rules":[
  39603. {
  39604. "mdmh":"HTC/*/HTC One M9/*"
  39605. },
  39606. {
  39607. "ua":"HTC One M9"
  39608. }
  39609. ],
  39610. "dpi":[
  39611. 442.5,
  39612. 443.3
  39613. ],
  39614. "bw":3,
  39615. "ac":500
  39616. },
  39617. {
  39618. "type":"android",
  39619. "rules":[
  39620. {
  39621. "mdmh":"HTC/*/HTC One_M8/*"
  39622. },
  39623. {
  39624. "ua":"HTC One_M8"
  39625. }
  39626. ],
  39627. "dpi":[
  39628. 449.7,
  39629. 447.4
  39630. ],
  39631. "bw":3,
  39632. "ac":500
  39633. },
  39634. {
  39635. "type":"android",
  39636. "rules":[
  39637. {
  39638. "mdmh":"HTC/*/HTC One/*"
  39639. },
  39640. {
  39641. "ua":"HTC One"
  39642. }
  39643. ],
  39644. "dpi":472.8,
  39645. "bw":3,
  39646. "ac":1000
  39647. },
  39648. {
  39649. "type":"android",
  39650. "rules":[
  39651. {
  39652. "mdmh":"Huawei/*/Nexus 6P/*"
  39653. },
  39654. {
  39655. "ua":"Nexus 6P"
  39656. }
  39657. ],
  39658. "dpi":[
  39659. 515.1,
  39660. 518
  39661. ],
  39662. "bw":3,
  39663. "ac":1000
  39664. },
  39665. {
  39666. "type":"android",
  39667. "rules":[
  39668. {
  39669. "mdmh":"LGE/*/Nexus 5X/*"
  39670. },
  39671. {
  39672. "ua":"Nexus 5X"
  39673. }
  39674. ],
  39675. "dpi":[
  39676. 422,
  39677. 419.9
  39678. ],
  39679. "bw":3,
  39680. "ac":1000
  39681. },
  39682. {
  39683. "type":"android",
  39684. "rules":[
  39685. {
  39686. "mdmh":"LGE/*/LGMS345/*"
  39687. },
  39688. {
  39689. "ua":"LGMS345"
  39690. }
  39691. ],
  39692. "dpi":[
  39693. 221.7,
  39694. 219.1
  39695. ],
  39696. "bw":3,
  39697. "ac":500
  39698. },
  39699. {
  39700. "type":"android",
  39701. "rules":[
  39702. {
  39703. "mdmh":"LGE/*/LG-D800/*"
  39704. },
  39705. {
  39706. "ua":"LG-D800"
  39707. }
  39708. ],
  39709. "dpi":[
  39710. 422,
  39711. 424.1
  39712. ],
  39713. "bw":3,
  39714. "ac":500
  39715. },
  39716. {
  39717. "type":"android",
  39718. "rules":[
  39719. {
  39720. "mdmh":"LGE/*/LG-D850/*"
  39721. },
  39722. {
  39723. "ua":"LG-D850"
  39724. }
  39725. ],
  39726. "dpi":[
  39727. 537.9,
  39728. 541.9
  39729. ],
  39730. "bw":3,
  39731. "ac":500
  39732. },
  39733. {
  39734. "type":"android",
  39735. "rules":[
  39736. {
  39737. "mdmh":"LGE/*/VS985 4G/*"
  39738. },
  39739. {
  39740. "ua":"VS985 4G"
  39741. }
  39742. ],
  39743. "dpi":[
  39744. 537.9,
  39745. 535.6
  39746. ],
  39747. "bw":3,
  39748. "ac":1000
  39749. },
  39750. {
  39751. "type":"android",
  39752. "rules":[
  39753. {
  39754. "mdmh":"LGE/*/Nexus 5/*"
  39755. },
  39756. {
  39757. "ua":"Nexus 5 B"
  39758. }
  39759. ],
  39760. "dpi":[
  39761. 442.4,
  39762. 444.8
  39763. ],
  39764. "bw":3,
  39765. "ac":1000
  39766. },
  39767. {
  39768. "type":"android",
  39769. "rules":[
  39770. {
  39771. "mdmh":"LGE/*/Nexus 4/*"
  39772. },
  39773. {
  39774. "ua":"Nexus 4"
  39775. }
  39776. ],
  39777. "dpi":[
  39778. 319.8,
  39779. 318.4
  39780. ],
  39781. "bw":3,
  39782. "ac":1000
  39783. },
  39784. {
  39785. "type":"android",
  39786. "rules":[
  39787. {
  39788. "mdmh":"LGE/*/LG-P769/*"
  39789. },
  39790. {
  39791. "ua":"LG-P769"
  39792. }
  39793. ],
  39794. "dpi":[
  39795. 240.6,
  39796. 247.5
  39797. ],
  39798. "bw":3,
  39799. "ac":1000
  39800. },
  39801. {
  39802. "type":"android",
  39803. "rules":[
  39804. {
  39805. "mdmh":"LGE/*/LGMS323/*"
  39806. },
  39807. {
  39808. "ua":"LGMS323"
  39809. }
  39810. ],
  39811. "dpi":[
  39812. 206.6,
  39813. 204.6
  39814. ],
  39815. "bw":3,
  39816. "ac":1000
  39817. },
  39818. {
  39819. "type":"android",
  39820. "rules":[
  39821. {
  39822. "mdmh":"LGE/*/LGLS996/*"
  39823. },
  39824. {
  39825. "ua":"LGLS996"
  39826. }
  39827. ],
  39828. "dpi":[
  39829. 403.4,
  39830. 401.5
  39831. ],
  39832. "bw":3,
  39833. "ac":1000
  39834. },
  39835. {
  39836. "type":"android",
  39837. "rules":[
  39838. {
  39839. "mdmh":"Micromax/*/4560MMX/*"
  39840. },
  39841. {
  39842. "ua":"4560MMX"
  39843. }
  39844. ],
  39845. "dpi":[
  39846. 240,
  39847. 219.4
  39848. ],
  39849. "bw":3,
  39850. "ac":1000
  39851. },
  39852. {
  39853. "type":"android",
  39854. "rules":[
  39855. {
  39856. "mdmh":"Micromax/*/A250/*"
  39857. },
  39858. {
  39859. "ua":"Micromax A250"
  39860. }
  39861. ],
  39862. "dpi":[
  39863. 480,
  39864. 446.4
  39865. ],
  39866. "bw":3,
  39867. "ac":1000
  39868. },
  39869. {
  39870. "type":"android",
  39871. "rules":[
  39872. {
  39873. "mdmh":"Micromax/*/Micromax AQ4501/*"
  39874. },
  39875. {
  39876. "ua":"Micromax AQ4501"
  39877. }
  39878. ],
  39879. "dpi":240,
  39880. "bw":3,
  39881. "ac":500
  39882. },
  39883. {
  39884. "type":"android",
  39885. "rules":[
  39886. {
  39887. "mdmh":"motorola/*/DROID RAZR/*"
  39888. },
  39889. {
  39890. "ua":"DROID RAZR"
  39891. }
  39892. ],
  39893. "dpi":[
  39894. 368.1,
  39895. 256.7
  39896. ],
  39897. "bw":3,
  39898. "ac":1000
  39899. },
  39900. {
  39901. "type":"android",
  39902. "rules":[
  39903. {
  39904. "mdmh":"motorola/*/XT830C/*"
  39905. },
  39906. {
  39907. "ua":"XT830C"
  39908. }
  39909. ],
  39910. "dpi":[
  39911. 254,
  39912. 255.9
  39913. ],
  39914. "bw":3,
  39915. "ac":1000
  39916. },
  39917. {
  39918. "type":"android",
  39919. "rules":[
  39920. {
  39921. "mdmh":"motorola/*/XT1021/*"
  39922. },
  39923. {
  39924. "ua":"XT1021"
  39925. }
  39926. ],
  39927. "dpi":[
  39928. 254,
  39929. 256.7
  39930. ],
  39931. "bw":3,
  39932. "ac":500
  39933. },
  39934. {
  39935. "type":"android",
  39936. "rules":[
  39937. {
  39938. "mdmh":"motorola/*/XT1023/*"
  39939. },
  39940. {
  39941. "ua":"XT1023"
  39942. }
  39943. ],
  39944. "dpi":[
  39945. 254,
  39946. 256.7
  39947. ],
  39948. "bw":3,
  39949. "ac":500
  39950. },
  39951. {
  39952. "type":"android",
  39953. "rules":[
  39954. {
  39955. "mdmh":"motorola/*/XT1028/*"
  39956. },
  39957. {
  39958. "ua":"XT1028"
  39959. }
  39960. ],
  39961. "dpi":[
  39962. 326.6,
  39963. 327.6
  39964. ],
  39965. "bw":3,
  39966. "ac":1000
  39967. },
  39968. {
  39969. "type":"android",
  39970. "rules":[
  39971. {
  39972. "mdmh":"motorola/*/XT1034/*"
  39973. },
  39974. {
  39975. "ua":"XT1034"
  39976. }
  39977. ],
  39978. "dpi":[
  39979. 326.6,
  39980. 328.4
  39981. ],
  39982. "bw":3,
  39983. "ac":500
  39984. },
  39985. {
  39986. "type":"android",
  39987. "rules":[
  39988. {
  39989. "mdmh":"motorola/*/XT1053/*"
  39990. },
  39991. {
  39992. "ua":"XT1053"
  39993. }
  39994. ],
  39995. "dpi":[
  39996. 315.3,
  39997. 316.1
  39998. ],
  39999. "bw":3,
  40000. "ac":1000
  40001. },
  40002. {
  40003. "type":"android",
  40004. "rules":[
  40005. {
  40006. "mdmh":"motorola/*/XT1562/*"
  40007. },
  40008. {
  40009. "ua":"XT1562"
  40010. }
  40011. ],
  40012. "dpi":[
  40013. 403.4,
  40014. 402.7
  40015. ],
  40016. "bw":3,
  40017. "ac":1000
  40018. },
  40019. {
  40020. "type":"android",
  40021. "rules":[
  40022. {
  40023. "mdmh":"motorola/*/Nexus 6/*"
  40024. },
  40025. {
  40026. "ua":"Nexus 6 B"
  40027. }
  40028. ],
  40029. "dpi":[
  40030. 494.3,
  40031. 489.7
  40032. ],
  40033. "bw":3,
  40034. "ac":1000
  40035. },
  40036. {
  40037. "type":"android",
  40038. "rules":[
  40039. {
  40040. "mdmh":"motorola/*/XT1063/*"
  40041. },
  40042. {
  40043. "ua":"XT1063"
  40044. }
  40045. ],
  40046. "dpi":[
  40047. 295,
  40048. 296.6
  40049. ],
  40050. "bw":3,
  40051. "ac":1000
  40052. },
  40053. {
  40054. "type":"android",
  40055. "rules":[
  40056. {
  40057. "mdmh":"motorola/*/XT1064/*"
  40058. },
  40059. {
  40060. "ua":"XT1064"
  40061. }
  40062. ],
  40063. "dpi":[
  40064. 295,
  40065. 295.6
  40066. ],
  40067. "bw":3,
  40068. "ac":500
  40069. },
  40070. {
  40071. "type":"android",
  40072. "rules":[
  40073. {
  40074. "mdmh":"motorola/*/XT1092/*"
  40075. },
  40076. {
  40077. "ua":"XT1092"
  40078. }
  40079. ],
  40080. "dpi":[
  40081. 422,
  40082. 424.1
  40083. ],
  40084. "bw":3,
  40085. "ac":500
  40086. },
  40087. {
  40088. "type":"android",
  40089. "rules":[
  40090. {
  40091. "mdmh":"motorola/*/XT1095/*"
  40092. },
  40093. {
  40094. "ua":"XT1095"
  40095. }
  40096. ],
  40097. "dpi":[
  40098. 422,
  40099. 423.4
  40100. ],
  40101. "bw":3,
  40102. "ac":1000
  40103. },
  40104. {
  40105. "type": "android",
  40106. "rules": [
  40107. {
  40108. "mdmh": "motorola/*/G4/*"
  40109. },
  40110. {
  40111. "ua": "Moto G (4)"
  40112. }
  40113. ],
  40114. "dpi": 401.0,
  40115. "bw": 4,
  40116. "ac": 1000
  40117. },
  40118. {
  40119. "type":"android",
  40120. "rules":[
  40121. {
  40122. "mdmh":"OnePlus/*/A0001/*"
  40123. },
  40124. {
  40125. "ua":"A0001"
  40126. }
  40127. ],
  40128. "dpi":[
  40129. 403.4,
  40130. 401
  40131. ],
  40132. "bw":3,
  40133. "ac":1000
  40134. },
  40135. {
  40136. "type":"android",
  40137. "rules":[
  40138. {
  40139. "mdmh":"OnePlus/*/ONE E1005/*"
  40140. },
  40141. {
  40142. "ua":"ONE E1005"
  40143. }
  40144. ],
  40145. "dpi":[
  40146. 442.4,
  40147. 441.4
  40148. ],
  40149. "bw":3,
  40150. "ac":1000
  40151. },
  40152. {
  40153. "type":"android",
  40154. "rules":[
  40155. {
  40156. "mdmh":"OnePlus/*/ONE A2005/*"
  40157. },
  40158. {
  40159. "ua":"ONE A2005"
  40160. }
  40161. ],
  40162. "dpi":[
  40163. 391.9,
  40164. 405.4
  40165. ],
  40166. "bw":3,
  40167. "ac":1000
  40168. },
  40169. {
  40170. "type":"android",
  40171. "rules":[
  40172. {
  40173. "mdmh":"OPPO/*/X909/*"
  40174. },
  40175. {
  40176. "ua":"X909"
  40177. }
  40178. ],
  40179. "dpi":[
  40180. 442.4,
  40181. 444.1
  40182. ],
  40183. "bw":3,
  40184. "ac":1000
  40185. },
  40186. {
  40187. "type":"android",
  40188. "rules":[
  40189. {
  40190. "mdmh":"samsung/*/GT-I9082/*"
  40191. },
  40192. {
  40193. "ua":"GT-I9082"
  40194. }
  40195. ],
  40196. "dpi":[
  40197. 184.7,
  40198. 185.4
  40199. ],
  40200. "bw":3,
  40201. "ac":1000
  40202. },
  40203. {
  40204. "type":"android",
  40205. "rules":[
  40206. {
  40207. "mdmh":"samsung/*/SM-G360P/*"
  40208. },
  40209. {
  40210. "ua":"SM-G360P"
  40211. }
  40212. ],
  40213. "dpi":[
  40214. 196.7,
  40215. 205.4
  40216. ],
  40217. "bw":3,
  40218. "ac":1000
  40219. },
  40220. {
  40221. "type":"android",
  40222. "rules":[
  40223. {
  40224. "mdmh":"samsung/*/Nexus S/*"
  40225. },
  40226. {
  40227. "ua":"Nexus S"
  40228. }
  40229. ],
  40230. "dpi":[
  40231. 234.5,
  40232. 229.8
  40233. ],
  40234. "bw":3,
  40235. "ac":1000
  40236. },
  40237. {
  40238. "type":"android",
  40239. "rules":[
  40240. {
  40241. "mdmh":"samsung/*/GT-I9300/*"
  40242. },
  40243. {
  40244. "ua":"GT-I9300"
  40245. }
  40246. ],
  40247. "dpi":[
  40248. 304.8,
  40249. 303.9
  40250. ],
  40251. "bw":5,
  40252. "ac":500
  40253. },
  40254. {
  40255. "type":"android",
  40256. "rules":[
  40257. {
  40258. "mdmh":"samsung/*/SM-T230NU/*"
  40259. },
  40260. {
  40261. "ua":"SM-T230NU"
  40262. }
  40263. ],
  40264. "dpi":216,
  40265. "bw":3,
  40266. "ac":500
  40267. },
  40268. {
  40269. "type":"android",
  40270. "rules":[
  40271. {
  40272. "mdmh":"samsung/*/SGH-T399/*"
  40273. },
  40274. {
  40275. "ua":"SGH-T399"
  40276. }
  40277. ],
  40278. "dpi":[
  40279. 217.7,
  40280. 231.4
  40281. ],
  40282. "bw":3,
  40283. "ac":1000
  40284. },
  40285. {
  40286. "type":"android",
  40287. "rules":[
  40288. {
  40289. "mdmh":"samsung/*/SM-N9005/*"
  40290. },
  40291. {
  40292. "ua":"SM-N9005"
  40293. }
  40294. ],
  40295. "dpi":[
  40296. 386.4,
  40297. 387
  40298. ],
  40299. "bw":3,
  40300. "ac":500
  40301. },
  40302. {
  40303. "type":"android",
  40304. "rules":[
  40305. {
  40306. "mdmh":"samsung/*/SAMSUNG-SM-N900A/*"
  40307. },
  40308. {
  40309. "ua":"SAMSUNG-SM-N900A"
  40310. }
  40311. ],
  40312. "dpi":[
  40313. 386.4,
  40314. 387.7
  40315. ],
  40316. "bw":3,
  40317. "ac":1000
  40318. },
  40319. {
  40320. "type":"android",
  40321. "rules":[
  40322. {
  40323. "mdmh":"samsung/*/GT-I9500/*"
  40324. },
  40325. {
  40326. "ua":"GT-I9500"
  40327. }
  40328. ],
  40329. "dpi":[
  40330. 442.5,
  40331. 443.3
  40332. ],
  40333. "bw":3,
  40334. "ac":500
  40335. },
  40336. {
  40337. "type":"android",
  40338. "rules":[
  40339. {
  40340. "mdmh":"samsung/*/GT-I9505/*"
  40341. },
  40342. {
  40343. "ua":"GT-I9505"
  40344. }
  40345. ],
  40346. "dpi":439.4,
  40347. "bw":4,
  40348. "ac":1000
  40349. },
  40350. {
  40351. "type":"android",
  40352. "rules":[
  40353. {
  40354. "mdmh":"samsung/*/SM-G900F/*"
  40355. },
  40356. {
  40357. "ua":"SM-G900F"
  40358. }
  40359. ],
  40360. "dpi":[
  40361. 415.6,
  40362. 431.6
  40363. ],
  40364. "bw":5,
  40365. "ac":1000
  40366. },
  40367. {
  40368. "type":"android",
  40369. "rules":[
  40370. {
  40371. "mdmh":"samsung/*/SM-G900M/*"
  40372. },
  40373. {
  40374. "ua":"SM-G900M"
  40375. }
  40376. ],
  40377. "dpi":[
  40378. 415.6,
  40379. 431.6
  40380. ],
  40381. "bw":5,
  40382. "ac":1000
  40383. },
  40384. {
  40385. "type":"android",
  40386. "rules":[
  40387. {
  40388. "mdmh":"samsung/*/SM-G800F/*"
  40389. },
  40390. {
  40391. "ua":"SM-G800F"
  40392. }
  40393. ],
  40394. "dpi":326.8,
  40395. "bw":3,
  40396. "ac":1000
  40397. },
  40398. {
  40399. "type":"android",
  40400. "rules":[
  40401. {
  40402. "mdmh":"samsung/*/SM-G906S/*"
  40403. },
  40404. {
  40405. "ua":"SM-G906S"
  40406. }
  40407. ],
  40408. "dpi":[
  40409. 562.7,
  40410. 572.4
  40411. ],
  40412. "bw":3,
  40413. "ac":1000
  40414. },
  40415. {
  40416. "type":"android",
  40417. "rules":[
  40418. {
  40419. "mdmh":"samsung/*/GT-I9300/*"
  40420. },
  40421. {
  40422. "ua":"GT-I9300"
  40423. }
  40424. ],
  40425. "dpi":[
  40426. 306.7,
  40427. 304.8
  40428. ],
  40429. "bw":5,
  40430. "ac":1000
  40431. },
  40432. {
  40433. "type":"android",
  40434. "rules":[
  40435. {
  40436. "mdmh":"samsung/*/SM-T535/*"
  40437. },
  40438. {
  40439. "ua":"SM-T535"
  40440. }
  40441. ],
  40442. "dpi":[
  40443. 142.6,
  40444. 136.4
  40445. ],
  40446. "bw":3,
  40447. "ac":500
  40448. },
  40449. {
  40450. "type":"android",
  40451. "rules":[
  40452. {
  40453. "mdmh":"samsung/*/SM-N920C/*"
  40454. },
  40455. {
  40456. "ua":"SM-N920C"
  40457. }
  40458. ],
  40459. "dpi":[
  40460. 515.1,
  40461. 518.4
  40462. ],
  40463. "bw":3,
  40464. "ac":1000
  40465. },
  40466. {
  40467. "type": "android",
  40468. "rules": [
  40469. {
  40470. "mdmh": "samsung/*/SM-N920W8/*"
  40471. },
  40472. {
  40473. "ua": "SM-N920W8"
  40474. }
  40475. ],
  40476. "dpi": [
  40477. 515.1,
  40478. 518.4
  40479. ],
  40480. "bw": 3,
  40481. "ac": 1000
  40482. },
  40483. {
  40484. "type":"android",
  40485. "rules":[
  40486. {
  40487. "mdmh":"samsung/*/GT-I9300I/*"
  40488. },
  40489. {
  40490. "ua":"GT-I9300I"
  40491. }
  40492. ],
  40493. "dpi":[
  40494. 304.8,
  40495. 305.8
  40496. ],
  40497. "bw":3,
  40498. "ac":1000
  40499. },
  40500. {
  40501. "type":"android",
  40502. "rules":[
  40503. {
  40504. "mdmh":"samsung/*/GT-I9195/*"
  40505. },
  40506. {
  40507. "ua":"GT-I9195"
  40508. }
  40509. ],
  40510. "dpi":[
  40511. 249.4,
  40512. 256.7
  40513. ],
  40514. "bw":3,
  40515. "ac":500
  40516. },
  40517. {
  40518. "type":"android",
  40519. "rules":[
  40520. {
  40521. "mdmh":"samsung/*/SPH-L520/*"
  40522. },
  40523. {
  40524. "ua":"SPH-L520"
  40525. }
  40526. ],
  40527. "dpi":[
  40528. 249.4,
  40529. 255.9
  40530. ],
  40531. "bw":3,
  40532. "ac":1000
  40533. },
  40534. {
  40535. "type":"android",
  40536. "rules":[
  40537. {
  40538. "mdmh":"samsung/*/SAMSUNG-SGH-I717/*"
  40539. },
  40540. {
  40541. "ua":"SAMSUNG-SGH-I717"
  40542. }
  40543. ],
  40544. "dpi":285.8,
  40545. "bw":3,
  40546. "ac":1000
  40547. },
  40548. {
  40549. "type":"android",
  40550. "rules":[
  40551. {
  40552. "mdmh":"samsung/*/SPH-D710/*"
  40553. },
  40554. {
  40555. "ua":"SPH-D710"
  40556. }
  40557. ],
  40558. "dpi":[
  40559. 217.7,
  40560. 204.2
  40561. ],
  40562. "bw":3,
  40563. "ac":1000
  40564. },
  40565. {
  40566. "type":"android",
  40567. "rules":[
  40568. {
  40569. "mdmh":"samsung/*/GT-N7100/*"
  40570. },
  40571. {
  40572. "ua":"GT-N7100"
  40573. }
  40574. ],
  40575. "dpi":265.1,
  40576. "bw":3,
  40577. "ac":1000
  40578. },
  40579. {
  40580. "type":"android",
  40581. "rules":[
  40582. {
  40583. "mdmh":"samsung/*/SCH-I605/*"
  40584. },
  40585. {
  40586. "ua":"SCH-I605"
  40587. }
  40588. ],
  40589. "dpi":265.1,
  40590. "bw":3,
  40591. "ac":1000
  40592. },
  40593. {
  40594. "type":"android",
  40595. "rules":[
  40596. {
  40597. "mdmh":"samsung/*/Galaxy Nexus/*"
  40598. },
  40599. {
  40600. "ua":"Galaxy Nexus"
  40601. }
  40602. ],
  40603. "dpi":[
  40604. 315.3,
  40605. 314.2
  40606. ],
  40607. "bw":3,
  40608. "ac":1000
  40609. },
  40610. {
  40611. "type":"android",
  40612. "rules":[
  40613. {
  40614. "mdmh":"samsung/*/SM-N910H/*"
  40615. },
  40616. {
  40617. "ua":"SM-N910H"
  40618. }
  40619. ],
  40620. "dpi":[
  40621. 515.1,
  40622. 518
  40623. ],
  40624. "bw":3,
  40625. "ac":1000
  40626. },
  40627. {
  40628. "type":"android",
  40629. "rules":[
  40630. {
  40631. "mdmh":"samsung/*/SM-N910C/*"
  40632. },
  40633. {
  40634. "ua":"SM-N910C"
  40635. }
  40636. ],
  40637. "dpi":[
  40638. 515.2,
  40639. 520.2
  40640. ],
  40641. "bw":3,
  40642. "ac":500
  40643. },
  40644. {
  40645. "type":"android",
  40646. "rules":[
  40647. {
  40648. "mdmh":"samsung/*/SM-G130M/*"
  40649. },
  40650. {
  40651. "ua":"SM-G130M"
  40652. }
  40653. ],
  40654. "dpi":[
  40655. 165.9,
  40656. 164.8
  40657. ],
  40658. "bw":3,
  40659. "ac":500
  40660. },
  40661. {
  40662. "type":"android",
  40663. "rules":[
  40664. {
  40665. "mdmh":"samsung/*/SM-G928I/*"
  40666. },
  40667. {
  40668. "ua":"SM-G928I"
  40669. }
  40670. ],
  40671. "dpi":[
  40672. 515.1,
  40673. 518.4
  40674. ],
  40675. "bw":3,
  40676. "ac":1000
  40677. },
  40678. {
  40679. "type":"android",
  40680. "rules":[
  40681. {
  40682. "mdmh":"samsung/*/SM-G920F/*"
  40683. },
  40684. {
  40685. "ua":"SM-G920F"
  40686. }
  40687. ],
  40688. "dpi":580.6,
  40689. "bw":3,
  40690. "ac":500
  40691. },
  40692. {
  40693. "type":"android",
  40694. "rules":[
  40695. {
  40696. "mdmh":"samsung/*/SM-G920P/*"
  40697. },
  40698. {
  40699. "ua":"SM-G920P"
  40700. }
  40701. ],
  40702. "dpi":[
  40703. 522.5,
  40704. 577
  40705. ],
  40706. "bw":3,
  40707. "ac":1000
  40708. },
  40709. {
  40710. "type":"android",
  40711. "rules":[
  40712. {
  40713. "mdmh":"samsung/*/SM-G925F/*"
  40714. },
  40715. {
  40716. "ua":"SM-G925F"
  40717. }
  40718. ],
  40719. "dpi":580.6,
  40720. "bw":3,
  40721. "ac":500
  40722. },
  40723. {
  40724. "type":"android",
  40725. "rules":[
  40726. {
  40727. "mdmh":"samsung/*/SM-G925V/*"
  40728. },
  40729. {
  40730. "ua":"SM-G925V"
  40731. }
  40732. ],
  40733. "dpi":[
  40734. 522.5,
  40735. 576.6
  40736. ],
  40737. "bw":3,
  40738. "ac":1000
  40739. },
  40740. {
  40741. "type": "android",
  40742. "rules": [
  40743. {
  40744. "mdmh": "samsung/*/SM-G930F/*"
  40745. },
  40746. {
  40747. "ua": "SM-G930F"
  40748. }
  40749. ],
  40750. "dpi": 576.6,
  40751. "bw": 3,
  40752. "ac": 1000
  40753. },
  40754. {
  40755. "type":"android",
  40756. "rules":[
  40757. {
  40758. "mdmh":"samsung/*/SM-G935F/*"
  40759. },
  40760. {
  40761. "ua":"SM-G935F"
  40762. }
  40763. ],
  40764. "dpi":533,
  40765. "bw":3,
  40766. "ac":500
  40767. },
  40768. {
  40769. "type":"android",
  40770. "rules":[
  40771. {
  40772. "mdmh":"Sony/*/C6903/*"
  40773. },
  40774. {
  40775. "ua":"C6903"
  40776. }
  40777. ],
  40778. "dpi":[
  40779. 442.5,
  40780. 443.3
  40781. ],
  40782. "bw":3,
  40783. "ac":500
  40784. },
  40785. {
  40786. "type":"android",
  40787. "rules":[
  40788. {
  40789. "mdmh":"Sony/*/D6653/*"
  40790. },
  40791. {
  40792. "ua":"D6653"
  40793. }
  40794. ],
  40795. "dpi":[
  40796. 428.6,
  40797. 427.6
  40798. ],
  40799. "bw":3,
  40800. "ac":1000
  40801. },
  40802. {
  40803. "type":"android",
  40804. "rules":[
  40805. {
  40806. "mdmh":"Sony/*/E6653/*"
  40807. },
  40808. {
  40809. "ua":"E6653"
  40810. }
  40811. ],
  40812. "dpi":[
  40813. 428.6,
  40814. 425.7
  40815. ],
  40816. "bw":3,
  40817. "ac":1000
  40818. },
  40819. {
  40820. "type":"android",
  40821. "rules":[
  40822. {
  40823. "mdmh":"Sony/*/E6853/*"
  40824. },
  40825. {
  40826. "ua":"E6853"
  40827. }
  40828. ],
  40829. "dpi":[
  40830. 403.4,
  40831. 401.9
  40832. ],
  40833. "bw":3,
  40834. "ac":1000
  40835. },
  40836. {
  40837. "type":"android",
  40838. "rules":[
  40839. {
  40840. "mdmh":"Sony/*/SGP321/*"
  40841. },
  40842. {
  40843. "ua":"SGP321"
  40844. }
  40845. ],
  40846. "dpi":[
  40847. 224.7,
  40848. 224.1
  40849. ],
  40850. "bw":3,
  40851. "ac":500
  40852. },
  40853. {
  40854. "type":"android",
  40855. "rules":[
  40856. {
  40857. "mdmh":"TCT/*/ALCATEL ONE TOUCH Fierce/*"
  40858. },
  40859. {
  40860. "ua":"ALCATEL ONE TOUCH Fierce"
  40861. }
  40862. ],
  40863. "dpi":[
  40864. 240,
  40865. 247.5
  40866. ],
  40867. "bw":3,
  40868. "ac":1000
  40869. },
  40870. {
  40871. "type":"android",
  40872. "rules":[
  40873. {
  40874. "mdmh":"THL/*/thl 5000/*"
  40875. },
  40876. {
  40877. "ua":"thl 5000"
  40878. }
  40879. ],
  40880. "dpi":[
  40881. 480,
  40882. 443.3
  40883. ],
  40884. "bw":3,
  40885. "ac":1000
  40886. },
  40887. {
  40888. "type":"android",
  40889. "rules":[
  40890. {
  40891. "mdmh":"ZTE/*/ZTE Blade L2/*"
  40892. },
  40893. {
  40894. "ua":"ZTE Blade L2"
  40895. }
  40896. ],
  40897. "dpi":240,
  40898. "bw":3,
  40899. "ac":500
  40900. },
  40901. {
  40902. "type":"ios",
  40903. "rules":[
  40904. {
  40905. "res":[
  40906. 640,
  40907. 960
  40908. ]
  40909. }
  40910. ],
  40911. "dpi":[
  40912. 325.1,
  40913. 328.4
  40914. ],
  40915. "bw":4,
  40916. "ac":1000
  40917. },
  40918. {
  40919. "type":"ios",
  40920. "rules":[
  40921. {
  40922. "res":[
  40923. 640,
  40924. 1136
  40925. ]
  40926. }
  40927. ],
  40928. "dpi":[
  40929. 317.1,
  40930. 320.2
  40931. ],
  40932. "bw":3,
  40933. "ac":1000
  40934. },
  40935. {
  40936. "type":"ios",
  40937. "rules":[
  40938. {
  40939. "res":[
  40940. 750,
  40941. 1334
  40942. ]
  40943. }
  40944. ],
  40945. "dpi":326.4,
  40946. "bw":4,
  40947. "ac":1000
  40948. },
  40949. {
  40950. "type":"ios",
  40951. "rules":[
  40952. {
  40953. "res":[
  40954. 1242,
  40955. 2208
  40956. ]
  40957. }
  40958. ],
  40959. "dpi":[
  40960. 453.6,
  40961. 458.4
  40962. ],
  40963. "bw":4,
  40964. "ac":1000
  40965. },
  40966. {
  40967. "type":"ios",
  40968. "rules":[
  40969. {
  40970. "res":[
  40971. 1125,
  40972. 2001
  40973. ]
  40974. }
  40975. ],
  40976. "dpi":[
  40977. 410.9,
  40978. 415.4
  40979. ],
  40980. "bw":4,
  40981. "ac":1000
  40982. }
  40983. ]
  40984. }
  40985. },{}],13:[function(_dereq_,module,exports){
  40986. /*
  40987. * Copyright 2015 Google Inc. All Rights Reserved.
  40988. * Licensed under the Apache License, Version 2.0 (the "License");
  40989. * you may not use this file except in compliance with the License.
  40990. * You may obtain a copy of the License at
  40991. *
  40992. * http://www.apache.org/licenses/LICENSE-2.0
  40993. *
  40994. * Unless required by applicable law or agreed to in writing, software
  40995. * distributed under the License is distributed on an "AS IS" BASIS,
  40996. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  40997. * See the License for the specific language governing permissions and
  40998. * limitations under the License.
  40999. */
  41000. // Offline cache of the DPDB, to be used until we load the online one (and
  41001. // as a fallback in case we can't load the online one).
  41002. var DPDB_CACHE = _dereq_('./dpdb-cache.js');
  41003. var Util = _dereq_('../util.js');
  41004. // Online DPDB URL.
  41005. var ONLINE_DPDB_URL = _dereq_('./dpdb.json');
  41006. /**
  41007. * Calculates device parameters based on the DPDB (Device Parameter Database).
  41008. * Initially, uses the cached DPDB values.
  41009. *
  41010. * If fetchOnline == true, then this object tries to fetch the online version
  41011. * of the DPDB and updates the device info if a better match is found.
  41012. * Calls the onDeviceParamsUpdated callback when there is an update to the
  41013. * device information.
  41014. */
  41015. function Dpdb(fetchOnline, onDeviceParamsUpdated) {
  41016. // Start with the offline DPDB cache while we are loading the real one.
  41017. this.dpdb = DPDB_CACHE;
  41018. // Calculate device params based on the offline version of the DPDB.
  41019. this.recalculateDeviceParams_();
  41020. // XHR to fetch online DPDB file, if requested.
  41021. if (fetchOnline) {
  41022. // Set the callback.
  41023. this.onDeviceParamsUpdated = onDeviceParamsUpdated;
  41024. var xhr = new XMLHttpRequest();
  41025. var obj = this;
  41026. xhr.open('GET', ONLINE_DPDB_URL, true);
  41027. xhr.addEventListener('load', function() {
  41028. obj.loading = false;
  41029. if (xhr.status >= 200 && xhr.status <= 299) {
  41030. // Success.
  41031. obj.dpdb = JSON.parse(xhr.response);
  41032. obj.recalculateDeviceParams_();
  41033. } else {
  41034. // Error loading the DPDB.
  41035. console.error('Error loading online DPDB!');
  41036. }
  41037. });
  41038. xhr.send();
  41039. }
  41040. }
  41041. // Returns the current device parameters.
  41042. Dpdb.prototype.getDeviceParams = function() {
  41043. return this.deviceParams;
  41044. };
  41045. // Recalculates this device's parameters based on the DPDB.
  41046. Dpdb.prototype.recalculateDeviceParams_ = function() {
  41047. var newDeviceParams = this.calcDeviceParams_();
  41048. if (newDeviceParams) {
  41049. this.deviceParams = newDeviceParams;
  41050. // Invoke callback, if it is set.
  41051. if (this.onDeviceParamsUpdated) {
  41052. this.onDeviceParamsUpdated(this.deviceParams);
  41053. }
  41054. } else {
  41055. console.error('Failed to recalculate device parameters.');
  41056. }
  41057. };
  41058. // Returns a DeviceParams object that represents the best guess as to this
  41059. // device's parameters. Can return null if the device does not match any
  41060. // known devices.
  41061. Dpdb.prototype.calcDeviceParams_ = function() {
  41062. var db = this.dpdb; // shorthand
  41063. if (!db) {
  41064. console.error('DPDB not available.');
  41065. return null;
  41066. }
  41067. if (db.format != 1) {
  41068. console.error('DPDB has unexpected format version.');
  41069. return null;
  41070. }
  41071. if (!db.devices || !db.devices.length) {
  41072. console.error('DPDB does not have a devices section.');
  41073. return null;
  41074. }
  41075. // Get the actual user agent and screen dimensions in pixels.
  41076. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  41077. var width = Util.getScreenWidth();
  41078. var height = Util.getScreenHeight();
  41079. if (!db.devices) {
  41080. console.error('DPDB has no devices section.');
  41081. return null;
  41082. }
  41083. for (var i = 0; i < db.devices.length; i++) {
  41084. var device = db.devices[i];
  41085. if (!device.rules) {
  41086. console.warn('Device[' + i + '] has no rules section.');
  41087. continue;
  41088. }
  41089. if (device.type != 'ios' && device.type != 'android') {
  41090. console.warn('Device[' + i + '] has invalid type.');
  41091. continue;
  41092. }
  41093. // See if this device is of the appropriate type.
  41094. if (Util.isIOS() != (device.type == 'ios')) continue;
  41095. // See if this device matches any of the rules:
  41096. var matched = false;
  41097. for (var j = 0; j < device.rules.length; j++) {
  41098. var rule = device.rules[j];
  41099. if (this.matchRule_(rule, userAgent, width, height)) {
  41100. matched = true;
  41101. break;
  41102. }
  41103. }
  41104. if (!matched) continue;
  41105. // device.dpi might be an array of [ xdpi, ydpi] or just a scalar.
  41106. var xdpi = device.dpi[0] || device.dpi;
  41107. var ydpi = device.dpi[1] || device.dpi;
  41108. return new DeviceParams({ xdpi: xdpi, ydpi: ydpi, bevelMm: device.bw });
  41109. }
  41110. console.warn('No DPDB device match.');
  41111. return null;
  41112. };
  41113. Dpdb.prototype.matchRule_ = function(rule, ua, screenWidth, screenHeight) {
  41114. // We can only match 'ua' and 'res' rules, not other types like 'mdmh'
  41115. // (which are meant for native platforms).
  41116. if (!rule.ua && !rule.res) return false;
  41117. // If our user agent string doesn't contain the indicated user agent string,
  41118. // the match fails.
  41119. if (rule.ua && ua.indexOf(rule.ua) < 0) return false;
  41120. // If the rule specifies screen dimensions that don't correspond to ours,
  41121. // the match fails.
  41122. if (rule.res) {
  41123. if (!rule.res[0] || !rule.res[1]) return false;
  41124. var resX = rule.res[0];
  41125. var resY = rule.res[1];
  41126. // Compare min and max so as to make the order not matter, i.e., it should
  41127. // be true that 640x480 == 480x640.
  41128. if (Math.min(screenWidth, screenHeight) != Math.min(resX, resY) ||
  41129. (Math.max(screenWidth, screenHeight) != Math.max(resX, resY))) {
  41130. return false;
  41131. }
  41132. }
  41133. return true;
  41134. }
  41135. function DeviceParams(params) {
  41136. this.xdpi = params.xdpi;
  41137. this.ydpi = params.ydpi;
  41138. this.bevelMm = params.bevelMm;
  41139. }
  41140. module.exports = Dpdb;
  41141. },{"../util.js":23,"./dpdb-cache.js":11,"./dpdb.json":12}],14:[function(_dereq_,module,exports){
  41142. /*
  41143. * Copyright 2015 Google Inc. All Rights Reserved.
  41144. * Licensed under the Apache License, Version 2.0 (the "License");
  41145. * you may not use this file except in compliance with the License.
  41146. * You may obtain a copy of the License at
  41147. *
  41148. * http://www.apache.org/licenses/LICENSE-2.0
  41149. *
  41150. * Unless required by applicable law or agreed to in writing, software
  41151. * distributed under the License is distributed on an "AS IS" BASIS,
  41152. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41153. * See the License for the specific language governing permissions and
  41154. * limitations under the License.
  41155. */
  41156. var Util = _dereq_('./util.js');
  41157. var WebVRPolyfill = _dereq_('./webvr-polyfill.js').WebVRPolyfill;
  41158. // Initialize a WebVRConfig just in case.
  41159. window.WebVRConfig = Util.extend({
  41160. // Forces availability of VR mode, even for non-mobile devices.
  41161. FORCE_ENABLE_VR: false,
  41162. // Complementary filter coefficient. 0 for accelerometer, 1 for gyro.
  41163. K_FILTER: 0.98,
  41164. // How far into the future to predict during fast motion (in seconds).
  41165. PREDICTION_TIME_S: 0.040,
  41166. // Flag to enable touch panner. In case you have your own touch controls.
  41167. TOUCH_PANNER_DISABLED: true,
  41168. // Flag to disabled the UI in VR Mode.
  41169. CARDBOARD_UI_DISABLED: false, // Default: false
  41170. // Flag to disable the instructions to rotate your device.
  41171. ROTATE_INSTRUCTIONS_DISABLED: false, // Default: false.
  41172. // Enable yaw panning only, disabling roll and pitch. This can be useful
  41173. // for panoramas with nothing interesting above or below.
  41174. YAW_ONLY: false,
  41175. // To disable keyboard and mouse controls, if you want to use your own
  41176. // implementation.
  41177. MOUSE_KEYBOARD_CONTROLS_DISABLED: false,
  41178. // Prevent the polyfill from initializing immediately. Requires the app
  41179. // to call InitializeWebVRPolyfill() before it can be used.
  41180. DEFER_INITIALIZATION: false,
  41181. // Enable the deprecated version of the API (navigator.getVRDevices).
  41182. ENABLE_DEPRECATED_API: false,
  41183. // Scales the recommended buffer size reported by WebVR, which can improve
  41184. // performance.
  41185. // UPDATE(2016-05-03): Setting this to 0.5 by default since 1.0 does not
  41186. // perform well on many mobile devices.
  41187. BUFFER_SCALE: 0.5,
  41188. // Allow VRDisplay.submitFrame to change gl bindings, which is more
  41189. // efficient if the application code will re-bind its resources on the
  41190. // next frame anyway. This has been seen to cause rendering glitches with
  41191. // THREE.js.
  41192. // Dirty bindings include: gl.FRAMEBUFFER_BINDING, gl.CURRENT_PROGRAM,
  41193. // gl.ARRAY_BUFFER_BINDING, gl.ELEMENT_ARRAY_BUFFER_BINDING,
  41194. // and gl.TEXTURE_BINDING_2D for texture unit 0.
  41195. DIRTY_SUBMIT_FRAME_BINDINGS: false,
  41196. // When set to true, this will cause a polyfilled VRDisplay to always be
  41197. // appended to the list returned by navigator.getVRDisplays(), even if that
  41198. // list includes a native VRDisplay.
  41199. ALWAYS_APPEND_POLYFILL_DISPLAY: false
  41200. }, window.WebVRConfig);
  41201. if (!window.WebVRConfig.DEFER_INITIALIZATION) {
  41202. new WebVRPolyfill();
  41203. } else {
  41204. window.InitializeWebVRPolyfill = function() {
  41205. new WebVRPolyfill();
  41206. }
  41207. }
  41208. },{"./util.js":23,"./webvr-polyfill.js":26}],15:[function(_dereq_,module,exports){
  41209. /*
  41210. * Copyright 2016 Google Inc. All Rights Reserved.
  41211. * Licensed under the Apache License, Version 2.0 (the "License");
  41212. * you may not use this file except in compliance with the License.
  41213. * You may obtain a copy of the License at
  41214. *
  41215. * http://www.apache.org/licenses/LICENSE-2.0
  41216. *
  41217. * Unless required by applicable law or agreed to in writing, software
  41218. * distributed under the License is distributed on an "AS IS" BASIS,
  41219. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41220. * See the License for the specific language governing permissions and
  41221. * limitations under the License.
  41222. */
  41223. var MathUtil = window.MathUtil || {};
  41224. MathUtil.degToRad = Math.PI / 180;
  41225. MathUtil.radToDeg = 180 / Math.PI;
  41226. // Some minimal math functionality borrowed from THREE.Math and stripped down
  41227. // for the purposes of this library.
  41228. MathUtil.Vector2 = function ( x, y ) {
  41229. this.x = x || 0;
  41230. this.y = y || 0;
  41231. };
  41232. MathUtil.Vector2.prototype = {
  41233. constructor: MathUtil.Vector2,
  41234. set: function ( x, y ) {
  41235. this.x = x;
  41236. this.y = y;
  41237. return this;
  41238. },
  41239. copy: function ( v ) {
  41240. this.x = v.x;
  41241. this.y = v.y;
  41242. return this;
  41243. },
  41244. subVectors: function ( a, b ) {
  41245. this.x = a.x - b.x;
  41246. this.y = a.y - b.y;
  41247. return this;
  41248. },
  41249. };
  41250. MathUtil.Vector3 = function ( x, y, z ) {
  41251. this.x = x || 0;
  41252. this.y = y || 0;
  41253. this.z = z || 0;
  41254. };
  41255. MathUtil.Vector3.prototype = {
  41256. constructor: MathUtil.Vector3,
  41257. set: function ( x, y, z ) {
  41258. this.x = x;
  41259. this.y = y;
  41260. this.z = z;
  41261. return this;
  41262. },
  41263. copy: function ( v ) {
  41264. this.x = v.x;
  41265. this.y = v.y;
  41266. this.z = v.z;
  41267. return this;
  41268. },
  41269. length: function () {
  41270. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  41271. },
  41272. normalize: function () {
  41273. var scalar = this.length();
  41274. if ( scalar !== 0 ) {
  41275. var invScalar = 1 / scalar;
  41276. this.multiplyScalar(invScalar);
  41277. } else {
  41278. this.x = 0;
  41279. this.y = 0;
  41280. this.z = 0;
  41281. }
  41282. return this;
  41283. },
  41284. multiplyScalar: function ( scalar ) {
  41285. this.x *= scalar;
  41286. this.y *= scalar;
  41287. this.z *= scalar;
  41288. },
  41289. applyQuaternion: function ( q ) {
  41290. var x = this.x;
  41291. var y = this.y;
  41292. var z = this.z;
  41293. var qx = q.x;
  41294. var qy = q.y;
  41295. var qz = q.z;
  41296. var qw = q.w;
  41297. // calculate quat * vector
  41298. var ix = qw * x + qy * z - qz * y;
  41299. var iy = qw * y + qz * x - qx * z;
  41300. var iz = qw * z + qx * y - qy * x;
  41301. var iw = - qx * x - qy * y - qz * z;
  41302. // calculate result * inverse quat
  41303. this.x = ix * qw + iw * - qx + iy * - qz - iz * - qy;
  41304. this.y = iy * qw + iw * - qy + iz * - qx - ix * - qz;
  41305. this.z = iz * qw + iw * - qz + ix * - qy - iy * - qx;
  41306. return this;
  41307. },
  41308. dot: function ( v ) {
  41309. return this.x * v.x + this.y * v.y + this.z * v.z;
  41310. },
  41311. crossVectors: function ( a, b ) {
  41312. var ax = a.x, ay = a.y, az = a.z;
  41313. var bx = b.x, by = b.y, bz = b.z;
  41314. this.x = ay * bz - az * by;
  41315. this.y = az * bx - ax * bz;
  41316. this.z = ax * by - ay * bx;
  41317. return this;
  41318. },
  41319. };
  41320. MathUtil.Quaternion = function ( x, y, z, w ) {
  41321. this.x = x || 0;
  41322. this.y = y || 0;
  41323. this.z = z || 0;
  41324. this.w = ( w !== undefined ) ? w : 1;
  41325. };
  41326. MathUtil.Quaternion.prototype = {
  41327. constructor: MathUtil.Quaternion,
  41328. set: function ( x, y, z, w ) {
  41329. this.x = x;
  41330. this.y = y;
  41331. this.z = z;
  41332. this.w = w;
  41333. return this;
  41334. },
  41335. copy: function ( quaternion ) {
  41336. this.x = quaternion.x;
  41337. this.y = quaternion.y;
  41338. this.z = quaternion.z;
  41339. this.w = quaternion.w;
  41340. return this;
  41341. },
  41342. setFromEulerXYZ: function( x, y, z ) {
  41343. var c1 = Math.cos( x / 2 );
  41344. var c2 = Math.cos( y / 2 );
  41345. var c3 = Math.cos( z / 2 );
  41346. var s1 = Math.sin( x / 2 );
  41347. var s2 = Math.sin( y / 2 );
  41348. var s3 = Math.sin( z / 2 );
  41349. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41350. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41351. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  41352. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  41353. return this;
  41354. },
  41355. setFromEulerYXZ: function( x, y, z ) {
  41356. var c1 = Math.cos( x / 2 );
  41357. var c2 = Math.cos( y / 2 );
  41358. var c3 = Math.cos( z / 2 );
  41359. var s1 = Math.sin( x / 2 );
  41360. var s2 = Math.sin( y / 2 );
  41361. var s3 = Math.sin( z / 2 );
  41362. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  41363. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  41364. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  41365. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  41366. return this;
  41367. },
  41368. setFromAxisAngle: function ( axis, angle ) {
  41369. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  41370. // assumes axis is normalized
  41371. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  41372. this.x = axis.x * s;
  41373. this.y = axis.y * s;
  41374. this.z = axis.z * s;
  41375. this.w = Math.cos( halfAngle );
  41376. return this;
  41377. },
  41378. multiply: function ( q ) {
  41379. return this.multiplyQuaternions( this, q );
  41380. },
  41381. multiplyQuaternions: function ( a, b ) {
  41382. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  41383. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w;
  41384. var qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  41385. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  41386. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  41387. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  41388. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  41389. return this;
  41390. },
  41391. inverse: function () {
  41392. this.x *= -1;
  41393. this.y *= -1;
  41394. this.z *= -1;
  41395. this.normalize();
  41396. return this;
  41397. },
  41398. normalize: function () {
  41399. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  41400. if ( l === 0 ) {
  41401. this.x = 0;
  41402. this.y = 0;
  41403. this.z = 0;
  41404. this.w = 1;
  41405. } else {
  41406. l = 1 / l;
  41407. this.x = this.x * l;
  41408. this.y = this.y * l;
  41409. this.z = this.z * l;
  41410. this.w = this.w * l;
  41411. }
  41412. return this;
  41413. },
  41414. slerp: function ( qb, t ) {
  41415. if ( t === 0 ) return this;
  41416. if ( t === 1 ) return this.copy( qb );
  41417. var x = this.x, y = this.y, z = this.z, w = this.w;
  41418. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  41419. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  41420. if ( cosHalfTheta < 0 ) {
  41421. this.w = - qb.w;
  41422. this.x = - qb.x;
  41423. this.y = - qb.y;
  41424. this.z = - qb.z;
  41425. cosHalfTheta = - cosHalfTheta;
  41426. } else {
  41427. this.copy( qb );
  41428. }
  41429. if ( cosHalfTheta >= 1.0 ) {
  41430. this.w = w;
  41431. this.x = x;
  41432. this.y = y;
  41433. this.z = z;
  41434. return this;
  41435. }
  41436. var halfTheta = Math.acos( cosHalfTheta );
  41437. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  41438. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  41439. this.w = 0.5 * ( w + this.w );
  41440. this.x = 0.5 * ( x + this.x );
  41441. this.y = 0.5 * ( y + this.y );
  41442. this.z = 0.5 * ( z + this.z );
  41443. return this;
  41444. }
  41445. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  41446. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  41447. this.w = ( w * ratioA + this.w * ratioB );
  41448. this.x = ( x * ratioA + this.x * ratioB );
  41449. this.y = ( y * ratioA + this.y * ratioB );
  41450. this.z = ( z * ratioA + this.z * ratioB );
  41451. return this;
  41452. },
  41453. setFromUnitVectors: function () {
  41454. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  41455. // assumes direction vectors vFrom and vTo are normalized
  41456. var v1, r;
  41457. var EPS = 0.000001;
  41458. return function ( vFrom, vTo ) {
  41459. if ( v1 === undefined ) v1 = new MathUtil.Vector3();
  41460. r = vFrom.dot( vTo ) + 1;
  41461. if ( r < EPS ) {
  41462. r = 0;
  41463. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  41464. v1.set( - vFrom.y, vFrom.x, 0 );
  41465. } else {
  41466. v1.set( 0, - vFrom.z, vFrom.y );
  41467. }
  41468. } else {
  41469. v1.crossVectors( vFrom, vTo );
  41470. }
  41471. this.x = v1.x;
  41472. this.y = v1.y;
  41473. this.z = v1.z;
  41474. this.w = r;
  41475. this.normalize();
  41476. return this;
  41477. }
  41478. }(),
  41479. };
  41480. module.exports = MathUtil;
  41481. },{}],16:[function(_dereq_,module,exports){
  41482. /*
  41483. * Copyright 2016 Google Inc. All Rights Reserved.
  41484. * Licensed under the Apache License, Version 2.0 (the "License");
  41485. * you may not use this file except in compliance with the License.
  41486. * You may obtain a copy of the License at
  41487. *
  41488. * http://www.apache.org/licenses/LICENSE-2.0
  41489. *
  41490. * Unless required by applicable law or agreed to in writing, software
  41491. * distributed under the License is distributed on an "AS IS" BASIS,
  41492. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41493. * See the License for the specific language governing permissions and
  41494. * limitations under the License.
  41495. */
  41496. var VRDisplay = _dereq_('./base.js').VRDisplay;
  41497. var MathUtil = _dereq_('./math-util.js');
  41498. var Util = _dereq_('./util.js');
  41499. // How much to rotate per key stroke.
  41500. var KEY_SPEED = 0.15;
  41501. var KEY_ANIMATION_DURATION = 80;
  41502. // How much to rotate for mouse events.
  41503. var MOUSE_SPEED_X = 0.5;
  41504. var MOUSE_SPEED_Y = 0.3;
  41505. /**
  41506. * VRDisplay based on mouse and keyboard input. Designed for desktops/laptops
  41507. * where orientation events aren't supported. Cannot present.
  41508. */
  41509. function MouseKeyboardVRDisplay() {
  41510. this.displayName = 'Mouse and Keyboard VRDisplay (webvr-polyfill)';
  41511. this.capabilities.hasOrientation = true;
  41512. // Attach to mouse and keyboard events.
  41513. window.addEventListener('keydown', this.onKeyDown_.bind(this));
  41514. window.addEventListener('mousemove', this.onMouseMove_.bind(this));
  41515. window.addEventListener('mousedown', this.onMouseDown_.bind(this));
  41516. window.addEventListener('mouseup', this.onMouseUp_.bind(this));
  41517. // "Private" members.
  41518. this.phi_ = 0;
  41519. this.theta_ = 0;
  41520. // Variables for keyboard-based rotation animation.
  41521. this.targetAngle_ = null;
  41522. this.angleAnimation_ = null;
  41523. // State variables for calculations.
  41524. this.orientation_ = new MathUtil.Quaternion();
  41525. // Variables for mouse-based rotation.
  41526. this.rotateStart_ = new MathUtil.Vector2();
  41527. this.rotateEnd_ = new MathUtil.Vector2();
  41528. this.rotateDelta_ = new MathUtil.Vector2();
  41529. this.isDragging_ = false;
  41530. this.orientationOut_ = new Float32Array(4);
  41531. }
  41532. MouseKeyboardVRDisplay.prototype = new VRDisplay();
  41533. MouseKeyboardVRDisplay.prototype.getImmediatePose = function() {
  41534. this.orientation_.setFromEulerYXZ(this.phi_, this.theta_, 0);
  41535. this.orientationOut_[0] = this.orientation_.x;
  41536. this.orientationOut_[1] = this.orientation_.y;
  41537. this.orientationOut_[2] = this.orientation_.z;
  41538. this.orientationOut_[3] = this.orientation_.w;
  41539. return {
  41540. position: null,
  41541. orientation: this.orientationOut_,
  41542. linearVelocity: null,
  41543. linearAcceleration: null,
  41544. angularVelocity: null,
  41545. angularAcceleration: null
  41546. };
  41547. };
  41548. MouseKeyboardVRDisplay.prototype.onKeyDown_ = function(e) {
  41549. // Track WASD and arrow keys.
  41550. if (e.keyCode == 38) { // Up key.
  41551. this.animatePhi_(this.phi_ + KEY_SPEED);
  41552. } else if (e.keyCode == 39) { // Right key.
  41553. this.animateTheta_(this.theta_ - KEY_SPEED);
  41554. } else if (e.keyCode == 40) { // Down key.
  41555. this.animatePhi_(this.phi_ - KEY_SPEED);
  41556. } else if (e.keyCode == 37) { // Left key.
  41557. this.animateTheta_(this.theta_ + KEY_SPEED);
  41558. }
  41559. };
  41560. MouseKeyboardVRDisplay.prototype.animateTheta_ = function(targetAngle) {
  41561. this.animateKeyTransitions_('theta_', targetAngle);
  41562. };
  41563. MouseKeyboardVRDisplay.prototype.animatePhi_ = function(targetAngle) {
  41564. // Prevent looking too far up or down.
  41565. targetAngle = Util.clamp(targetAngle, -Math.PI/2, Math.PI/2);
  41566. this.animateKeyTransitions_('phi_', targetAngle);
  41567. };
  41568. /**
  41569. * Start an animation to transition an angle from one value to another.
  41570. */
  41571. MouseKeyboardVRDisplay.prototype.animateKeyTransitions_ = function(angleName, targetAngle) {
  41572. // If an animation is currently running, cancel it.
  41573. if (this.angleAnimation_) {
  41574. cancelAnimationFrame(this.angleAnimation_);
  41575. }
  41576. var startAngle = this[angleName];
  41577. var startTime = new Date();
  41578. // Set up an interval timer to perform the animation.
  41579. this.angleAnimation_ = requestAnimationFrame(function animate() {
  41580. // Once we're finished the animation, we're done.
  41581. var elapsed = new Date() - startTime;
  41582. if (elapsed >= KEY_ANIMATION_DURATION) {
  41583. this[angleName] = targetAngle;
  41584. cancelAnimationFrame(this.angleAnimation_);
  41585. return;
  41586. }
  41587. // loop with requestAnimationFrame
  41588. this.angleAnimation_ = requestAnimationFrame(animate.bind(this))
  41589. // Linearly interpolate the angle some amount.
  41590. var percent = elapsed / KEY_ANIMATION_DURATION;
  41591. this[angleName] = startAngle + (targetAngle - startAngle) * percent;
  41592. }.bind(this));
  41593. };
  41594. MouseKeyboardVRDisplay.prototype.onMouseDown_ = function(e) {
  41595. this.rotateStart_.set(e.clientX, e.clientY);
  41596. this.isDragging_ = true;
  41597. };
  41598. // Very similar to https://gist.github.com/mrflix/8351020
  41599. MouseKeyboardVRDisplay.prototype.onMouseMove_ = function(e) {
  41600. if (!this.isDragging_ && !this.isPointerLocked_()) {
  41601. return;
  41602. }
  41603. // Support pointer lock API.
  41604. if (this.isPointerLocked_()) {
  41605. var movementX = e.movementX || e.mozMovementX || 0;
  41606. var movementY = e.movementY || e.mozMovementY || 0;
  41607. this.rotateEnd_.set(this.rotateStart_.x - movementX, this.rotateStart_.y - movementY);
  41608. } else {
  41609. this.rotateEnd_.set(e.clientX, e.clientY);
  41610. }
  41611. // Calculate how much we moved in mouse space.
  41612. this.rotateDelta_.subVectors(this.rotateEnd_, this.rotateStart_);
  41613. this.rotateStart_.copy(this.rotateEnd_);
  41614. // Keep track of the cumulative euler angles.
  41615. this.phi_ += 2 * Math.PI * this.rotateDelta_.y / screen.height * MOUSE_SPEED_Y;
  41616. this.theta_ += 2 * Math.PI * this.rotateDelta_.x / screen.width * MOUSE_SPEED_X;
  41617. // Prevent looking too far up or down.
  41618. this.phi_ = Util.clamp(this.phi_, -Math.PI/2, Math.PI/2);
  41619. };
  41620. MouseKeyboardVRDisplay.prototype.onMouseUp_ = function(e) {
  41621. this.isDragging_ = false;
  41622. };
  41623. MouseKeyboardVRDisplay.prototype.isPointerLocked_ = function() {
  41624. var el = document.pointerLockElement || document.mozPointerLockElement ||
  41625. document.webkitPointerLockElement;
  41626. return el !== undefined;
  41627. };
  41628. MouseKeyboardVRDisplay.prototype.resetPose = function() {
  41629. this.phi_ = 0;
  41630. this.theta_ = 0;
  41631. };
  41632. module.exports = MouseKeyboardVRDisplay;
  41633. },{"./base.js":3,"./math-util.js":15,"./util.js":23}],17:[function(_dereq_,module,exports){
  41634. /*
  41635. * Copyright 2015 Google Inc. All Rights Reserved.
  41636. * Licensed under the Apache License, Version 2.0 (the "License");
  41637. * you may not use this file except in compliance with the License.
  41638. * You may obtain a copy of the License at
  41639. *
  41640. * http://www.apache.org/licenses/LICENSE-2.0
  41641. *
  41642. * Unless required by applicable law or agreed to in writing, software
  41643. * distributed under the License is distributed on an "AS IS" BASIS,
  41644. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41645. * See the License for the specific language governing permissions and
  41646. * limitations under the License.
  41647. */
  41648. var Util = _dereq_('./util.js');
  41649. function RotateInstructions() {
  41650. this.loadIcon_();
  41651. var overlay = document.createElement('div');
  41652. var s = overlay.style;
  41653. s.position = 'fixed';
  41654. s.top = 0;
  41655. s.right = 0;
  41656. s.bottom = 0;
  41657. s.left = 0;
  41658. s.backgroundColor = 'gray';
  41659. s.fontFamily = 'sans-serif';
  41660. // Force this to be above the fullscreen canvas, which is at zIndex: 999999.
  41661. s.zIndex = 1000000;
  41662. var img = document.createElement('img');
  41663. img.src = this.icon;
  41664. var s = img.style;
  41665. s.marginLeft = '25%';
  41666. s.marginTop = '25%';
  41667. s.width = '50%';
  41668. overlay.appendChild(img);
  41669. var text = document.createElement('div');
  41670. var s = text.style;
  41671. s.textAlign = 'center';
  41672. s.fontSize = '16px';
  41673. s.lineHeight = '24px';
  41674. s.margin = '24px 25%';
  41675. s.width = '50%';
  41676. text.innerHTML = 'Place your phone into your Cardboard viewer.';
  41677. overlay.appendChild(text);
  41678. var snackbar = document.createElement('div');
  41679. var s = snackbar.style;
  41680. s.backgroundColor = '#CFD8DC';
  41681. s.position = 'fixed';
  41682. s.bottom = 0;
  41683. s.width = '100%';
  41684. s.height = '48px';
  41685. s.padding = '14px 24px';
  41686. s.boxSizing = 'border-box';
  41687. s.color = '#656A6B';
  41688. overlay.appendChild(snackbar);
  41689. var snackbarText = document.createElement('div');
  41690. snackbarText.style.float = 'left';
  41691. snackbarText.innerHTML = 'No Cardboard viewer?';
  41692. var snackbarButton = document.createElement('a');
  41693. snackbarButton.href = 'https://www.google.com/get/cardboard/get-cardboard/';
  41694. snackbarButton.innerHTML = 'get one';
  41695. snackbarButton.target = '_blank';
  41696. var s = snackbarButton.style;
  41697. s.float = 'right';
  41698. s.fontWeight = 600;
  41699. s.textTransform = 'uppercase';
  41700. s.borderLeft = '1px solid gray';
  41701. s.paddingLeft = '24px';
  41702. s.textDecoration = 'none';
  41703. s.color = '#656A6B';
  41704. snackbar.appendChild(snackbarText);
  41705. snackbar.appendChild(snackbarButton);
  41706. this.overlay = overlay;
  41707. this.text = text;
  41708. this.hide();
  41709. }
  41710. RotateInstructions.prototype.show = function(parent) {
  41711. if (!parent && !this.overlay.parentElement) {
  41712. document.body.appendChild(this.overlay);
  41713. } else if (parent) {
  41714. if (this.overlay.parentElement && this.overlay.parentElement != parent)
  41715. this.overlay.parentElement.removeChild(this.overlay);
  41716. parent.appendChild(this.overlay);
  41717. }
  41718. this.overlay.style.display = 'block';
  41719. var img = this.overlay.querySelector('img');
  41720. var s = img.style;
  41721. if (Util.isLandscapeMode()) {
  41722. s.width = '20%';
  41723. s.marginLeft = '40%';
  41724. s.marginTop = '3%';
  41725. } else {
  41726. s.width = '50%';
  41727. s.marginLeft = '25%';
  41728. s.marginTop = '25%';
  41729. }
  41730. };
  41731. RotateInstructions.prototype.hide = function() {
  41732. this.overlay.style.display = 'none';
  41733. };
  41734. RotateInstructions.prototype.showTemporarily = function(ms, parent) {
  41735. this.show(parent);
  41736. this.timer = setTimeout(this.hide.bind(this), ms);
  41737. };
  41738. RotateInstructions.prototype.disableShowTemporarily = function() {
  41739. clearTimeout(this.timer);
  41740. };
  41741. RotateInstructions.prototype.update = function() {
  41742. this.disableShowTemporarily();
  41743. // In portrait VR mode, tell the user to rotate to landscape. Otherwise, hide
  41744. // the instructions.
  41745. if (!Util.isLandscapeMode() && Util.isMobile()) {
  41746. this.show();
  41747. } else {
  41748. this.hide();
  41749. }
  41750. };
  41751. RotateInstructions.prototype.loadIcon_ = function() {
  41752. // Encoded asset_src/rotate-instructions.svg
  41753. 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+');
  41754. };
  41755. module.exports = RotateInstructions;
  41756. },{"./util.js":23}],18:[function(_dereq_,module,exports){
  41757. /*
  41758. * Copyright 2015 Google Inc. All Rights Reserved.
  41759. * Licensed under the Apache License, Version 2.0 (the "License");
  41760. * you may not use this file except in compliance with the License.
  41761. * You may obtain a copy of the License at
  41762. *
  41763. * http://www.apache.org/licenses/LICENSE-2.0
  41764. *
  41765. * Unless required by applicable law or agreed to in writing, software
  41766. * distributed under the License is distributed on an "AS IS" BASIS,
  41767. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41768. * See the License for the specific language governing permissions and
  41769. * limitations under the License.
  41770. */
  41771. var SensorSample = _dereq_('./sensor-sample.js');
  41772. var MathUtil = _dereq_('../math-util.js');
  41773. var Util = _dereq_('../util.js');
  41774. /**
  41775. * An implementation of a simple complementary filter, which fuses gyroscope and
  41776. * accelerometer data from the 'devicemotion' event.
  41777. *
  41778. * Accelerometer data is very noisy, but stable over the long term.
  41779. * Gyroscope data is smooth, but tends to drift over the long term.
  41780. *
  41781. * This fusion is relatively simple:
  41782. * 1. Get orientation estimates from accelerometer by applying a low-pass filter
  41783. * on that data.
  41784. * 2. Get orientation estimates from gyroscope by integrating over time.
  41785. * 3. Combine the two estimates, weighing (1) in the long term, but (2) for the
  41786. * short term.
  41787. */
  41788. function ComplementaryFilter(kFilter) {
  41789. this.kFilter = kFilter;
  41790. // Raw sensor measurements.
  41791. this.currentAccelMeasurement = new SensorSample();
  41792. this.currentGyroMeasurement = new SensorSample();
  41793. this.previousGyroMeasurement = new SensorSample();
  41794. // Set default look direction to be in the correct direction.
  41795. if (Util.isIOS()) {
  41796. this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1);
  41797. } else {
  41798. this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1);
  41799. }
  41800. this.previousFilterQ = new MathUtil.Quaternion();
  41801. this.previousFilterQ.copy(this.filterQ);
  41802. // Orientation based on the accelerometer.
  41803. this.accelQ = new MathUtil.Quaternion();
  41804. // Whether or not the orientation has been initialized.
  41805. this.isOrientationInitialized = false;
  41806. // Running estimate of gravity based on the current orientation.
  41807. this.estimatedGravity = new MathUtil.Vector3();
  41808. // Measured gravity based on accelerometer.
  41809. this.measuredGravity = new MathUtil.Vector3();
  41810. // Debug only quaternion of gyro-based orientation.
  41811. this.gyroIntegralQ = new MathUtil.Quaternion();
  41812. }
  41813. ComplementaryFilter.prototype.addAccelMeasurement = function(vector, timestampS) {
  41814. this.currentAccelMeasurement.set(vector, timestampS);
  41815. };
  41816. ComplementaryFilter.prototype.addGyroMeasurement = function(vector, timestampS) {
  41817. this.currentGyroMeasurement.set(vector, timestampS);
  41818. var deltaT = timestampS - this.previousGyroMeasurement.timestampS;
  41819. if (Util.isTimestampDeltaValid(deltaT)) {
  41820. this.run_();
  41821. }
  41822. this.previousGyroMeasurement.copy(this.currentGyroMeasurement);
  41823. };
  41824. ComplementaryFilter.prototype.run_ = function() {
  41825. if (!this.isOrientationInitialized) {
  41826. this.accelQ = this.accelToQuaternion_(this.currentAccelMeasurement.sample);
  41827. this.previousFilterQ.copy(this.accelQ);
  41828. this.isOrientationInitialized = true;
  41829. return;
  41830. }
  41831. var deltaT = this.currentGyroMeasurement.timestampS -
  41832. this.previousGyroMeasurement.timestampS;
  41833. // Convert gyro rotation vector to a quaternion delta.
  41834. var gyroDeltaQ = this.gyroToQuaternionDelta_(this.currentGyroMeasurement.sample, deltaT);
  41835. this.gyroIntegralQ.multiply(gyroDeltaQ);
  41836. // filter_1 = K * (filter_0 + gyro * dT) + (1 - K) * accel.
  41837. this.filterQ.copy(this.previousFilterQ);
  41838. this.filterQ.multiply(gyroDeltaQ);
  41839. // Calculate the delta between the current estimated gravity and the real
  41840. // gravity vector from accelerometer.
  41841. var invFilterQ = new MathUtil.Quaternion();
  41842. invFilterQ.copy(this.filterQ);
  41843. invFilterQ.inverse();
  41844. this.estimatedGravity.set(0, 0, -1);
  41845. this.estimatedGravity.applyQuaternion(invFilterQ);
  41846. this.estimatedGravity.normalize();
  41847. this.measuredGravity.copy(this.currentAccelMeasurement.sample);
  41848. this.measuredGravity.normalize();
  41849. // Compare estimated gravity with measured gravity, get the delta quaternion
  41850. // between the two.
  41851. var deltaQ = new MathUtil.Quaternion();
  41852. deltaQ.setFromUnitVectors(this.estimatedGravity, this.measuredGravity);
  41853. deltaQ.inverse();
  41854. if (Util.isDebug()) {
  41855. console.log('Delta: %d deg, G_est: (%s, %s, %s), G_meas: (%s, %s, %s)',
  41856. MathUtil.radToDeg * Util.getQuaternionAngle(deltaQ),
  41857. (this.estimatedGravity.x).toFixed(1),
  41858. (this.estimatedGravity.y).toFixed(1),
  41859. (this.estimatedGravity.z).toFixed(1),
  41860. (this.measuredGravity.x).toFixed(1),
  41861. (this.measuredGravity.y).toFixed(1),
  41862. (this.measuredGravity.z).toFixed(1));
  41863. }
  41864. // Calculate the SLERP target: current orientation plus the measured-estimated
  41865. // quaternion delta.
  41866. var targetQ = new MathUtil.Quaternion();
  41867. targetQ.copy(this.filterQ);
  41868. targetQ.multiply(deltaQ);
  41869. // SLERP factor: 0 is pure gyro, 1 is pure accel.
  41870. this.filterQ.slerp(targetQ, 1 - this.kFilter);
  41871. this.previousFilterQ.copy(this.filterQ);
  41872. };
  41873. ComplementaryFilter.prototype.getOrientation = function() {
  41874. return this.filterQ;
  41875. };
  41876. ComplementaryFilter.prototype.accelToQuaternion_ = function(accel) {
  41877. var normAccel = new MathUtil.Vector3();
  41878. normAccel.copy(accel);
  41879. normAccel.normalize();
  41880. var quat = new MathUtil.Quaternion();
  41881. quat.setFromUnitVectors(new MathUtil.Vector3(0, 0, -1), normAccel);
  41882. quat.inverse();
  41883. return quat;
  41884. };
  41885. ComplementaryFilter.prototype.gyroToQuaternionDelta_ = function(gyro, dt) {
  41886. // Extract axis and angle from the gyroscope data.
  41887. var quat = new MathUtil.Quaternion();
  41888. var axis = new MathUtil.Vector3();
  41889. axis.copy(gyro);
  41890. axis.normalize();
  41891. quat.setFromAxisAngle(axis, gyro.length() * dt);
  41892. return quat;
  41893. };
  41894. module.exports = ComplementaryFilter;
  41895. },{"../math-util.js":15,"../util.js":23,"./sensor-sample.js":21}],19:[function(_dereq_,module,exports){
  41896. /*
  41897. * Copyright 2015 Google Inc. All Rights Reserved.
  41898. * Licensed under the Apache License, Version 2.0 (the "License");
  41899. * you may not use this file except in compliance with the License.
  41900. * You may obtain a copy of the License at
  41901. *
  41902. * http://www.apache.org/licenses/LICENSE-2.0
  41903. *
  41904. * Unless required by applicable law or agreed to in writing, software
  41905. * distributed under the License is distributed on an "AS IS" BASIS,
  41906. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  41907. * See the License for the specific language governing permissions and
  41908. * limitations under the License.
  41909. */
  41910. var ComplementaryFilter = _dereq_('./complementary-filter.js');
  41911. var PosePredictor = _dereq_('./pose-predictor.js');
  41912. var TouchPanner = _dereq_('../touch-panner.js');
  41913. var MathUtil = _dereq_('../math-util.js');
  41914. var Util = _dereq_('../util.js');
  41915. /**
  41916. * The pose sensor, implemented using DeviceMotion APIs.
  41917. */
  41918. function FusionPoseSensor() {
  41919. this.deviceId = 'webvr-polyfill:fused';
  41920. this.deviceName = 'VR Position Device (webvr-polyfill:fused)';
  41921. this.accelerometer = new MathUtil.Vector3();
  41922. this.gyroscope = new MathUtil.Vector3();
  41923. this.start();
  41924. this.filter = new ComplementaryFilter(WebVRConfig.K_FILTER);
  41925. this.posePredictor = new PosePredictor(WebVRConfig.PREDICTION_TIME_S);
  41926. this.touchPanner = new TouchPanner();
  41927. this.filterToWorldQ = new MathUtil.Quaternion();
  41928. // Set the filter to world transform, depending on OS.
  41929. if (Util.isIOS()) {
  41930. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2);
  41931. } else {
  41932. this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2);
  41933. }
  41934. this.inverseWorldToScreenQ = new MathUtil.Quaternion();
  41935. this.worldToScreenQ = new MathUtil.Quaternion();
  41936. this.originalPoseAdjustQ = new MathUtil.Quaternion();
  41937. this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1),
  41938. -window.orientation * Math.PI / 180);
  41939. this.setScreenTransform_();
  41940. // Adjust this filter for being in landscape mode.
  41941. if (Util.isLandscapeMode()) {
  41942. this.filterToWorldQ.multiply(this.inverseWorldToScreenQ);
  41943. }
  41944. // Keep track of a reset transform for resetSensor.
  41945. this.resetQ = new MathUtil.Quaternion();
  41946. this.isFirefoxAndroid = Util.isFirefoxAndroid();
  41947. this.isIOS = Util.isIOS();
  41948. this.orientationOut_ = new Float32Array(4);
  41949. }
  41950. FusionPoseSensor.prototype.getPosition = function() {
  41951. // This PoseSensor doesn't support position
  41952. return null;
  41953. };
  41954. FusionPoseSensor.prototype.getOrientation = function() {
  41955. // Convert from filter space to the the same system used by the
  41956. // deviceorientation event.
  41957. var orientation = this.filter.getOrientation();
  41958. // Predict orientation.
  41959. this.predictedQ = this.posePredictor.getPrediction(orientation, this.gyroscope, this.previousTimestampS);
  41960. // Convert to THREE coordinate system: -Z forward, Y up, X right.
  41961. var out = new MathUtil.Quaternion();
  41962. out.copy(this.filterToWorldQ);
  41963. out.multiply(this.resetQ);
  41964. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  41965. out.multiply(this.touchPanner.getOrientation());
  41966. }
  41967. out.multiply(this.predictedQ);
  41968. out.multiply(this.worldToScreenQ);
  41969. // Handle the yaw-only case.
  41970. if (WebVRConfig.YAW_ONLY) {
  41971. // Make a quaternion that only turns around the Y-axis.
  41972. out.x = 0;
  41973. out.z = 0;
  41974. out.normalize();
  41975. }
  41976. this.orientationOut_[0] = out.x;
  41977. this.orientationOut_[1] = out.y;
  41978. this.orientationOut_[2] = out.z;
  41979. this.orientationOut_[3] = out.w;
  41980. return this.orientationOut_;
  41981. };
  41982. FusionPoseSensor.prototype.resetPose = function() {
  41983. // Reduce to inverted yaw-only.
  41984. this.resetQ.copy(this.filter.getOrientation());
  41985. this.resetQ.x = 0;
  41986. this.resetQ.y = 0;
  41987. this.resetQ.z *= -1;
  41988. this.resetQ.normalize();
  41989. // Take into account extra transformations in landscape mode.
  41990. if (Util.isLandscapeMode()) {
  41991. this.resetQ.multiply(this.inverseWorldToScreenQ);
  41992. }
  41993. // Take into account original pose.
  41994. this.resetQ.multiply(this.originalPoseAdjustQ);
  41995. if (!WebVRConfig.TOUCH_PANNER_DISABLED) {
  41996. this.touchPanner.resetSensor();
  41997. }
  41998. };
  41999. FusionPoseSensor.prototype.onDeviceMotion_ = function(deviceMotion) {
  42000. this.updateDeviceMotion_(deviceMotion);
  42001. };
  42002. FusionPoseSensor.prototype.updateDeviceMotion_ = function(deviceMotion) {
  42003. var accGravity = deviceMotion.accelerationIncludingGravity;
  42004. var rotRate = deviceMotion.rotationRate;
  42005. var timestampS = deviceMotion.timeStamp / 1000;
  42006. // Firefox Android timeStamp returns one thousandth of a millisecond.
  42007. if (this.isFirefoxAndroid) {
  42008. timestampS /= 1000;
  42009. }
  42010. var deltaS = timestampS - this.previousTimestampS;
  42011. if (deltaS <= Util.MIN_TIMESTEP || deltaS > Util.MAX_TIMESTEP) {
  42012. console.warn('Invalid timestamps detected. Time step between successive ' +
  42013. 'gyroscope sensor samples is very small or not monotonic');
  42014. this.previousTimestampS = timestampS;
  42015. return;
  42016. }
  42017. this.accelerometer.set(-accGravity.x, -accGravity.y, -accGravity.z);
  42018. this.gyroscope.set(rotRate.alpha, rotRate.beta, rotRate.gamma);
  42019. // With iOS and Firefox Android, rotationRate is reported in degrees,
  42020. // so we first convert to radians.
  42021. if (this.isIOS || this.isFirefoxAndroid) {
  42022. this.gyroscope.multiplyScalar(Math.PI / 180);
  42023. }
  42024. this.filter.addAccelMeasurement(this.accelerometer, timestampS);
  42025. this.filter.addGyroMeasurement(this.gyroscope, timestampS);
  42026. this.previousTimestampS = timestampS;
  42027. };
  42028. FusionPoseSensor.prototype.onOrientationChange_ = function(screenOrientation) {
  42029. this.setScreenTransform_();
  42030. };
  42031. /**
  42032. * This is only needed if we are in an cross origin iframe on iOS to work around
  42033. * this issue: https://bugs.webkit.org/show_bug.cgi?id=152299.
  42034. */
  42035. FusionPoseSensor.prototype.onMessage_ = function(event) {
  42036. var message = event.data;
  42037. // If there's no message type, ignore it.
  42038. if (!message || !message.type) {
  42039. return;
  42040. }
  42041. // Ignore all messages that aren't devicemotion.
  42042. var type = message.type.toLowerCase();
  42043. if (type !== 'devicemotion') {
  42044. return;
  42045. }
  42046. // Update device motion.
  42047. this.updateDeviceMotion_(message.deviceMotionEvent);
  42048. };
  42049. FusionPoseSensor.prototype.setScreenTransform_ = function() {
  42050. this.worldToScreenQ.set(0, 0, 0, 1);
  42051. switch (window.orientation) {
  42052. case 0:
  42053. break;
  42054. case 90:
  42055. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -Math.PI / 2);
  42056. break;
  42057. case -90:
  42058. this.worldToScreenQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), Math.PI / 2);
  42059. break;
  42060. case 180:
  42061. // TODO.
  42062. break;
  42063. }
  42064. this.inverseWorldToScreenQ.copy(this.worldToScreenQ);
  42065. this.inverseWorldToScreenQ.inverse();
  42066. };
  42067. FusionPoseSensor.prototype.start = function() {
  42068. this.onDeviceMotionCallback_ = this.onDeviceMotion_.bind(this);
  42069. this.onOrientationChangeCallback_ = this.onOrientationChange_.bind(this);
  42070. this.onMessageCallback_ = this.onMessage_.bind(this);
  42071. // Only listen for postMessages if we're in an iOS and embedded inside a cross
  42072. // domain IFrame. In this case, the polyfill can still work if the containing
  42073. // page sends synthetic devicemotion events. For an example of this, see
  42074. // iframe-message-sender.js in VR View: https://goo.gl/XDtvFZ
  42075. if (Util.isIOS() && Util.isInsideCrossDomainIFrame()) {
  42076. window.addEventListener('message', this.onMessageCallback_);
  42077. }
  42078. window.addEventListener('orientationchange', this.onOrientationChangeCallback_);
  42079. window.addEventListener('devicemotion', this.onDeviceMotionCallback_);
  42080. };
  42081. FusionPoseSensor.prototype.stop = function() {
  42082. window.removeEventListener('devicemotion', this.onDeviceMotionCallback_);
  42083. window.removeEventListener('orientationchange', this.onOrientationChangeCallback_);
  42084. window.removeEventListener('message', this.onMessageCallback_);
  42085. };
  42086. module.exports = FusionPoseSensor;
  42087. },{"../math-util.js":15,"../touch-panner.js":22,"../util.js":23,"./complementary-filter.js":18,"./pose-predictor.js":20}],20:[function(_dereq_,module,exports){
  42088. /*
  42089. * Copyright 2015 Google Inc. All Rights Reserved.
  42090. * Licensed under the Apache License, Version 2.0 (the "License");
  42091. * you may not use this file except in compliance with the License.
  42092. * You may obtain a copy of the License at
  42093. *
  42094. * http://www.apache.org/licenses/LICENSE-2.0
  42095. *
  42096. * Unless required by applicable law or agreed to in writing, software
  42097. * distributed under the License is distributed on an "AS IS" BASIS,
  42098. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42099. * See the License for the specific language governing permissions and
  42100. * limitations under the License.
  42101. */
  42102. var MathUtil = _dereq_('../math-util');
  42103. var Util = _dereq_('../util');
  42104. /**
  42105. * Given an orientation and the gyroscope data, predicts the future orientation
  42106. * of the head. This makes rendering appear faster.
  42107. *
  42108. * Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf
  42109. *
  42110. * @param {Number} predictionTimeS time from head movement to the appearance of
  42111. * the corresponding image.
  42112. */
  42113. function PosePredictor(predictionTimeS) {
  42114. this.predictionTimeS = predictionTimeS;
  42115. // The quaternion corresponding to the previous state.
  42116. this.previousQ = new MathUtil.Quaternion();
  42117. // Previous time a prediction occurred.
  42118. this.previousTimestampS = null;
  42119. // The delta quaternion that adjusts the current pose.
  42120. this.deltaQ = new MathUtil.Quaternion();
  42121. // The output quaternion.
  42122. this.outQ = new MathUtil.Quaternion();
  42123. }
  42124. PosePredictor.prototype.getPrediction = function(currentQ, gyro, timestampS) {
  42125. if (!this.previousTimestampS) {
  42126. this.previousQ.copy(currentQ);
  42127. this.previousTimestampS = timestampS;
  42128. return currentQ;
  42129. }
  42130. // Calculate axis and angle based on gyroscope rotation rate data.
  42131. var axis = new MathUtil.Vector3();
  42132. axis.copy(gyro);
  42133. axis.normalize();
  42134. var angularSpeed = gyro.length();
  42135. // If we're rotating slowly, don't do prediction.
  42136. if (angularSpeed < MathUtil.degToRad * 20) {
  42137. if (Util.isDebug()) {
  42138. console.log('Moving slowly, at %s deg/s: no prediction',
  42139. (MathUtil.radToDeg * angularSpeed).toFixed(1));
  42140. }
  42141. this.outQ.copy(currentQ);
  42142. this.previousQ.copy(currentQ);
  42143. return this.outQ;
  42144. }
  42145. // Get the predicted angle based on the time delta and latency.
  42146. var deltaT = timestampS - this.previousTimestampS;
  42147. var predictAngle = angularSpeed * this.predictionTimeS;
  42148. this.deltaQ.setFromAxisAngle(axis, predictAngle);
  42149. this.outQ.copy(this.previousQ);
  42150. this.outQ.multiply(this.deltaQ);
  42151. this.previousQ.copy(currentQ);
  42152. this.previousTimestampS = timestampS;
  42153. return this.outQ;
  42154. };
  42155. module.exports = PosePredictor;
  42156. },{"../math-util":15,"../util":23}],21:[function(_dereq_,module,exports){
  42157. function SensorSample(sample, timestampS) {
  42158. this.set(sample, timestampS);
  42159. };
  42160. SensorSample.prototype.set = function(sample, timestampS) {
  42161. this.sample = sample;
  42162. this.timestampS = timestampS;
  42163. };
  42164. SensorSample.prototype.copy = function(sensorSample) {
  42165. this.set(sensorSample.sample, sensorSample.timestampS);
  42166. };
  42167. module.exports = SensorSample;
  42168. },{}],22:[function(_dereq_,module,exports){
  42169. /*
  42170. * Copyright 2015 Google Inc. All Rights Reserved.
  42171. * Licensed under the Apache License, Version 2.0 (the "License");
  42172. * you may not use this file except in compliance with the License.
  42173. * You may obtain a copy of the License at
  42174. *
  42175. * http://www.apache.org/licenses/LICENSE-2.0
  42176. *
  42177. * Unless required by applicable law or agreed to in writing, software
  42178. * distributed under the License is distributed on an "AS IS" BASIS,
  42179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42180. * See the License for the specific language governing permissions and
  42181. * limitations under the License.
  42182. */
  42183. var MathUtil = _dereq_('./math-util.js');
  42184. var Util = _dereq_('./util.js');
  42185. var ROTATE_SPEED = 0.5;
  42186. /**
  42187. * Provides a quaternion responsible for pre-panning the scene before further
  42188. * transformations due to device sensors.
  42189. */
  42190. function TouchPanner() {
  42191. window.addEventListener('touchstart', this.onTouchStart_.bind(this));
  42192. window.addEventListener('touchmove', this.onTouchMove_.bind(this));
  42193. window.addEventListener('touchend', this.onTouchEnd_.bind(this));
  42194. this.isTouching = false;
  42195. this.rotateStart = new MathUtil.Vector2();
  42196. this.rotateEnd = new MathUtil.Vector2();
  42197. this.rotateDelta = new MathUtil.Vector2();
  42198. this.theta = 0;
  42199. this.orientation = new MathUtil.Quaternion();
  42200. }
  42201. TouchPanner.prototype.getOrientation = function() {
  42202. this.orientation.setFromEulerXYZ(0, 0, this.theta);
  42203. return this.orientation;
  42204. };
  42205. TouchPanner.prototype.resetSensor = function() {
  42206. this.theta = 0;
  42207. };
  42208. TouchPanner.prototype.onTouchStart_ = function(e) {
  42209. // Only respond if there is exactly one touch.
  42210. if (e.touches.length != 1) {
  42211. return;
  42212. }
  42213. this.rotateStart.set(e.touches[0].pageX, e.touches[0].pageY);
  42214. this.isTouching = true;
  42215. };
  42216. TouchPanner.prototype.onTouchMove_ = function(e) {
  42217. if (!this.isTouching) {
  42218. return;
  42219. }
  42220. this.rotateEnd.set(e.touches[0].pageX, e.touches[0].pageY);
  42221. this.rotateDelta.subVectors(this.rotateEnd, this.rotateStart);
  42222. this.rotateStart.copy(this.rotateEnd);
  42223. // On iOS, direction is inverted.
  42224. if (Util.isIOS()) {
  42225. this.rotateDelta.x *= -1;
  42226. }
  42227. var element = document.body;
  42228. this.theta += 2 * Math.PI * this.rotateDelta.x / element.clientWidth * ROTATE_SPEED;
  42229. };
  42230. TouchPanner.prototype.onTouchEnd_ = function(e) {
  42231. this.isTouching = false;
  42232. };
  42233. module.exports = TouchPanner;
  42234. },{"./math-util.js":15,"./util.js":23}],23:[function(_dereq_,module,exports){
  42235. /*
  42236. * Copyright 2015 Google Inc. All Rights Reserved.
  42237. * Licensed under the Apache License, Version 2.0 (the "License");
  42238. * you may not use this file except in compliance with the License.
  42239. * You may obtain a copy of the License at
  42240. *
  42241. * http://www.apache.org/licenses/LICENSE-2.0
  42242. *
  42243. * Unless required by applicable law or agreed to in writing, software
  42244. * distributed under the License is distributed on an "AS IS" BASIS,
  42245. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42246. * See the License for the specific language governing permissions and
  42247. * limitations under the License.
  42248. */
  42249. var objectAssign = _dereq_('object-assign');
  42250. var Util = window.Util || {};
  42251. Util.MIN_TIMESTEP = 0.001;
  42252. Util.MAX_TIMESTEP = 1;
  42253. Util.base64 = function(mimeType, base64) {
  42254. return 'data:' + mimeType + ';base64,' + base64;
  42255. };
  42256. Util.clamp = function(value, min, max) {
  42257. return Math.min(Math.max(min, value), max);
  42258. };
  42259. Util.lerp = function(a, b, t) {
  42260. return a + ((b - a) * t);
  42261. };
  42262. Util.isIOS = (function() {
  42263. var isIOS = /iPad|iPhone|iPod/.test(navigator.platform);
  42264. return function() {
  42265. return isIOS;
  42266. };
  42267. })();
  42268. Util.isWebViewAndroid = (function() {
  42269. var isWebViewAndroid = navigator.userAgent.indexOf('Version') !== -1 &&
  42270. navigator.userAgent.indexOf('Android') !== -1 &&
  42271. navigator.userAgent.indexOf('Chrome') !== -1;
  42272. return function() {
  42273. return isWebViewAndroid;
  42274. };
  42275. })();
  42276. Util.isSafari = (function() {
  42277. var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  42278. return function() {
  42279. return isSafari;
  42280. };
  42281. })();
  42282. Util.isFirefoxAndroid = (function() {
  42283. var isFirefoxAndroid = navigator.userAgent.indexOf('Firefox') !== -1 &&
  42284. navigator.userAgent.indexOf('Android') !== -1;
  42285. return function() {
  42286. return isFirefoxAndroid;
  42287. };
  42288. })();
  42289. Util.isLandscapeMode = function() {
  42290. return (window.orientation == 90 || window.orientation == -90);
  42291. };
  42292. // Helper method to validate the time steps of sensor timestamps.
  42293. Util.isTimestampDeltaValid = function(timestampDeltaS) {
  42294. if (isNaN(timestampDeltaS)) {
  42295. return false;
  42296. }
  42297. if (timestampDeltaS <= Util.MIN_TIMESTEP) {
  42298. return false;
  42299. }
  42300. if (timestampDeltaS > Util.MAX_TIMESTEP) {
  42301. return false;
  42302. }
  42303. return true;
  42304. };
  42305. Util.getScreenWidth = function() {
  42306. return Math.max(window.screen.width, window.screen.height) *
  42307. window.devicePixelRatio;
  42308. };
  42309. Util.getScreenHeight = function() {
  42310. return Math.min(window.screen.width, window.screen.height) *
  42311. window.devicePixelRatio;
  42312. };
  42313. Util.requestFullscreen = function(element) {
  42314. if (Util.isWebViewAndroid()) {
  42315. return false;
  42316. }
  42317. if (element.requestFullscreen) {
  42318. element.requestFullscreen();
  42319. } else if (element.webkitRequestFullscreen) {
  42320. element.webkitRequestFullscreen();
  42321. } else if (element.mozRequestFullScreen) {
  42322. element.mozRequestFullScreen();
  42323. } else if (element.msRequestFullscreen) {
  42324. element.msRequestFullscreen();
  42325. } else {
  42326. return false;
  42327. }
  42328. return true;
  42329. };
  42330. Util.exitFullscreen = function() {
  42331. if (document.exitFullscreen) {
  42332. document.exitFullscreen();
  42333. } else if (document.webkitExitFullscreen) {
  42334. document.webkitExitFullscreen();
  42335. } else if (document.mozCancelFullScreen) {
  42336. document.mozCancelFullScreen();
  42337. } else if (document.msExitFullscreen) {
  42338. document.msExitFullscreen();
  42339. } else {
  42340. return false;
  42341. }
  42342. return true;
  42343. };
  42344. Util.getFullscreenElement = function() {
  42345. return document.fullscreenElement ||
  42346. document.webkitFullscreenElement ||
  42347. document.mozFullScreenElement ||
  42348. document.msFullscreenElement;
  42349. };
  42350. Util.linkProgram = function(gl, vertexSource, fragmentSource, attribLocationMap) {
  42351. // No error checking for brevity.
  42352. var vertexShader = gl.createShader(gl.VERTEX_SHADER);
  42353. gl.shaderSource(vertexShader, vertexSource);
  42354. gl.compileShader(vertexShader);
  42355. var fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
  42356. gl.shaderSource(fragmentShader, fragmentSource);
  42357. gl.compileShader(fragmentShader);
  42358. var program = gl.createProgram();
  42359. gl.attachShader(program, vertexShader);
  42360. gl.attachShader(program, fragmentShader);
  42361. for (var attribName in attribLocationMap)
  42362. gl.bindAttribLocation(program, attribLocationMap[attribName], attribName);
  42363. gl.linkProgram(program);
  42364. gl.deleteShader(vertexShader);
  42365. gl.deleteShader(fragmentShader);
  42366. return program;
  42367. };
  42368. Util.getProgramUniforms = function(gl, program) {
  42369. var uniforms = {};
  42370. var uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  42371. var uniformName = '';
  42372. for (var i = 0; i < uniformCount; i++) {
  42373. var uniformInfo = gl.getActiveUniform(program, i);
  42374. uniformName = uniformInfo.name.replace('[0]', '');
  42375. uniforms[uniformName] = gl.getUniformLocation(program, uniformName);
  42376. }
  42377. return uniforms;
  42378. };
  42379. Util.orthoMatrix = function (out, left, right, bottom, top, near, far) {
  42380. var lr = 1 / (left - right),
  42381. bt = 1 / (bottom - top),
  42382. nf = 1 / (near - far);
  42383. out[0] = -2 * lr;
  42384. out[1] = 0;
  42385. out[2] = 0;
  42386. out[3] = 0;
  42387. out[4] = 0;
  42388. out[5] = -2 * bt;
  42389. out[6] = 0;
  42390. out[7] = 0;
  42391. out[8] = 0;
  42392. out[9] = 0;
  42393. out[10] = 2 * nf;
  42394. out[11] = 0;
  42395. out[12] = (left + right) * lr;
  42396. out[13] = (top + bottom) * bt;
  42397. out[14] = (far + near) * nf;
  42398. out[15] = 1;
  42399. return out;
  42400. };
  42401. Util.isMobile = function() {
  42402. var check = false;
  42403. (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);
  42404. return check;
  42405. };
  42406. Util.extend = objectAssign;
  42407. Util.safariCssSizeWorkaround = function(canvas) {
  42408. // TODO(smus): Remove this workaround when Safari for iOS is fixed.
  42409. // iOS only workaround (for https://bugs.webkit.org/show_bug.cgi?id=152556).
  42410. //
  42411. // "To the last I grapple with thee;
  42412. // from hell's heart I stab at thee;
  42413. // for hate's sake I spit my last breath at thee."
  42414. // -- Moby Dick, by Herman Melville
  42415. if (Util.isIOS()) {
  42416. var width = canvas.style.width;
  42417. var height = canvas.style.height;
  42418. canvas.style.width = (parseInt(width) + 1) + 'px';
  42419. canvas.style.height = (parseInt(height)) + 'px';
  42420. setTimeout(function() {
  42421. canvas.style.width = width;
  42422. canvas.style.height = height;
  42423. }, 100);
  42424. }
  42425. // Debug only.
  42426. window.Util = Util;
  42427. window.canvas = canvas;
  42428. };
  42429. Util.isDebug = function() {
  42430. return Util.getQueryParameter('debug');
  42431. };
  42432. Util.getQueryParameter = function(name) {
  42433. var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  42434. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  42435. results = regex.exec(location.search);
  42436. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  42437. };
  42438. Util.frameDataFromPose = (function() {
  42439. var piOver180 = Math.PI / 180.0;
  42440. var rad45 = Math.PI * 0.25;
  42441. // Borrowed from glMatrix.
  42442. function mat4_perspectiveFromFieldOfView(out, fov, near, far) {
  42443. var upTan = Math.tan(fov ? (fov.upDegrees * piOver180) : rad45),
  42444. downTan = Math.tan(fov ? (fov.downDegrees * piOver180) : rad45),
  42445. leftTan = Math.tan(fov ? (fov.leftDegrees * piOver180) : rad45),
  42446. rightTan = Math.tan(fov ? (fov.rightDegrees * piOver180) : rad45),
  42447. xScale = 2.0 / (leftTan + rightTan),
  42448. yScale = 2.0 / (upTan + downTan);
  42449. out[0] = xScale;
  42450. out[1] = 0.0;
  42451. out[2] = 0.0;
  42452. out[3] = 0.0;
  42453. out[4] = 0.0;
  42454. out[5] = yScale;
  42455. out[6] = 0.0;
  42456. out[7] = 0.0;
  42457. out[8] = -((leftTan - rightTan) * xScale * 0.5);
  42458. out[9] = ((upTan - downTan) * yScale * 0.5);
  42459. out[10] = far / (near - far);
  42460. out[11] = -1.0;
  42461. out[12] = 0.0;
  42462. out[13] = 0.0;
  42463. out[14] = (far * near) / (near - far);
  42464. out[15] = 0.0;
  42465. return out;
  42466. }
  42467. function mat4_fromRotationTranslation(out, q, v) {
  42468. // Quaternion math
  42469. var x = q[0], y = q[1], z = q[2], w = q[3],
  42470. x2 = x + x,
  42471. y2 = y + y,
  42472. z2 = z + z,
  42473. xx = x * x2,
  42474. xy = x * y2,
  42475. xz = x * z2,
  42476. yy = y * y2,
  42477. yz = y * z2,
  42478. zz = z * z2,
  42479. wx = w * x2,
  42480. wy = w * y2,
  42481. wz = w * z2;
  42482. out[0] = 1 - (yy + zz);
  42483. out[1] = xy + wz;
  42484. out[2] = xz - wy;
  42485. out[3] = 0;
  42486. out[4] = xy - wz;
  42487. out[5] = 1 - (xx + zz);
  42488. out[6] = yz + wx;
  42489. out[7] = 0;
  42490. out[8] = xz + wy;
  42491. out[9] = yz - wx;
  42492. out[10] = 1 - (xx + yy);
  42493. out[11] = 0;
  42494. out[12] = v[0];
  42495. out[13] = v[1];
  42496. out[14] = v[2];
  42497. out[15] = 1;
  42498. return out;
  42499. };
  42500. function mat4_translate(out, a, v) {
  42501. var x = v[0], y = v[1], z = v[2],
  42502. a00, a01, a02, a03,
  42503. a10, a11, a12, a13,
  42504. a20, a21, a22, a23;
  42505. if (a === out) {
  42506. out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
  42507. out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
  42508. out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
  42509. out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
  42510. } else {
  42511. a00 = a[0]; a01 = a[1]; a02 = a[2]; a03 = a[3];
  42512. a10 = a[4]; a11 = a[5]; a12 = a[6]; a13 = a[7];
  42513. a20 = a[8]; a21 = a[9]; a22 = a[10]; a23 = a[11];
  42514. out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a03;
  42515. out[4] = a10; out[5] = a11; out[6] = a12; out[7] = a13;
  42516. out[8] = a20; out[9] = a21; out[10] = a22; out[11] = a23;
  42517. out[12] = a00 * x + a10 * y + a20 * z + a[12];
  42518. out[13] = a01 * x + a11 * y + a21 * z + a[13];
  42519. out[14] = a02 * x + a12 * y + a22 * z + a[14];
  42520. out[15] = a03 * x + a13 * y + a23 * z + a[15];
  42521. }
  42522. return out;
  42523. };
  42524. function mat4_invert(out, a) {
  42525. var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3],
  42526. a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7],
  42527. a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11],
  42528. a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15],
  42529. b00 = a00 * a11 - a01 * a10,
  42530. b01 = a00 * a12 - a02 * a10,
  42531. b02 = a00 * a13 - a03 * a10,
  42532. b03 = a01 * a12 - a02 * a11,
  42533. b04 = a01 * a13 - a03 * a11,
  42534. b05 = a02 * a13 - a03 * a12,
  42535. b06 = a20 * a31 - a21 * a30,
  42536. b07 = a20 * a32 - a22 * a30,
  42537. b08 = a20 * a33 - a23 * a30,
  42538. b09 = a21 * a32 - a22 * a31,
  42539. b10 = a21 * a33 - a23 * a31,
  42540. b11 = a22 * a33 - a23 * a32,
  42541. // Calculate the determinant
  42542. det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
  42543. if (!det) {
  42544. return null;
  42545. }
  42546. det = 1.0 / det;
  42547. out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
  42548. out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
  42549. out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
  42550. out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
  42551. out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
  42552. out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
  42553. out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
  42554. out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
  42555. out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
  42556. out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
  42557. out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
  42558. out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
  42559. out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
  42560. out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
  42561. out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
  42562. out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
  42563. return out;
  42564. };
  42565. var defaultOrientation = new Float32Array([0, 0, 0, 1]);
  42566. var defaultPosition = new Float32Array([0, 0, 0]);
  42567. function updateEyeMatrices(projection, view, pose, parameters, vrDisplay) {
  42568. mat4_perspectiveFromFieldOfView(projection, parameters ? parameters.fieldOfView : null, vrDisplay.depthNear, vrDisplay.depthFar);
  42569. var orientation = pose.orientation || defaultOrientation;
  42570. var position = pose.position || defaultPosition;
  42571. mat4_fromRotationTranslation(view, orientation, position);
  42572. if (parameters)
  42573. mat4_translate(view, view, parameters.offset);
  42574. mat4_invert(view, view);
  42575. }
  42576. return function(frameData, pose, vrDisplay) {
  42577. if (!frameData || !pose)
  42578. return false;
  42579. frameData.pose = pose;
  42580. frameData.timestamp = pose.timestamp;
  42581. updateEyeMatrices(
  42582. frameData.leftProjectionMatrix, frameData.leftViewMatrix,
  42583. pose, vrDisplay.getEyeParameters("left"), vrDisplay);
  42584. updateEyeMatrices(
  42585. frameData.rightProjectionMatrix, frameData.rightViewMatrix,
  42586. pose, vrDisplay.getEyeParameters("right"), vrDisplay);
  42587. return true;
  42588. };
  42589. })();
  42590. Util.isInsideCrossDomainIFrame = function() {
  42591. var isFramed = (window.self !== window.top);
  42592. var refDomain = Util.getDomainFromUrl(document.referrer);
  42593. var thisDomain = Util.getDomainFromUrl(window.location.href);
  42594. return isFramed && (refDomain !== thisDomain);
  42595. };
  42596. // From http://stackoverflow.com/a/23945027.
  42597. Util.getDomainFromUrl = function(url) {
  42598. var domain;
  42599. // Find & remove protocol (http, ftp, etc.) and get domain.
  42600. if (url.indexOf("://") > -1) {
  42601. domain = url.split('/')[2];
  42602. }
  42603. else {
  42604. domain = url.split('/')[0];
  42605. }
  42606. //find & remove port number
  42607. domain = domain.split(':')[0];
  42608. return domain;
  42609. }
  42610. module.exports = Util;
  42611. },{"object-assign":2}],24:[function(_dereq_,module,exports){
  42612. /*
  42613. * Copyright 2015 Google Inc. All Rights Reserved.
  42614. * Licensed under the Apache License, Version 2.0 (the "License");
  42615. * you may not use this file except in compliance with the License.
  42616. * You may obtain a copy of the License at
  42617. *
  42618. * http://www.apache.org/licenses/LICENSE-2.0
  42619. *
  42620. * Unless required by applicable law or agreed to in writing, software
  42621. * distributed under the License is distributed on an "AS IS" BASIS,
  42622. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42623. * See the License for the specific language governing permissions and
  42624. * limitations under the License.
  42625. */
  42626. var DeviceInfo = _dereq_('./device-info.js');
  42627. var EventEmitter3 = _dereq_('eventemitter3');
  42628. var Util = _dereq_('./util.js');
  42629. var DEFAULT_VIEWER = 'CardboardV1';
  42630. var VIEWER_KEY = 'WEBVR_CARDBOARD_VIEWER';
  42631. var CLASS_NAME = 'webvr-polyfill-viewer-selector';
  42632. /**
  42633. * Creates a viewer selector with the options specified. Supports being shown
  42634. * and hidden. Generates events when viewer parameters change. Also supports
  42635. * saving the currently selected index in localStorage.
  42636. */
  42637. function ViewerSelector() {
  42638. // Try to load the selected key from local storage. If none exists, use the
  42639. // default key.
  42640. try {
  42641. this.selectedKey = localStorage.getItem(VIEWER_KEY) || DEFAULT_VIEWER;
  42642. } catch (error) {
  42643. console.error('Failed to load viewer profile: %s', error);
  42644. }
  42645. this.dialog = this.createDialog_(DeviceInfo.Viewers);
  42646. this.root = null;
  42647. }
  42648. ViewerSelector.prototype = new EventEmitter3();
  42649. ViewerSelector.prototype.show = function(root) {
  42650. this.root = root;
  42651. root.appendChild(this.dialog);
  42652. // Ensure the currently selected item is checked.
  42653. var selected = this.dialog.querySelector('#' + this.selectedKey);
  42654. selected.checked = true;
  42655. // Show the UI.
  42656. this.dialog.style.display = 'block';
  42657. };
  42658. ViewerSelector.prototype.hide = function() {
  42659. if (this.root && this.root.contains(this.dialog)) {
  42660. this.root.removeChild(this.dialog);
  42661. }
  42662. this.dialog.style.display = 'none';
  42663. };
  42664. ViewerSelector.prototype.getCurrentViewer = function() {
  42665. return DeviceInfo.Viewers[this.selectedKey];
  42666. };
  42667. ViewerSelector.prototype.getSelectedKey_ = function() {
  42668. var input = this.dialog.querySelector('input[name=field]:checked');
  42669. if (input) {
  42670. return input.id;
  42671. }
  42672. return null;
  42673. };
  42674. ViewerSelector.prototype.onSave_ = function() {
  42675. this.selectedKey = this.getSelectedKey_();
  42676. if (!this.selectedKey || !DeviceInfo.Viewers[this.selectedKey]) {
  42677. console.error('ViewerSelector.onSave_: this should never happen!');
  42678. return;
  42679. }
  42680. this.emit('change', DeviceInfo.Viewers[this.selectedKey]);
  42681. // Attempt to save the viewer profile, but fails in private mode.
  42682. try {
  42683. localStorage.setItem(VIEWER_KEY, this.selectedKey);
  42684. } catch(error) {
  42685. console.error('Failed to save viewer profile: %s', error);
  42686. }
  42687. this.hide();
  42688. };
  42689. /**
  42690. * Creates the dialog.
  42691. */
  42692. ViewerSelector.prototype.createDialog_ = function(options) {
  42693. var container = document.createElement('div');
  42694. container.classList.add(CLASS_NAME);
  42695. container.style.display = 'none';
  42696. // Create an overlay that dims the background, and which goes away when you
  42697. // tap it.
  42698. var overlay = document.createElement('div');
  42699. var s = overlay.style;
  42700. s.position = 'fixed';
  42701. s.left = 0;
  42702. s.top = 0;
  42703. s.width = '100%';
  42704. s.height = '100%';
  42705. s.background = 'rgba(0, 0, 0, 0.3)';
  42706. overlay.addEventListener('click', this.hide.bind(this));
  42707. var width = 280;
  42708. var dialog = document.createElement('div');
  42709. var s = dialog.style;
  42710. s.boxSizing = 'border-box';
  42711. s.position = 'fixed';
  42712. s.top = '24px';
  42713. s.left = '50%';
  42714. s.marginLeft = (-width/2) + 'px';
  42715. s.width = width + 'px';
  42716. s.padding = '24px';
  42717. s.overflow = 'hidden';
  42718. s.background = '#fafafa';
  42719. s.fontFamily = "'Roboto', sans-serif";
  42720. s.boxShadow = '0px 5px 20px #666';
  42721. dialog.appendChild(this.createH1_('Select your viewer'));
  42722. for (var id in options) {
  42723. dialog.appendChild(this.createChoice_(id, options[id].label));
  42724. }
  42725. dialog.appendChild(this.createButton_('Save', this.onSave_.bind(this)));
  42726. container.appendChild(overlay);
  42727. container.appendChild(dialog);
  42728. return container;
  42729. };
  42730. ViewerSelector.prototype.createH1_ = function(name) {
  42731. var h1 = document.createElement('h1');
  42732. var s = h1.style;
  42733. s.color = 'black';
  42734. s.fontSize = '20px';
  42735. s.fontWeight = 'bold';
  42736. s.marginTop = 0;
  42737. s.marginBottom = '24px';
  42738. h1.innerHTML = name;
  42739. return h1;
  42740. };
  42741. ViewerSelector.prototype.createChoice_ = function(id, name) {
  42742. /*
  42743. <div class="choice">
  42744. <input id="v1" type="radio" name="field" value="v1">
  42745. <label for="v1">Cardboard V1</label>
  42746. </div>
  42747. */
  42748. var div = document.createElement('div');
  42749. div.style.marginTop = '8px';
  42750. div.style.color = 'black';
  42751. var input = document.createElement('input');
  42752. input.style.fontSize = '30px';
  42753. input.setAttribute('id', id);
  42754. input.setAttribute('type', 'radio');
  42755. input.setAttribute('value', id);
  42756. input.setAttribute('name', 'field');
  42757. var label = document.createElement('label');
  42758. label.style.marginLeft = '4px';
  42759. label.setAttribute('for', id);
  42760. label.innerHTML = name;
  42761. div.appendChild(input);
  42762. div.appendChild(label);
  42763. return div;
  42764. };
  42765. ViewerSelector.prototype.createButton_ = function(label, onclick) {
  42766. var button = document.createElement('button');
  42767. button.innerHTML = label;
  42768. var s = button.style;
  42769. s.float = 'right';
  42770. s.textTransform = 'uppercase';
  42771. s.color = '#1094f7';
  42772. s.fontSize = '14px';
  42773. s.letterSpacing = 0;
  42774. s.border = 0;
  42775. s.background = 'none';
  42776. s.marginTop = '16px';
  42777. button.addEventListener('click', onclick);
  42778. return button;
  42779. };
  42780. module.exports = ViewerSelector;
  42781. },{"./device-info.js":8,"./util.js":23,"eventemitter3":1}],25:[function(_dereq_,module,exports){
  42782. /*
  42783. * Copyright 2015 Google Inc. All Rights Reserved.
  42784. * Licensed under the Apache License, Version 2.0 (the "License");
  42785. * you may not use this file except in compliance with the License.
  42786. * You may obtain a copy of the License at
  42787. *
  42788. * http://www.apache.org/licenses/LICENSE-2.0
  42789. *
  42790. * Unless required by applicable law or agreed to in writing, software
  42791. * distributed under the License is distributed on an "AS IS" BASIS,
  42792. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42793. * See the License for the specific language governing permissions and
  42794. * limitations under the License.
  42795. */
  42796. var Util = _dereq_('./util.js');
  42797. /**
  42798. * Android and iOS compatible wakelock implementation.
  42799. *
  42800. * Refactored thanks to dkovalev@.
  42801. */
  42802. function AndroidWakeLock() {
  42803. var video = document.createElement('video');
  42804. video.addEventListener('ended', function() {
  42805. video.play();
  42806. });
  42807. this.request = function() {
  42808. if (video.paused) {
  42809. // Base64 version of videos_src/no-sleep-120s.mp4.
  42810. video.src = Util.base64('video/mp4', 'AAAAGGZ0eXBpc29tAAAAAG1wNDFhdmMxAAAIA21vb3YAAABsbXZoZAAAAADSa9v60mvb+gABX5AAlw/gAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAdkdHJhawAAAFx0a2hkAAAAAdJr2/rSa9v6AAAAAQAAAAAAlw/gAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAQAAAAHAAAAAAAJGVkdHMAAAAcZWxzdAAAAAAAAAABAJcP4AAAAAAAAQAAAAAG3G1kaWEAAAAgbWRoZAAAAADSa9v60mvb+gAPQkAGjneAFccAAAAAAC1oZGxyAAAAAAAAAAB2aWRlAAAAAAAAAAAAAAAAVmlkZW9IYW5kbGVyAAAABodtaW5mAAAAFHZtaGQAAAABAAAAAAAAAAAAAAAkZGluZgAAABxkcmVmAAAAAAAAAAEAAAAMdXJsIAAAAAEAAAZHc3RibAAAAJdzdHNkAAAAAAAAAAEAAACHYXZjMQAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAAAMABwASAAAAEgAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABj//wAAADFhdmNDAWQAC//hABlnZAALrNlfllw4QAAAAwBAAAADAKPFCmWAAQAFaOvssiwAAAAYc3R0cwAAAAAAAAABAAAAbgAPQkAAAAAUc3RzcwAAAAAAAAABAAAAAQAAA4BjdHRzAAAAAAAAAG4AAAABAD0JAAAAAAEAehIAAAAAAQA9CQAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEATEtAAAAAAQAehIAAAAABAAAAAAAAAAEAD0JAAAAAAQBMS0AAAAABAB6EgAAAAAEAAAAAAAAAAQAPQkAAAAABAExLQAAAAAEAHoSAAAAAAQAAAAAAAAABAA9CQAAAAAEALcbAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAABuAAAAAQAAAcxzdHN6AAAAAAAAAAAAAABuAAADCQAAABgAAAAOAAAADgAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABIAAAAOAAAADAAAAAwAAAASAAAADgAAAAwAAAAMAAAAEgAAAA4AAAAMAAAADAAAABMAAAAUc3RjbwAAAAAAAAABAAAIKwAAACt1ZHRhAAAAI6llbmMAFwAAdmxjIDIuMi4xIHN0cmVhbSBvdXRwdXQAAAAId2lkZQAACRRtZGF0AAACrgX//6vcRem95tlIt5Ys2CDZI+7veDI2NCAtIGNvcmUgMTQyIC0gSC4yNjQvTVBFRy00IEFWQyBjb2RlYyAtIENvcHlsZWZ0IDIwMDMtMjAxNCAtIGh0dHA6Ly93d3cudmlkZW9sYW4ub3JnL3gyNjQuaHRtbCAtIG9wdGlvbnM6IGNhYmFjPTEgcmVmPTMgZGVibG9jaz0xOjA6MCBhbmFseXNlPTB4MzoweDEzIG1lPWhleCBzdWJtZT03IHBzeT0xIHBzeV9yZD0xLjAwOjAuMDAgbWl4ZWRfcmVmPTEgbWVfcmFuZ2U9MTYgY2hyb21hX21lPTEgdHJlbGxpcz0xIDh4OGRjdD0xIGNxbT0wIGRlYWR6b25lPTIxLDExIGZhc3RfcHNraXA9MSBjaHJvbWFfcXBfb2Zmc2V0PS0yIHRocmVhZHM9MTIgbG9va2FoZWFkX3RocmVhZHM9MSBzbGljZWRfdGhyZWFkcz0wIG5yPTAgZGVjaW1hdGU9MSBpbnRlcmxhY2VkPTAgYmx1cmF5X2NvbXBhdD0wIGNvbnN0cmFpbmVkX2ludHJhPTAgYmZyYW1lcz0zIGJfcHlyYW1pZD0yIGJfYWRhcHQ9MSBiX2JpYXM9MCBkaXJlY3Q9MSB3ZWlnaHRiPTEgb3Blbl9nb3A9MCB3ZWlnaHRwPTIga2V5aW50PTI1MCBrZXlpbnRfbWluPTEgc2NlbmVjdXQ9NDAgaW50cmFfcmVmcmVzaD0wIHJjX2xvb2thaGVhZD00MCByYz1hYnIgbWJ0cmVlPTEgYml0cmF0ZT0xMDAgcmF0ZXRvbD0xLjAgcWNvbXA9MC42MCBxcG1pbj0xMCBxcG1heD01MSBxcHN0ZXA9NCBpcF9yYXRpbz0xLjQwIGFxPTE6MS4wMACAAAAAU2WIhAAQ/8ltlOe+cTZuGkKg+aRtuivcDZ0pBsfsEi9p/i1yU9DxS2lq4dXTinViF1URBKXgnzKBd/Uh1bkhHtMrwrRcOJslD01UB+fyaL6ef+DBAAAAFEGaJGxBD5B+v+a+4QqF3MgBXz9MAAAACkGeQniH/+94r6EAAAAKAZ5hdEN/8QytwAAAAAgBnmNqQ3/EgQAAAA5BmmhJqEFomUwIIf/+4QAAAApBnoZFESw//76BAAAACAGepXRDf8SBAAAACAGep2pDf8SAAAAADkGarEmoQWyZTAgh//7gAAAACkGeykUVLD//voEAAAAIAZ7pdEN/xIAAAAAIAZ7rakN/xIAAAAAOQZrwSahBbJlMCCH//uEAAAAKQZ8ORRUsP/++gQAAAAgBny10Q3/EgQAAAAgBny9qQ3/EgAAAAA5BmzRJqEFsmUwIIf/+4AAAAApBn1JFFSw//76BAAAACAGfcXRDf8SAAAAACAGfc2pDf8SAAAAADkGbeEmoQWyZTAgh//7hAAAACkGflkUVLD//voAAAAAIAZ+1dEN/xIEAAAAIAZ+3akN/xIEAAAAOQZu8SahBbJlMCCH//uAAAAAKQZ/aRRUsP/++gQAAAAgBn/l0Q3/EgAAAAAgBn/tqQ3/EgQAAAA5Bm+BJqEFsmUwIIf/+4QAAAApBnh5FFSw//76AAAAACAGePXRDf8SAAAAACAGeP2pDf8SBAAAADkGaJEmoQWyZTAgh//7gAAAACkGeQkUVLD//voEAAAAIAZ5hdEN/xIAAAAAIAZ5jakN/xIEAAAAOQZpoSahBbJlMCCH//uEAAAAKQZ6GRRUsP/++gQAAAAgBnqV0Q3/EgQAAAAgBnqdqQ3/EgAAAAA5BmqxJqEFsmUwIIf/+4AAAAApBnspFFSw//76BAAAACAGe6XRDf8SAAAAACAGe62pDf8SAAAAADkGa8EmoQWyZTAgh//7hAAAACkGfDkUVLD//voEAAAAIAZ8tdEN/xIEAAAAIAZ8vakN/xIAAAAAOQZs0SahBbJlMCCH//uAAAAAKQZ9SRRUsP/++gQAAAAgBn3F0Q3/EgAAAAAgBn3NqQ3/EgAAAAA5Bm3hJqEFsmUwIIf/+4QAAAApBn5ZFFSw//76AAAAACAGftXRDf8SBAAAACAGft2pDf8SBAAAADkGbvEmoQWyZTAgh//7gAAAACkGf2kUVLD//voEAAAAIAZ/5dEN/xIAAAAAIAZ/7akN/xIEAAAAOQZvgSahBbJlMCCH//uEAAAAKQZ4eRRUsP/++gAAAAAgBnj10Q3/EgAAAAAgBnj9qQ3/EgQAAAA5BmiRJqEFsmUwIIf/+4AAAAApBnkJFFSw//76BAAAACAGeYXRDf8SAAAAACAGeY2pDf8SBAAAADkGaaEmoQWyZTAgh//7hAAAACkGehkUVLD//voEAAAAIAZ6ldEN/xIEAAAAIAZ6nakN/xIAAAAAOQZqsSahBbJlMCCH//uAAAAAKQZ7KRRUsP/++gQAAAAgBnul0Q3/EgAAAAAgBnutqQ3/EgAAAAA5BmvBJqEFsmUwIIf/+4QAAAApBnw5FFSw//76BAAAACAGfLXRDf8SBAAAACAGfL2pDf8SAAAAADkGbNEmoQWyZTAgh//7gAAAACkGfUkUVLD//voEAAAAIAZ9xdEN/xIAAAAAIAZ9zakN/xIAAAAAOQZt4SahBbJlMCCH//uEAAAAKQZ+WRRUsP/++gAAAAAgBn7V0Q3/EgQAAAAgBn7dqQ3/EgQAAAA5Bm7xJqEFsmUwIIf/+4AAAAApBn9pFFSw//76BAAAACAGf+XRDf8SAAAAACAGf+2pDf8SBAAAADkGb4EmoQWyZTAgh//7hAAAACkGeHkUVLD//voAAAAAIAZ49dEN/xIAAAAAIAZ4/akN/xIEAAAAOQZokSahBbJlMCCH//uAAAAAKQZ5CRRUsP/++gQAAAAgBnmF0Q3/EgAAAAAgBnmNqQ3/EgQAAAA5BmmhJqEFsmUwIIf/+4QAAAApBnoZFFSw//76BAAAACAGepXRDf8SBAAAACAGep2pDf8SAAAAADkGarEmoQWyZTAgh//7gAAAACkGeykUVLD//voEAAAAIAZ7pdEN/xIAAAAAIAZ7rakN/xIAAAAAPQZruSahBbJlMFEw3//7B');
  42811. video.play();
  42812. }
  42813. };
  42814. this.release = function() {
  42815. video.pause();
  42816. video.src = '';
  42817. };
  42818. }
  42819. function iOSWakeLock() {
  42820. var timer = null;
  42821. this.request = function() {
  42822. if (!timer) {
  42823. timer = setInterval(function() {
  42824. window.location = window.location;
  42825. setTimeout(window.stop, 0);
  42826. }, 30000);
  42827. }
  42828. }
  42829. this.release = function() {
  42830. if (timer) {
  42831. clearInterval(timer);
  42832. timer = null;
  42833. }
  42834. }
  42835. }
  42836. function getWakeLock() {
  42837. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  42838. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  42839. return iOSWakeLock;
  42840. } else {
  42841. return AndroidWakeLock;
  42842. }
  42843. }
  42844. module.exports = getWakeLock();
  42845. },{"./util.js":23}],26:[function(_dereq_,module,exports){
  42846. /*
  42847. * Copyright 2015 Google Inc. All Rights Reserved.
  42848. * Licensed under the Apache License, Version 2.0 (the "License");
  42849. * you may not use this file except in compliance with the License.
  42850. * You may obtain a copy of the License at
  42851. *
  42852. * http://www.apache.org/licenses/LICENSE-2.0
  42853. *
  42854. * Unless required by applicable law or agreed to in writing, software
  42855. * distributed under the License is distributed on an "AS IS" BASIS,
  42856. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  42857. * See the License for the specific language governing permissions and
  42858. * limitations under the License.
  42859. */
  42860. var Util = _dereq_('./util.js');
  42861. var CardboardVRDisplay = _dereq_('./cardboard-vr-display.js');
  42862. var MouseKeyboardVRDisplay = _dereq_('./mouse-keyboard-vr-display.js');
  42863. // Uncomment to add positional tracking via webcam.
  42864. //var WebcamPositionSensorVRDevice = require('./webcam-position-sensor-vr-device.js');
  42865. var VRDisplay = _dereq_('./base.js').VRDisplay;
  42866. var VRFrameData = _dereq_('./base.js').VRFrameData;
  42867. var HMDVRDevice = _dereq_('./base.js').HMDVRDevice;
  42868. var PositionSensorVRDevice = _dereq_('./base.js').PositionSensorVRDevice;
  42869. var VRDisplayHMDDevice = _dereq_('./display-wrappers.js').VRDisplayHMDDevice;
  42870. var VRDisplayPositionSensorDevice = _dereq_('./display-wrappers.js').VRDisplayPositionSensorDevice;
  42871. function WebVRPolyfill() {
  42872. this.displays = [];
  42873. this.devices = []; // For deprecated objects
  42874. this.devicesPopulated = false;
  42875. this.nativeWebVRAvailable = this.isWebVRAvailable();
  42876. this.nativeLegacyWebVRAvailable = this.isDeprecatedWebVRAvailable();
  42877. this.nativeGetVRDisplaysFunc = this.nativeWebVRAvailable ?
  42878. navigator.getVRDisplays :
  42879. null;
  42880. if (!this.nativeLegacyWebVRAvailable) {
  42881. this.enablePolyfill();
  42882. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42883. this.enableDeprecatedPolyfill();
  42884. }
  42885. }
  42886. // Put a shim in place to update the API to 1.1 if needed.
  42887. InstallWebVRSpecShim();
  42888. }
  42889. WebVRPolyfill.prototype.isWebVRAvailable = function() {
  42890. return ('getVRDisplays' in navigator);
  42891. };
  42892. WebVRPolyfill.prototype.isDeprecatedWebVRAvailable = function() {
  42893. return ('getVRDevices' in navigator) || ('mozGetVRDevices' in navigator);
  42894. };
  42895. WebVRPolyfill.prototype.populateDevices = function() {
  42896. if (this.devicesPopulated) {
  42897. return;
  42898. }
  42899. // Initialize our virtual VR devices.
  42900. var vrDisplay = null;
  42901. // Add a Cardboard VRDisplay on compatible mobile devices
  42902. if (this.isCardboardCompatible()) {
  42903. vrDisplay = new CardboardVRDisplay();
  42904. this.displays.push(vrDisplay);
  42905. // For backwards compatibility
  42906. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42907. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42908. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42909. }
  42910. }
  42911. // Add a Mouse and Keyboard driven VRDisplay for desktops/laptops
  42912. if (!this.isMobile() && !WebVRConfig.MOUSE_KEYBOARD_CONTROLS_DISABLED) {
  42913. vrDisplay = new MouseKeyboardVRDisplay();
  42914. this.displays.push(vrDisplay);
  42915. // For backwards compatibility
  42916. if (WebVRConfig.ENABLE_DEPRECATED_API) {
  42917. this.devices.push(new VRDisplayHMDDevice(vrDisplay));
  42918. this.devices.push(new VRDisplayPositionSensorDevice(vrDisplay));
  42919. }
  42920. }
  42921. // Uncomment to add positional tracking via webcam.
  42922. //if (!this.isMobile() && WebVRConfig.ENABLE_DEPRECATED_API) {
  42923. // positionDevice = new WebcamPositionSensorVRDevice();
  42924. // this.devices.push(positionDevice);
  42925. //}
  42926. this.devicesPopulated = true;
  42927. };
  42928. WebVRPolyfill.prototype.enablePolyfill = function() {
  42929. // Provide navigator.getVRDisplays.
  42930. navigator.getVRDisplays = this.getVRDisplays.bind(this);
  42931. // Provide the VRDisplay object.
  42932. window.VRDisplay = VRDisplay;
  42933. // Provide navigator.vrEnabled.
  42934. var self = this;
  42935. Object.defineProperty(navigator, 'vrEnabled', {
  42936. get: function () {
  42937. return self.isCardboardCompatible() &&
  42938. (self.isFullScreenAvailable() || Util.isIOS());
  42939. }
  42940. });
  42941. if (!'VRFrameData' in window) {
  42942. // Provide the VRFrameData object.
  42943. window.VRFrameData = VRFrameData;
  42944. }
  42945. };
  42946. WebVRPolyfill.prototype.enableDeprecatedPolyfill = function() {
  42947. // Provide navigator.getVRDevices.
  42948. navigator.getVRDevices = this.getVRDevices.bind(this);
  42949. // Provide the CardboardHMDVRDevice and PositionSensorVRDevice objects.
  42950. window.HMDVRDevice = HMDVRDevice;
  42951. window.PositionSensorVRDevice = PositionSensorVRDevice;
  42952. };
  42953. WebVRPolyfill.prototype.getVRDisplays = function() {
  42954. this.populateDevices();
  42955. var polyfillDisplays = this.displays;
  42956. if (this.nativeWebVRAvailable) {
  42957. return this.nativeGetVRDisplaysFunc.call(navigator).then(function(nativeDisplays) {
  42958. if (WebVRConfig.ALWAYS_APPEND_POLYFILL_DISPLAY) {
  42959. return nativeDisplays.concat(polyfillDisplays);
  42960. } else {
  42961. return nativeDisplays.length > 0 ? nativeDisplays : polyfillDisplays;
  42962. }
  42963. });
  42964. } else {
  42965. return new Promise(function(resolve, reject) {
  42966. try {
  42967. resolve(polyfillDisplays);
  42968. } catch (e) {
  42969. reject(e);
  42970. }
  42971. });
  42972. }
  42973. };
  42974. WebVRPolyfill.prototype.getVRDevices = function() {
  42975. console.warn('getVRDevices is deprecated. Please update your code to use getVRDisplays instead.');
  42976. var self = this;
  42977. return new Promise(function(resolve, reject) {
  42978. try {
  42979. if (!self.devicesPopulated) {
  42980. if (self.nativeWebVRAvailable) {
  42981. return navigator.getVRDisplays(function(displays) {
  42982. for (var i = 0; i < displays.length; ++i) {
  42983. self.devices.push(new VRDisplayHMDDevice(displays[i]));
  42984. self.devices.push(new VRDisplayPositionSensorDevice(displays[i]));
  42985. }
  42986. self.devicesPopulated = true;
  42987. resolve(self.devices);
  42988. }, reject);
  42989. }
  42990. if (self.nativeLegacyWebVRAvailable) {
  42991. return (navigator.getVRDDevices || navigator.mozGetVRDevices)(function(devices) {
  42992. for (var i = 0; i < devices.length; ++i) {
  42993. if (devices[i] instanceof HMDVRDevice) {
  42994. self.devices.push(devices[i]);
  42995. }
  42996. if (devices[i] instanceof PositionSensorVRDevice) {
  42997. self.devices.push(devices[i]);
  42998. }
  42999. }
  43000. self.devicesPopulated = true;
  43001. resolve(self.devices);
  43002. }, reject);
  43003. }
  43004. }
  43005. self.populateDevices();
  43006. resolve(self.devices);
  43007. } catch (e) {
  43008. reject(e);
  43009. }
  43010. });
  43011. };
  43012. /**
  43013. * Determine if a device is mobile.
  43014. */
  43015. WebVRPolyfill.prototype.isMobile = function() {
  43016. return /Android/i.test(navigator.userAgent) ||
  43017. /iPhone|iPad|iPod/i.test(navigator.userAgent);
  43018. };
  43019. WebVRPolyfill.prototype.isCardboardCompatible = function() {
  43020. // For now, support all iOS and Android devices.
  43021. // Also enable the WebVRConfig.FORCE_VR flag for debugging.
  43022. return this.isMobile() || WebVRConfig.FORCE_ENABLE_VR;
  43023. };
  43024. WebVRPolyfill.prototype.isFullScreenAvailable = function() {
  43025. return (document.fullscreenEnabled ||
  43026. document.mozFullScreenEnabled ||
  43027. document.webkitFullscreenEnabled ||
  43028. false);
  43029. };
  43030. // Installs a shim that updates a WebVR 1.0 spec implementation to WebVR 1.1
  43031. function InstallWebVRSpecShim() {
  43032. if ('VRDisplay' in window && !('VRFrameData' in window)) {
  43033. // Provide the VRFrameData object.
  43034. window.VRFrameData = VRFrameData;
  43035. // A lot of Chrome builds don't have depthNear and depthFar, even
  43036. // though they're in the WebVR 1.0 spec. Patch them in if they're not present.
  43037. if(!('depthNear' in window.VRDisplay.prototype)) {
  43038. window.VRDisplay.prototype.depthNear = 0.01;
  43039. }
  43040. if(!('depthFar' in window.VRDisplay.prototype)) {
  43041. window.VRDisplay.prototype.depthFar = 10000.0;
  43042. }
  43043. window.VRDisplay.prototype.getFrameData = function(frameData) {
  43044. return Util.frameDataFromPose(frameData, this.getPose(), this);
  43045. }
  43046. }
  43047. };
  43048. module.exports.WebVRPolyfill = WebVRPolyfill;
  43049. },{"./base.js":3,"./cardboard-vr-display.js":6,"./display-wrappers.js":9,"./mouse-keyboard-vr-display.js":16,"./util.js":23}]},{},[14])(14)
  43050. });
  43051. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  43052. },{}],51:[function(_dereq_,module,exports){
  43053. var newline = /\n/
  43054. var newlineChar = '\n'
  43055. var whitespace = /\s/
  43056. module.exports = function(text, opt) {
  43057. var lines = module.exports.lines(text, opt)
  43058. return lines.map(function(line) {
  43059. return text.substring(line.start, line.end)
  43060. }).join('\n')
  43061. }
  43062. module.exports.lines = function wordwrap(text, opt) {
  43063. opt = opt||{}
  43064. //zero width results in nothing visible
  43065. if (opt.width === 0 && opt.mode !== 'nowrap')
  43066. return []
  43067. text = text||''
  43068. var width = typeof opt.width === 'number' ? opt.width : Number.MAX_VALUE
  43069. var start = Math.max(0, opt.start||0)
  43070. var end = typeof opt.end === 'number' ? opt.end : text.length
  43071. var mode = opt.mode
  43072. var measure = opt.measure || monospace
  43073. if (mode === 'pre')
  43074. return pre(measure, text, start, end, width)
  43075. else
  43076. return greedy(measure, text, start, end, width, mode)
  43077. }
  43078. function idxOf(text, chr, start, end) {
  43079. var idx = text.indexOf(chr, start)
  43080. if (idx === -1 || idx > end)
  43081. return end
  43082. return idx
  43083. }
  43084. function isWhitespace(chr) {
  43085. return whitespace.test(chr)
  43086. }
  43087. function pre(measure, text, start, end, width) {
  43088. var lines = []
  43089. var lineStart = start
  43090. for (var i=start; i<end && i<text.length; i++) {
  43091. var chr = text.charAt(i)
  43092. var isNewline = newline.test(chr)
  43093. //If we've reached a newline, then step down a line
  43094. //Or if we've reached the EOF
  43095. if (isNewline || i===end-1) {
  43096. var lineEnd = isNewline ? i : i+1
  43097. var measured = measure(text, lineStart, lineEnd, width)
  43098. lines.push(measured)
  43099. lineStart = i+1
  43100. }
  43101. }
  43102. return lines
  43103. }
  43104. function greedy(measure, text, start, end, width, mode) {
  43105. //A greedy word wrapper based on LibGDX algorithm
  43106. //https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/BitmapFontCache.java
  43107. var lines = []
  43108. var testWidth = width
  43109. //if 'nowrap' is specified, we only wrap on newline chars
  43110. if (mode === 'nowrap')
  43111. testWidth = Number.MAX_VALUE
  43112. while (start < end && start < text.length) {
  43113. //get next newline position
  43114. var newLine = idxOf(text, newlineChar, start, end)
  43115. //eat whitespace at start of line
  43116. while (start < newLine) {
  43117. if (!isWhitespace( text.charAt(start) ))
  43118. break
  43119. start++
  43120. }
  43121. //determine visible # of glyphs for the available width
  43122. var measured = measure(text, start, newLine, testWidth)
  43123. var lineEnd = start + (measured.end-measured.start)
  43124. var nextStart = lineEnd + newlineChar.length
  43125. //if we had to cut the line before the next newline...
  43126. if (lineEnd < newLine) {
  43127. //find char to break on
  43128. while (lineEnd > start) {
  43129. if (isWhitespace(text.charAt(lineEnd)))
  43130. break
  43131. lineEnd--
  43132. }
  43133. if (lineEnd === start) {
  43134. if (nextStart > start + newlineChar.length) nextStart--
  43135. lineEnd = nextStart // If no characters to break, show all.
  43136. } else {
  43137. nextStart = lineEnd
  43138. //eat whitespace at end of line
  43139. while (lineEnd > start) {
  43140. if (!isWhitespace(text.charAt(lineEnd - newlineChar.length)))
  43141. break
  43142. lineEnd--
  43143. }
  43144. }
  43145. }
  43146. if (lineEnd >= start) {
  43147. var result = measure(text, start, lineEnd, testWidth)
  43148. lines.push(result)
  43149. }
  43150. start = nextStart
  43151. }
  43152. return lines
  43153. }
  43154. //determines the visible number of glyphs within a given width
  43155. function monospace(text, start, end, width) {
  43156. var glyphs = Math.min(width, end-start)
  43157. return {
  43158. start: start,
  43159. end: start+glyphs
  43160. }
  43161. }
  43162. },{}],52:[function(_dereq_,module,exports){
  43163. "use strict";
  43164. var window = _dereq_("global/window")
  43165. var isFunction = _dereq_("is-function")
  43166. var parseHeaders = _dereq_("parse-headers")
  43167. var xtend = _dereq_("xtend")
  43168. module.exports = createXHR
  43169. createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
  43170. createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
  43171. forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) {
  43172. createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) {
  43173. options = initParams(uri, options, callback)
  43174. options.method = method.toUpperCase()
  43175. return _createXHR(options)
  43176. }
  43177. })
  43178. function forEachArray(array, iterator) {
  43179. for (var i = 0; i < array.length; i++) {
  43180. iterator(array[i])
  43181. }
  43182. }
  43183. function isEmpty(obj){
  43184. for(var i in obj){
  43185. if(obj.hasOwnProperty(i)) return false
  43186. }
  43187. return true
  43188. }
  43189. function initParams(uri, options, callback) {
  43190. var params = uri
  43191. if (isFunction(options)) {
  43192. callback = options
  43193. if (typeof uri === "string") {
  43194. params = {uri:uri}
  43195. }
  43196. } else {
  43197. params = xtend(options, {uri: uri})
  43198. }
  43199. params.callback = callback
  43200. return params
  43201. }
  43202. function createXHR(uri, options, callback) {
  43203. options = initParams(uri, options, callback)
  43204. return _createXHR(options)
  43205. }
  43206. function _createXHR(options) {
  43207. if(typeof options.callback === "undefined"){
  43208. throw new Error("callback argument missing")
  43209. }
  43210. var called = false
  43211. var callback = function cbOnce(err, response, body){
  43212. if(!called){
  43213. called = true
  43214. options.callback(err, response, body)
  43215. }
  43216. }
  43217. function readystatechange() {
  43218. if (xhr.readyState === 4) {
  43219. loadFunc()
  43220. }
  43221. }
  43222. function getBody() {
  43223. // Chrome with requestType=blob throws errors arround when even testing access to responseText
  43224. var body = undefined
  43225. if (xhr.response) {
  43226. body = xhr.response
  43227. } else {
  43228. body = xhr.responseText || getXml(xhr)
  43229. }
  43230. if (isJson) {
  43231. try {
  43232. body = JSON.parse(body)
  43233. } catch (e) {}
  43234. }
  43235. return body
  43236. }
  43237. function errorFunc(evt) {
  43238. clearTimeout(timeoutTimer)
  43239. if(!(evt instanceof Error)){
  43240. evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
  43241. }
  43242. evt.statusCode = 0
  43243. return callback(evt, failureResponse)
  43244. }
  43245. // will load the data & process the response in a special response object
  43246. function loadFunc() {
  43247. if (aborted) return
  43248. var status
  43249. clearTimeout(timeoutTimer)
  43250. if(options.useXDR && xhr.status===undefined) {
  43251. //IE8 CORS GET successful response doesn't have a status field, but body is fine
  43252. status = 200
  43253. } else {
  43254. status = (xhr.status === 1223 ? 204 : xhr.status)
  43255. }
  43256. var response = failureResponse
  43257. var err = null
  43258. if (status !== 0){
  43259. response = {
  43260. body: getBody(),
  43261. statusCode: status,
  43262. method: method,
  43263. headers: {},
  43264. url: uri,
  43265. rawRequest: xhr
  43266. }
  43267. if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
  43268. response.headers = parseHeaders(xhr.getAllResponseHeaders())
  43269. }
  43270. } else {
  43271. err = new Error("Internal XMLHttpRequest Error")
  43272. }
  43273. return callback(err, response, response.body)
  43274. }
  43275. var xhr = options.xhr || null
  43276. if (!xhr) {
  43277. if (options.cors || options.useXDR) {
  43278. xhr = new createXHR.XDomainRequest()
  43279. }else{
  43280. xhr = new createXHR.XMLHttpRequest()
  43281. }
  43282. }
  43283. var key
  43284. var aborted
  43285. var uri = xhr.url = options.uri || options.url
  43286. var method = xhr.method = options.method || "GET"
  43287. var body = options.body || options.data
  43288. var headers = xhr.headers = options.headers || {}
  43289. var sync = !!options.sync
  43290. var isJson = false
  43291. var timeoutTimer
  43292. var failureResponse = {
  43293. body: undefined,
  43294. headers: {},
  43295. statusCode: 0,
  43296. method: method,
  43297. url: uri,
  43298. rawRequest: xhr
  43299. }
  43300. if ("json" in options && options.json !== false) {
  43301. isJson = true
  43302. headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
  43303. if (method !== "GET" && method !== "HEAD") {
  43304. headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
  43305. body = JSON.stringify(options.json === true ? body : options.json)
  43306. }
  43307. }
  43308. xhr.onreadystatechange = readystatechange
  43309. xhr.onload = loadFunc
  43310. xhr.onerror = errorFunc
  43311. // IE9 must have onprogress be set to a unique function.
  43312. xhr.onprogress = function () {
  43313. // IE must die
  43314. }
  43315. xhr.onabort = function(){
  43316. aborted = true;
  43317. }
  43318. xhr.ontimeout = errorFunc
  43319. xhr.open(method, uri, !sync, options.username, options.password)
  43320. //has to be after open
  43321. if(!sync) {
  43322. xhr.withCredentials = !!options.withCredentials
  43323. }
  43324. // Cannot set timeout with sync request
  43325. // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
  43326. // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
  43327. if (!sync && options.timeout > 0 ) {
  43328. timeoutTimer = setTimeout(function(){
  43329. if (aborted) return
  43330. aborted = true//IE9 may still call readystatechange
  43331. xhr.abort("timeout")
  43332. var e = new Error("XMLHttpRequest timeout")
  43333. e.code = "ETIMEDOUT"
  43334. errorFunc(e)
  43335. }, options.timeout )
  43336. }
  43337. if (xhr.setRequestHeader) {
  43338. for(key in headers){
  43339. if(headers.hasOwnProperty(key)){
  43340. xhr.setRequestHeader(key, headers[key])
  43341. }
  43342. }
  43343. } else if (options.headers && !isEmpty(options.headers)) {
  43344. throw new Error("Headers cannot be set on an XDomainRequest object")
  43345. }
  43346. if ("responseType" in options) {
  43347. xhr.responseType = options.responseType
  43348. }
  43349. if ("beforeSend" in options &&
  43350. typeof options.beforeSend === "function"
  43351. ) {
  43352. options.beforeSend(xhr)
  43353. }
  43354. // Microsoft Edge browser sends "undefined" when send is called with undefined value.
  43355. // XMLHttpRequest spec says to pass null as body to indicate no body
  43356. // See https://github.com/naugtur/xhr/issues/100.
  43357. xhr.send(body || null)
  43358. return xhr
  43359. }
  43360. function getXml(xhr) {
  43361. if (xhr.responseType === "document") {
  43362. return xhr.responseXML
  43363. }
  43364. var firefoxBugTakenEffect = xhr.status === 204 && xhr.responseXML && xhr.responseXML.documentElement.nodeName === "parsererror"
  43365. if (xhr.responseType === "" && !firefoxBugTakenEffect) {
  43366. return xhr.responseXML
  43367. }
  43368. return null
  43369. }
  43370. function noop() {}
  43371. },{"global/window":20,"is-function":24,"parse-headers":33,"xtend":54}],53:[function(_dereq_,module,exports){
  43372. module.exports = (function xmlparser() {
  43373. //common browsers
  43374. if (typeof window.DOMParser !== 'undefined') {
  43375. return function(str) {
  43376. var parser = new window.DOMParser()
  43377. return parser.parseFromString(str, 'application/xml')
  43378. }
  43379. }
  43380. //IE8 fallback
  43381. if (typeof window.ActiveXObject !== 'undefined'
  43382. && new window.ActiveXObject('Microsoft.XMLDOM')) {
  43383. return function(str) {
  43384. var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM")
  43385. xmlDoc.async = "false"
  43386. xmlDoc.loadXML(str)
  43387. return xmlDoc
  43388. }
  43389. }
  43390. //last resort fallback
  43391. return function(str) {
  43392. var div = document.createElement('div')
  43393. div.innerHTML = str
  43394. return div
  43395. }
  43396. })()
  43397. },{}],54:[function(_dereq_,module,exports){
  43398. module.exports = extend
  43399. var hasOwnProperty = Object.prototype.hasOwnProperty;
  43400. function extend() {
  43401. var target = {}
  43402. for (var i = 0; i < arguments.length; i++) {
  43403. var source = arguments[i]
  43404. for (var key in source) {
  43405. if (hasOwnProperty.call(source, key)) {
  43406. target[key] = source[key]
  43407. }
  43408. }
  43409. }
  43410. return target
  43411. }
  43412. },{}],55:[function(_dereq_,module,exports){
  43413. module.exports={
  43414. "name": "aframe",
  43415. "version": "0.5.0",
  43416. "description": "A web framework for building virtual reality experiences.",
  43417. "homepage": "https://aframe.io/",
  43418. "main": "dist/aframe-master.js",
  43419. "scripts": {
  43420. "browserify": "browserify src/index.js -s 'AFRAME' -p browserify-derequire",
  43421. "build": "mkdirp build/ && npm run browserify -- --debug -t [envify --INSPECTOR_VERSION dev] -o build/aframe.js",
  43422. "codecov": "codecov",
  43423. "dev": "npm run build && cross-env INSPECTOR_VERSION=dev node ./scripts/budo -t envify",
  43424. "dist": "node scripts/updateVersionLog.js && npm run dist:min && npm run dist:max",
  43425. "dist:max": "npm run browserify -s -- --debug | exorcist dist/aframe-master.js.map > dist/aframe-master.js",
  43426. "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",
  43427. "docs": "markserv --dir docs --port 9001",
  43428. "ghpages": "ghpages -p gh-pages/",
  43429. "lint": "semistandard -v | snazzy",
  43430. "precommit": "npm run lint",
  43431. "preghpages": "npm run dist && rimraf gh-pages && mkdirp gh-pages && cp -r {.nojekyll,dist,lib,examples,index.html,style} gh-pages/. 2>/dev/null || : && git checkout dist/ && replace 'build/aframe-master.js' 'dist/aframe-master.min.js' gh-pages/ -r --silent",
  43432. "prerelease": "npm run dist && node scripts/release.js 0.4.0 0.5.0",
  43433. "start": "npm run dev",
  43434. "test": "karma start ./tests/karma.conf.js",
  43435. "test:docs": "node scripts/docsLint.js",
  43436. "test:firefox": "karma start ./tests/karma.conf.js --browsers Firefox",
  43437. "test:chrome": "karma start ./tests/karma.conf.js --browsers Chrome"
  43438. },
  43439. "repository": "aframevr/aframe",
  43440. "license": "MIT",
  43441. "dependencies": {
  43442. "browserify-css": "^0.8.2",
  43443. "debug": "^2.2.0",
  43444. "deep-assign": "^2.0.0",
  43445. "document-register-element": "dmarcos/document-register-element#8ccc532b7",
  43446. "envify": "^3.4.1",
  43447. "load-bmfont": "^1.2.3",
  43448. "object-assign": "^4.0.1",
  43449. "present": "0.0.6",
  43450. "promise-polyfill": "^3.1.0",
  43451. "style-attr": "^1.0.2",
  43452. "three": "^0.83.0",
  43453. "three-bmfont-text": "^2.1.0",
  43454. "tween.js": "^15.0.0",
  43455. "webvr-polyfill": "dmarcos/webvr-polyfill#a02a8089b"
  43456. },
  43457. "devDependencies": {
  43458. "browserify": "^13.1.0",
  43459. "browserify-derequire": "^0.9.4",
  43460. "browserify-istanbul": "^2.0.0",
  43461. "budo": "^9.2.0",
  43462. "chai": "^3.5.0",
  43463. "chai-shallow-deep-equal": "^1.4.0",
  43464. "chalk": "^1.1.3",
  43465. "codecov": "^1.0.1",
  43466. "cross-env": "^3.1.3",
  43467. "exorcist": "^0.4.0",
  43468. "ghpages": "0.0.8",
  43469. "git-rev": "^0.2.1",
  43470. "glob": "^7.1.1",
  43471. "husky": "^0.11.7",
  43472. "istanbul": "^0.4.5",
  43473. "karma": "^1.3.0",
  43474. "karma-browserify": "^5.1.0",
  43475. "karma-chai-shallow-deep-equal": "0.0.4",
  43476. "karma-chrome-launcher": "^2.0.0",
  43477. "karma-coverage": "^1.1.1",
  43478. "karma-env-preprocessor": "^0.1.1",
  43479. "karma-firefox-launcher": "^1.0.0",
  43480. "karma-mocha": "^1.1.1",
  43481. "karma-mocha-reporter": "^2.1.0",
  43482. "karma-sinon-chai": "^1.2.4",
  43483. "lolex": "^1.5.1",
  43484. "markserv": "0.0.20",
  43485. "minifyify": "^7.3.3",
  43486. "mkdirp": "^0.5.1",
  43487. "mocha": "^3.0.2",
  43488. "mozilla-download": "^1.1.1",
  43489. "open": "0.0.5",
  43490. "replace": "^0.3.0",
  43491. "rimraf": "^2.5.4",
  43492. "semistandard": "^9.0.0",
  43493. "sinon": "^1.17.5",
  43494. "sinon-chai": "^2.8.0",
  43495. "snazzy": "^5.0.0",
  43496. "too-wordy": "ngokevin/too-wordy",
  43497. "uglifyjs": "^2.4.10",
  43498. "write-good": "^0.9.1"
  43499. },
  43500. "link": true,
  43501. "browserify": {
  43502. "transform": [
  43503. "browserify-css",
  43504. "envify"
  43505. ]
  43506. },
  43507. "semistandard": {
  43508. "ignore": [
  43509. "build/**",
  43510. "dist/**",
  43511. "examples/**/shaders/*.js",
  43512. "**/vendor/**"
  43513. ]
  43514. },
  43515. "keywords": [
  43516. "3d",
  43517. "aframe",
  43518. "cardboard",
  43519. "components",
  43520. "oculus",
  43521. "three",
  43522. "three.js",
  43523. "rift",
  43524. "vive",
  43525. "vr",
  43526. "web-components",
  43527. "webvr"
  43528. ],
  43529. "browserify-css": {
  43530. "minify": true
  43531. },
  43532. "engines": {
  43533. "node": ">= 4.6.0",
  43534. "npm": "^2.15.9"
  43535. }
  43536. }
  43537. },{}],56:[function(_dereq_,module,exports){
  43538. var registerComponent = _dereq_('../core/component').registerComponent;
  43539. var THREE = _dereq_('../lib/three');
  43540. /**
  43541. * Blend character model component.
  43542. * Loads a model with skeletal animation blending.
  43543. */
  43544. module.exports.Component = registerComponent('blend-character-model', {
  43545. schema: {type: 'asset'},
  43546. init: function () {
  43547. this.model = null;
  43548. },
  43549. update: function () {
  43550. var self = this;
  43551. var el = this.el;
  43552. var src = this.data;
  43553. if (!src) { return; }
  43554. this.remove();
  43555. this.model = new THREE.BlendCharacter();
  43556. this.model.load(src, function () {
  43557. el.setObject3D('mesh', self.model);
  43558. el.emit('model-loaded', {format: 'blend', model: self.model});
  43559. self.model.castShadow = true;
  43560. self.model.receiveShadow = true;
  43561. self.model.material.shading = THREE.FlatShading;
  43562. self.model.geometry.computeBoundingBox();
  43563. });
  43564. },
  43565. remove: function () {
  43566. if (!this.model) { return; }
  43567. this.el.removeObject3D('mesh');
  43568. }
  43569. });
  43570. },{"../core/component":100,"../lib/three":146}],57:[function(_dereq_,module,exports){
  43571. var registerComponent = _dereq_('../core/component').registerComponent;
  43572. var THREE = _dereq_('../lib/three');
  43573. var utils = _dereq_('../utils/');
  43574. var bind = utils.bind;
  43575. var checkHasPositionalTracking = utils.device.checkHasPositionalTracking;
  43576. /**
  43577. * Camera component.
  43578. * Pairs along with camera system to handle tracking the active camera.
  43579. */
  43580. module.exports.Component = registerComponent('camera', {
  43581. schema: {
  43582. active: {default: true},
  43583. far: {default: 10000},
  43584. fov: {default: 80, min: 0},
  43585. near: {default: 0.005, min: 0},
  43586. userHeight: {default: 0, min: 0},
  43587. zoom: {default: 1, min: 0}
  43588. },
  43589. /**
  43590. * Initialize three.js camera and add it to the entity.
  43591. * Add reference from scene to this entity as the camera.
  43592. */
  43593. init: function () {
  43594. var camera;
  43595. var el = this.el;
  43596. var sceneEl = el.sceneEl;
  43597. this.savedPose = null;
  43598. // Create camera.
  43599. camera = this.camera = new THREE.PerspectiveCamera();
  43600. el.setObject3D('camera', camera);
  43601. // Add listeners to save and restore camera pose if headset is present.
  43602. this.onEnterVR = bind(this.onEnterVR, this);
  43603. this.onExitVR = bind(this.onExitVR, this);
  43604. sceneEl.addEventListener('enter-vr', this.onEnterVR);
  43605. sceneEl.addEventListener('exit-vr', this.onExitVR);
  43606. },
  43607. /**
  43608. * Update three.js camera.
  43609. */
  43610. update: function (oldData) {
  43611. var el = this.el;
  43612. var data = this.data;
  43613. var camera = this.camera;
  43614. var system = this.system;
  43615. // Update height offset.
  43616. this.addHeightOffset(oldData.userHeight);
  43617. // Update properties.
  43618. camera.aspect = data.aspect || (window.innerWidth / window.innerHeight);
  43619. camera.far = data.far;
  43620. camera.fov = data.fov;
  43621. camera.near = data.near;
  43622. camera.zoom = data.zoom;
  43623. camera.updateProjectionMatrix();
  43624. // Active property did not change.
  43625. if (oldData && oldData.active === data.active) { return; }
  43626. // If `active` property changes, or first update, handle active camera with system.
  43627. if (data.active && system.activeCameraEl !== el) {
  43628. // Camera enabled. Set camera to this camera.
  43629. system.setActiveCamera(el);
  43630. } else if (!data.active && system.activeCameraEl === el) {
  43631. // Camera disabled. Set camera to another camera.
  43632. system.disableActiveCamera();
  43633. }
  43634. },
  43635. /**
  43636. * Remove camera on remove (callback).
  43637. */
  43638. remove: function () {
  43639. var sceneEl = this.el.sceneEl;
  43640. this.el.removeObject3D('camera');
  43641. sceneEl.removeEventListener('enter-vr', this.onEnterVR);
  43642. sceneEl.removeEventListener('exit-vr', this.onExitVR);
  43643. },
  43644. /**
  43645. * Save pose and remove the offset.
  43646. */
  43647. onEnterVR: function () {
  43648. this.saveCameraPose();
  43649. this.removeHeightOffset();
  43650. },
  43651. /**
  43652. * Restore the pose. Do not need to re-add the offset because it was saved on entering VR.
  43653. */
  43654. onExitVR: function () {
  43655. this.restoreCameraPose();
  43656. },
  43657. /**
  43658. * Offsets the position of the camera to set a human scale perspective
  43659. * This offset is not necessary when using a headset because the SDK
  43660. * will return the real user's head height and position.
  43661. */
  43662. addHeightOffset: function (oldOffset) {
  43663. var el = this.el;
  43664. var currentPosition;
  43665. var userHeightOffset = this.data.userHeight;
  43666. oldOffset = oldOffset || 0;
  43667. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43668. el.setAttribute('position', {
  43669. x: currentPosition.x,
  43670. y: currentPosition.y - oldOffset + userHeightOffset,
  43671. z: currentPosition.z
  43672. });
  43673. },
  43674. /**
  43675. * Remove the height offset (called when entering VR) since WebVR API gives absolute
  43676. * position.
  43677. */
  43678. removeHeightOffset: function () {
  43679. var currentPosition;
  43680. var el = this.el;
  43681. var hasPositionalTracking;
  43682. var userHeightOffset = this.data.userHeight;
  43683. // Remove the offset if there is positional tracking when entering VR.
  43684. // Necessary for fullscreen mode with no headset.
  43685. // Checking this.hasPositionalTracking to make the value injectable for unit tests.
  43686. hasPositionalTracking = this.hasPositionalTracking || checkHasPositionalTracking();
  43687. if (!userHeightOffset || !hasPositionalTracking) { return; }
  43688. currentPosition = el.getAttribute('position') || {x: 0, y: 0, z: 0};
  43689. el.setAttribute('position', {
  43690. x: currentPosition.x,
  43691. y: currentPosition.y - userHeightOffset,
  43692. z: currentPosition.z
  43693. });
  43694. },
  43695. /**
  43696. * Save camera pose before entering VR to restore later if exiting.
  43697. */
  43698. saveCameraPose: function () {
  43699. var el = this.el;
  43700. var hasPositionalTracking = this.hasPositionalTracking || checkHasPositionalTracking();
  43701. if (this.savedPose || !hasPositionalTracking) { return; }
  43702. this.savedPose = {
  43703. position: el.getAttribute('position'),
  43704. rotation: el.getAttribute('rotation')
  43705. };
  43706. },
  43707. /**
  43708. * Reset camera pose to before entering VR.
  43709. */
  43710. restoreCameraPose: function () {
  43711. var el = this.el;
  43712. var savedPose = this.savedPose;
  43713. var hasPositionalTracking = this.hasPositionalTracking || checkHasPositionalTracking();
  43714. if (!savedPose || !hasPositionalTracking) { return; }
  43715. // Reset camera orientation.
  43716. el.setAttribute('position', savedPose.position);
  43717. el.setAttribute('rotation', savedPose.rotation);
  43718. this.savedPose = null;
  43719. }
  43720. });
  43721. },{"../core/component":100,"../lib/three":146,"../utils/":167}],58:[function(_dereq_,module,exports){
  43722. var registerComponent = _dereq_('../core/component').registerComponent;
  43723. var THREE = _dereq_('../lib/three');
  43724. module.exports.Component = registerComponent('collada-model', {
  43725. schema: {type: 'asset'},
  43726. init: function () {
  43727. this.model = null;
  43728. this.loader = new THREE.ColladaLoader();
  43729. this.loader.options.convertUpAxis = true;
  43730. },
  43731. update: function () {
  43732. var self = this;
  43733. var el = this.el;
  43734. var src = this.data;
  43735. if (!src) { return; }
  43736. this.remove();
  43737. this.loader.load(src, function (colladaModel) {
  43738. self.model = colladaModel.scene;
  43739. el.setObject3D('mesh', self.model);
  43740. el.emit('model-loaded', {format: 'collada', model: self.model});
  43741. });
  43742. },
  43743. remove: function () {
  43744. if (!this.model) { return; }
  43745. this.el.removeObject3D('mesh');
  43746. }
  43747. });
  43748. },{"../core/component":100,"../lib/three":146}],59:[function(_dereq_,module,exports){
  43749. var registerComponent = _dereq_('../core/component').registerComponent;
  43750. var utils = _dereq_('../utils/');
  43751. var bind = utils.bind;
  43752. var EVENTS = {
  43753. CLICK: 'click',
  43754. FUSING: 'fusing',
  43755. MOUSEENTER: 'mouseenter',
  43756. MOUSEDOWN: 'mousedown',
  43757. MOUSELEAVE: 'mouseleave',
  43758. MOUSEUP: 'mouseup'
  43759. };
  43760. var STATES = {
  43761. FUSING: 'cursor-fusing',
  43762. HOVERING: 'cursor-hovering',
  43763. HOVERED: 'cursor-hovered'
  43764. };
  43765. /**
  43766. * Cursor component. Applies the raycaster component specifically for starting the raycaster
  43767. * from the camera and pointing from camera's facing direction, and then only returning the
  43768. * closest intersection. Cursor can be fine-tuned by setting raycaster properties.
  43769. *
  43770. * @member {object} fuseTimeout - Timeout to trigger fuse-click.
  43771. * @member {Element} mouseDownEl - Entity that was last mousedowned during current click.
  43772. * @member {object} intersection - Attributes of the current intersection event, including
  43773. * 3D- and 2D-space coordinates. See: http://threejs.org/docs/api/core/Raycaster.html
  43774. * @member {Element} intersectedEl - Currently-intersected entity. Used to keep track to
  43775. * emit events when unintersecting.
  43776. */
  43777. module.exports.Component = registerComponent('cursor', {
  43778. dependencies: ['raycaster'],
  43779. schema: {
  43780. fuse: {default: utils.device.isMobile()},
  43781. fuseTimeout: {default: 1500, min: 0}
  43782. },
  43783. init: function () {
  43784. var cursorEl = this.el;
  43785. var canvas = cursorEl.sceneEl.canvas;
  43786. this.fuseTimeout = undefined;
  43787. this.mouseDownEl = null;
  43788. this.intersection = null;
  43789. this.intersectedEl = null;
  43790. // Wait for canvas to load.
  43791. if (!canvas) {
  43792. cursorEl.sceneEl.addEventListener('render-target-loaded', bind(this.init, this));
  43793. return;
  43794. }
  43795. // Attach event listeners.
  43796. canvas.addEventListener('mousedown', bind(this.onMouseDown, this));
  43797. canvas.addEventListener('mouseup', bind(this.onMouseUp, this));
  43798. cursorEl.addEventListener('raycaster-intersection', bind(this.onIntersection, this));
  43799. cursorEl.addEventListener('raycaster-intersection-cleared',
  43800. bind(this.onIntersectionCleared, this));
  43801. },
  43802. /**
  43803. * Trigger mousedown and keep track of the mousedowned entity.
  43804. */
  43805. onMouseDown: function (evt) {
  43806. this.twoWayEmit(EVENTS.MOUSEDOWN);
  43807. this.mouseDownEl = this.intersectedEl;
  43808. },
  43809. /**
  43810. * Trigger mouseup if:
  43811. * - Not fusing (mobile has no mouse).
  43812. * - Currently intersecting an entity.
  43813. * - Currently-intersected entity is the same as the one when mousedown was triggered,
  43814. * in case user mousedowned one entity, dragged to another, and mouseupped.
  43815. */
  43816. onMouseUp: function (evt) {
  43817. this.twoWayEmit(EVENTS.MOUSEUP);
  43818. if (this.data.fuse || !this.intersectedEl ||
  43819. this.mouseDownEl !== this.intersectedEl) { return; }
  43820. this.twoWayEmit(EVENTS.CLICK);
  43821. },
  43822. /**
  43823. * Handle intersection.
  43824. */
  43825. onIntersection: function (evt) {
  43826. var self = this;
  43827. var cursorEl = this.el;
  43828. var data = this.data;
  43829. var index;
  43830. var intersectedEl;
  43831. var intersection;
  43832. // Select closest object, excluding the cursor.
  43833. index = evt.detail.els[0] === cursorEl ? 1 : 0;
  43834. intersection = evt.detail.intersections[index];
  43835. intersectedEl = evt.detail.els[index];
  43836. // If cursor is the only intersected object, ignore the event.
  43837. if (!intersectedEl) { return; }
  43838. // Already intersecting this entity.
  43839. if (this.intersectedEl === intersectedEl) {
  43840. this.intersection = intersection;
  43841. return;
  43842. }
  43843. // Unset current intersection.
  43844. if (this.intersectedEl) { this.clearCurrentIntersection(); }
  43845. // Set new intersection.
  43846. this.intersection = intersection;
  43847. this.intersectedEl = intersectedEl;
  43848. // Hovering.
  43849. cursorEl.addState(STATES.HOVERING);
  43850. intersectedEl.addState(STATES.HOVERED);
  43851. self.twoWayEmit(EVENTS.MOUSEENTER);
  43852. // Begin fuse if necessary.
  43853. if (data.fuseTimeout === 0 || !data.fuse) { return; }
  43854. cursorEl.addState(STATES.FUSING);
  43855. this.twoWayEmit(EVENTS.FUSING);
  43856. this.fuseTimeout = setTimeout(function fuse () {
  43857. cursorEl.removeState(STATES.FUSING);
  43858. self.twoWayEmit(EVENTS.CLICK);
  43859. }, data.fuseTimeout);
  43860. },
  43861. /**
  43862. * Handle intersection cleared.
  43863. */
  43864. onIntersectionCleared: function (evt) {
  43865. var cursorEl = this.el;
  43866. var intersectedEl = evt.detail.el;
  43867. // Ignore the cursor.
  43868. if (cursorEl === intersectedEl) { return; }
  43869. // Ignore if the event didn't occur on the current intersection.
  43870. if (intersectedEl !== this.intersectedEl) { return; }
  43871. this.clearCurrentIntersection();
  43872. },
  43873. clearCurrentIntersection: function () {
  43874. var cursorEl = this.el;
  43875. // No longer hovering (or fusing).
  43876. this.intersectedEl.removeState(STATES.HOVERED);
  43877. cursorEl.removeState(STATES.HOVERING);
  43878. cursorEl.removeState(STATES.FUSING);
  43879. this.twoWayEmit(EVENTS.MOUSELEAVE);
  43880. // Unset intersected entity (after emitting the event).
  43881. this.intersection = null;
  43882. this.intersectedEl = null;
  43883. // Clear fuseTimeout.
  43884. clearTimeout(this.fuseTimeout);
  43885. },
  43886. /**
  43887. * Helper to emit on both the cursor and the intersected entity (if exists).
  43888. */
  43889. twoWayEmit: function (evtName) {
  43890. var el = this.el;
  43891. var intersectedEl = this.intersectedEl;
  43892. var intersection = this.intersection;
  43893. el.emit(evtName, {intersectedEl: intersectedEl, intersection: intersection});
  43894. if (!intersectedEl) { return; }
  43895. intersectedEl.emit(evtName, {cursorEl: el, intersection: intersection});
  43896. }
  43897. });
  43898. },{"../core/component":100,"../utils/":167}],60:[function(_dereq_,module,exports){
  43899. var debug = _dereq_('../utils/debug');
  43900. var geometries = _dereq_('../core/geometry').geometries;
  43901. var geometryNames = _dereq_('../core/geometry').geometryNames;
  43902. var registerComponent = _dereq_('../core/component').registerComponent;
  43903. var THREE = _dereq_('../lib/three');
  43904. var dummyGeometry = new THREE.Geometry();
  43905. var warn = debug('components:geometry:warn');
  43906. /**
  43907. * Geometry component. Combined with material component to make a mesh in 3D object.
  43908. * Extended with registered geometries.
  43909. */
  43910. module.exports.Component = registerComponent('geometry', {
  43911. schema: {
  43912. buffer: {default: true},
  43913. mergeTo: {type: 'selector'},
  43914. primitive: {default: 'box', oneOf: geometryNames},
  43915. skipCache: {default: false}
  43916. },
  43917. init: function () {
  43918. this.geometry = null;
  43919. },
  43920. /**
  43921. * Talk to geometry system to get or create geometry.
  43922. */
  43923. update: function (previousData) {
  43924. var data = this.data;
  43925. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  43926. var system = this.system;
  43927. // Dispose old geometry if we created one.
  43928. if (this.geometry) {
  43929. system.unuseGeometry(previousData);
  43930. this.geometry = null;
  43931. }
  43932. // Create new geometry.
  43933. this.geometry = mesh.geometry = system.getOrCreateGeometry(data);
  43934. if (data.mergeTo) {
  43935. this.mergeTo(data.mergeTo);
  43936. }
  43937. },
  43938. /**
  43939. * Merge geometry to another entity's geometry.
  43940. * Remove the entity from the scene. Not a reversible operation.
  43941. *
  43942. * @param {Element} toEl - Entity where the geometry will be merged to.
  43943. */
  43944. mergeTo: function (toEl) {
  43945. var el = this.el;
  43946. var mesh = el.getObject3D('mesh');
  43947. var toMesh;
  43948. if (!toEl || !toEl.isEntity) {
  43949. warn('There is not a valid entity to merge the geometry to');
  43950. return;
  43951. }
  43952. if (toEl === el) {
  43953. warn('Source and target geometries cannot be the same for merge');
  43954. return;
  43955. }
  43956. // Create mesh if entity does not have one.
  43957. toMesh = toEl.getObject3D('mesh');
  43958. if (!toMesh) {
  43959. toMesh = toEl.getOrCreateObject3D('mesh', THREE.Mesh);
  43960. toEl.setAttribute('material', el.getAttribute('material'));
  43961. return;
  43962. }
  43963. if (toMesh.geometry instanceof THREE.Geometry === false ||
  43964. mesh.geometry instanceof THREE.Geometry === false) {
  43965. warn('Geometry merge is only available for `THREE.Geometry` types. ' +
  43966. 'Check that both of the merging geometry and the target geometry have `buffer` ' +
  43967. 'set to false');
  43968. return;
  43969. }
  43970. if (this.data.skipCache === false) {
  43971. warn('Cached geometries are not allowed to merge. Set `skipCache` to true');
  43972. return;
  43973. }
  43974. mesh.parent.updateMatrixWorld();
  43975. toMesh.geometry.merge(mesh.geometry, mesh.matrixWorld);
  43976. el.emit('geometry-merged', {mergeTarget: toEl});
  43977. el.parentNode.removeChild(el);
  43978. },
  43979. /**
  43980. * Tell geometry system that entity is no longer using the geometry.
  43981. * Unset the geometry on the mesh
  43982. */
  43983. remove: function () {
  43984. this.system.unuseGeometry(this.data);
  43985. this.el.getObject3D('mesh').geometry = dummyGeometry;
  43986. this.geometry = null;
  43987. },
  43988. /**
  43989. * Update geometry component schema based on geometry type.
  43990. *
  43991. * @param {object} data - New data passed by Component.
  43992. */
  43993. updateSchema: function (data) {
  43994. var newGeometryType = data.primitive;
  43995. var currentGeometryType = this.data && this.data.primitive;
  43996. var schema = geometries[newGeometryType] && geometries[newGeometryType].schema;
  43997. // Geometry has no schema.
  43998. if (!schema) { throw new Error('Unknown geometry schema `' + newGeometryType + '`'); }
  43999. // Nothing has changed.
  44000. if (currentGeometryType && currentGeometryType === newGeometryType) { return; }
  44001. this.extendSchema(schema);
  44002. }
  44003. });
  44004. },{"../core/component":100,"../core/geometry":101,"../lib/three":146,"../utils/debug":163}],61:[function(_dereq_,module,exports){
  44005. var registerComponent = _dereq_('../core/component').registerComponent;
  44006. var THREE = _dereq_('../lib/three');
  44007. /**
  44008. * glTF model loader.
  44009. */
  44010. module.exports.Component = registerComponent('gltf-model', {
  44011. schema: {type: 'model'},
  44012. init: function () {
  44013. this.model = null;
  44014. this.loader = new THREE.GLTFLoader();
  44015. },
  44016. update: function () {
  44017. var self = this;
  44018. var el = this.el;
  44019. var src = this.data;
  44020. if (!src) { return; }
  44021. this.remove();
  44022. this.loader.load(src, function gltfLoaded (gltfModel) {
  44023. self.model = gltfModel.scene;
  44024. self.system.registerModel(self.model);
  44025. el.setObject3D('mesh', self.model);
  44026. el.emit('model-loaded', {format: 'gltf', model: self.model});
  44027. });
  44028. },
  44029. remove: function () {
  44030. if (!this.model) { return; }
  44031. this.el.removeObject3D('mesh');
  44032. this.system.unregisterModel(this.model);
  44033. }
  44034. });
  44035. },{"../core/component":100,"../lib/three":146}],62:[function(_dereq_,module,exports){
  44036. var registerComponent = _dereq_('../core/component').registerComponent;
  44037. var OCULUS_LEFT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v2/leftHand.json';
  44038. var OCULUS_RIGHT_HAND_MODEL_URL = 'https://cdn.aframe.io/controllers/oculus-hands/v2/rightHand.json';
  44039. /**
  44040. *
  44041. * Hand Controls component
  44042. * Auto-detect appropriate controllers
  44043. * Handle common events coming from the detected vendor-specific controls
  44044. * Translate button events to hand related actions:
  44045. * gripclose, gripopen, thumbup, thumbdown, pointup, pointdown
  44046. * Load a hand model with gestures that are applied based
  44047. * on the button pressed.
  44048. *
  44049. * @property {left/right} Hand mapping
  44050. */
  44051. module.exports.Component = registerComponent('hand-controls', {
  44052. schema: {default: 'left'},
  44053. init: function () {
  44054. var self = this;
  44055. this.touchedButtons = {};
  44056. this.pressedButtons = {};
  44057. this.onGripDown = function () { self.handleButton('grip', 'down'); };
  44058. this.onGripUp = function () { self.handleButton('grip', 'up'); };
  44059. this.onTrackpadDown = function () { self.handleButton('trackpad', 'down'); };
  44060. this.onTrackpadUp = function () { self.handleButton('trackpad', 'up'); };
  44061. this.onTrackpadTouchStart = function () { self.handleButton('trackpad', 'touchstart'); };
  44062. this.onTrackpadTouchEnd = function () { self.handleButton('trackpad', 'touchend'); };
  44063. this.onTriggerDown = function () { self.handleButton('trigger', 'down'); };
  44064. this.onTriggerUp = function () { self.handleButton('trigger', 'up'); };
  44065. this.onTriggerTouchStart = function () { self.handleButton('trigger', 'touchstart'); };
  44066. this.onTriggerTouchEnd = function () { self.handleButton('trigger', 'touchend'); };
  44067. this.onGripTouchStart = function () { self.handleButton('grip', 'touchstart'); };
  44068. this.onGripTouchEnd = function () { self.handleButton('grip', 'touchend'); };
  44069. this.onThumbstickDown = function () { self.handleButton('thumbstick', 'down'); };
  44070. this.onThumbstickUp = function () { self.handleButton('thumbstick', 'up'); };
  44071. this.onAorXTouchStart = function () { self.handleButton('AorX', 'touchstart'); };
  44072. this.onAorXTouchEnd = function () { self.handleButton('AorX', 'touchend'); };
  44073. this.onBorYTouchStart = function () { self.handleButton('BorY', 'touchstart'); };
  44074. this.onBorYTouchEnd = function () { self.handleButton('BorY', 'touchend'); };
  44075. this.onSurfaceTouchStart = function () { self.handleButton('surface', 'touchstart'); };
  44076. this.onSurfaceTouchEnd = function () { self.handleButton('surface', 'touchend'); };
  44077. },
  44078. play: function () {
  44079. this.addEventListeners();
  44080. },
  44081. pause: function () {
  44082. this.removeEventListeners();
  44083. },
  44084. addEventListeners: function () {
  44085. var el = this.el;
  44086. el.addEventListener('gripdown', this.onGripDown);
  44087. el.addEventListener('gripup', this.onGripUp);
  44088. el.addEventListener('trackpaddown', this.onTrackpadDown);
  44089. el.addEventListener('trackpadup', this.onTrackpadUp);
  44090. el.addEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44091. el.addEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44092. el.addEventListener('triggerdown', this.onTriggerDown);
  44093. el.addEventListener('triggerup', this.onTriggerUp);
  44094. el.addEventListener('triggertouchstart', this.onTriggerTouchStart);
  44095. el.addEventListener('triggertouchend', this.onTriggerTouchEnd);
  44096. el.addEventListener('griptouchstart', this.onGripTouchStart);
  44097. el.addEventListener('griptouchend', this.onGripTouchEnd);
  44098. el.addEventListener('thumbstickdown', this.onThumbstickDown);
  44099. el.addEventListener('thumbstickup', this.onThumbstickUp);
  44100. el.addEventListener('Atouchstart', this.onAorXTouchStart);
  44101. el.addEventListener('Atouchend', this.onAorXTouchEnd);
  44102. el.addEventListener('Btouchstart', this.onBorYTouchStart);
  44103. el.addEventListener('Btouchend', this.onBorYTouchEnd);
  44104. el.addEventListener('Xtouchstart', this.onAorXTouchStart);
  44105. el.addEventListener('Xtouchend', this.onAorXTouchEnd);
  44106. el.addEventListener('Ytouchstart', this.onBorYTouchStart);
  44107. el.addEventListener('Ytouchend', this.onBorYTouchEnd);
  44108. el.addEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44109. el.addEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44110. },
  44111. removeEventListeners: function () {
  44112. var el = this.el;
  44113. el.removeEventListener('gripdown', this.onGripDown);
  44114. el.removeEventListener('gripup', this.onGripUp);
  44115. el.removeEventListener('trackpaddown', this.onTrackpadDown);
  44116. el.removeEventListener('trackpadup', this.onTrackpadUp);
  44117. el.removeEventListener('trackpadtouchstart', this.onTrackpadTouchStart);
  44118. el.removeEventListener('trackpadtouchend', this.onTrackpadTouchEnd);
  44119. el.removeEventListener('triggerdown', this.onTriggerDown);
  44120. el.removeEventListener('triggerup', this.onTriggerUp);
  44121. el.removeEventListener('triggertouchstart', this.onTriggerTouchStart);
  44122. el.removeEventListener('triggertouchend', this.onTriggerTouchEnd);
  44123. el.removeEventListener('griptouchstart', this.onGripTouchStart);
  44124. el.removeEventListener('griptouchend', this.onGripTouchEnd);
  44125. el.removeEventListener('thumbstickdown', this.onThumbstickDown);
  44126. el.removeEventListener('thumbstickup', this.onThumbstickUp);
  44127. el.removeEventListener('Atouchstart', this.onAorXTouchStart);
  44128. el.removeEventListener('Atouchend', this.onAorXTouchEnd);
  44129. el.removeEventListener('Btouchstart', this.onBorYTouchStart);
  44130. el.removeEventListener('Btouchend', this.onBorYTouchEnd);
  44131. el.removeEventListener('Xtouchstart', this.onAorXTouchStart);
  44132. el.removeEventListener('Xtouchend', this.onAorXTouchEnd);
  44133. el.removeEventListener('Ytouchstart', this.onBorYTouchStart);
  44134. el.removeEventListener('Ytouchend', this.onBorYTouchEnd);
  44135. el.removeEventListener('surfacetouchstart', this.onSurfaceTouchStart);
  44136. el.removeEventListener('surfacetouchend', this.onSurfaceTouchEnd);
  44137. },
  44138. update: function () {
  44139. var el = this.el;
  44140. var hand = this.data;
  44141. var controlConfiguration = {
  44142. hand: hand,
  44143. model: false,
  44144. rotationOffset: hand === 'left' ? 90 : -90
  44145. };
  44146. var modelUrl;
  44147. if (hand === 'left') {
  44148. modelUrl = 'url(' + OCULUS_LEFT_HAND_MODEL_URL + ')';
  44149. } else {
  44150. modelUrl = 'url(' + OCULUS_RIGHT_HAND_MODEL_URL + ')';
  44151. }
  44152. el.setAttribute('vive-controls', controlConfiguration);
  44153. el.setAttribute('oculus-touch-controls', controlConfiguration);
  44154. el.setAttribute('blend-character-model', modelUrl);
  44155. },
  44156. /** Play the model animations based on the pressed button and kind of event.
  44157. *
  44158. * @param {string} button the name of the button
  44159. * @param {string} evt the event associated to the button
  44160. */
  44161. handleButton: function (button, evt) {
  44162. var isPressed = evt === 'down';
  44163. var isTouched = evt === 'touchstart';
  44164. var lastGesture;
  44165. if (evt.indexOf('touch') === 0) {
  44166. if (isTouched === this.touchedButtons[button]) { return; }
  44167. this.touchedButtons[button] = isTouched;
  44168. } else {
  44169. if (isPressed === this.pressedButtons[button]) { return; }
  44170. this.pressedButtons[button] = isPressed;
  44171. }
  44172. lastGesture = this.gesture;
  44173. this.gesture = this.determineGesture();
  44174. if (this.gesture === lastGesture) { return; }
  44175. this.animateGesture(this.gesture);
  44176. this.emitGestureEvents(this.gesture, lastGesture);
  44177. },
  44178. isOculusTouchController: function () {
  44179. var trackedControls = this.el.components['tracked-controls'];
  44180. var controllerId = trackedControls && trackedControls.controller && trackedControls.controller.id;
  44181. return controllerId && controllerId.indexOf('Oculus Touch') === 0;
  44182. },
  44183. determineGesture: function () {
  44184. var gesture;
  44185. var isGripActive = this.pressedButtons['grip'];
  44186. var isSurfaceActive = this.pressedButtons['surface'] || this.touchedButtons['surface'];
  44187. var isTrackpadActive = this.pressedButtons['trackpad'] || this.touchedButtons['trackpad'];
  44188. var isTriggerActive = this.pressedButtons['trigger'] || this.touchedButtons['trigger'];
  44189. var isABXYActive = this.touchedButtons['AorX'] || this.touchedButtons['BorY'];
  44190. var isOculusTouch = this.isOculusTouchController();
  44191. // this works well with Oculus Touch, but Vive needs tweaks
  44192. if (isGripActive) {
  44193. if (!isOculusTouch) {
  44194. gesture = 'fist';
  44195. } else
  44196. if (isSurfaceActive || isABXYActive || isTrackpadActive) {
  44197. gesture = isTriggerActive ? 'fist' : 'pointing';
  44198. } else {
  44199. gesture = isTriggerActive ? 'thumb' : 'pistol';
  44200. }
  44201. } else
  44202. if (isTriggerActive) {
  44203. gesture = isOculusTouch ? 'touch' : 'fist';
  44204. } else
  44205. if (!isOculusTouch && isTrackpadActive) { gesture = 'pointing'; }
  44206. return gesture;
  44207. },
  44208. gestureAnimationMapping: {
  44209. default: 'Open',
  44210. pointing: 'Point',
  44211. pistol: 'Point + Thumb',
  44212. fist: 'Fist',
  44213. touch: 'Hold',
  44214. thumb: 'Thumb Up'
  44215. },
  44216. animateGesture: function (gesture) {
  44217. var isOculusTouch = this.isOculusTouchController();
  44218. if (!gesture && !isOculusTouch) {
  44219. // for Vive (and other non-Oculus Touch), change rest pose to be thumb down
  44220. this.playAnimation('Open', true);
  44221. return;
  44222. }
  44223. var animation = this.gestureAnimationMapping[gesture || 'default'];
  44224. this.playAnimation(animation || 'Open', !animation && isOculusTouch);
  44225. },
  44226. // map to old vive-specific event names for now
  44227. gestureEventMapping: {
  44228. fist: 'grip', // fist: e.g. grip active, trigger active, trackpad / surface active
  44229. touch: 'point', // 'touch' e.g. trigger active, grip not active
  44230. thumb: 'thumb', // thumbs up: e.g. grip active, trigger active, trackpad / surface not active
  44231. pointing: 'pointing', // pointing: e.g. grip active, trackpad / surface active, trigger not active
  44232. pistol: 'pistol' // pistol: e.g. grip active, trigger not active, trackpad / surface not active
  44233. },
  44234. gestureEventName: function (gesture, active) {
  44235. if (!gesture) return 0;
  44236. var eventName = this.gestureEventMapping[gesture];
  44237. if (eventName === 'grip') { return eventName + (active ? 'close' : 'open'); }
  44238. if (eventName === 'point' || eventName === 'thumb') { return eventName + (active ? 'up' : 'down'); }
  44239. if (eventName === 'pointing' || eventName === 'pistol') { return eventName + (active ? 'start' : 'end'); }
  44240. return 0;
  44241. },
  44242. emitGestureEvents: function (gesture, lastGesture) {
  44243. var el = this.el;
  44244. var eventName;
  44245. if (lastGesture !== gesture) {
  44246. eventName = this.gestureEventName(lastGesture, false);
  44247. if (eventName) { el.emit(eventName); }
  44248. eventName = this.gestureEventName(gesture, true);
  44249. if (eventName) { el.emit(eventName); }
  44250. }
  44251. },
  44252. /**
  44253. * Play the hand animations based on button state.
  44254. *
  44255. * @param {string} animation - the name of the animation.
  44256. * @param {string} reverse - It the animation has to play in reverse.
  44257. */
  44258. playAnimation: function (animation, reverse) {
  44259. var animationActive = this.animationActive;
  44260. var timeScale = 1;
  44261. var mesh = this.el.getObject3D('mesh');
  44262. var clipAction;
  44263. if (!mesh) { return; }
  44264. // determine direction of the animation.
  44265. if (reverse) { timeScale = -1; }
  44266. // stop current animation.
  44267. if (animationActive) { mesh.play(animationActive, 0); }
  44268. // play new animation.
  44269. clipAction = mesh.mixer.clipAction(animation);
  44270. // returning when no clipAction will prevent further issues
  44271. // (e.g. controllers no longer updating pose)
  44272. // but per https://github.com/aframevr/aframe/pull/2191#discussion_r93121878
  44273. // the preference is to NOT prevent the issues to catch bugs earlier in QA.
  44274. clipAction.loop = 2200;
  44275. clipAction.clampWhenFinished = true;
  44276. clipAction.timeScale = timeScale;
  44277. mesh.play(animation, 1);
  44278. this.animationActive = animation;
  44279. }
  44280. });
  44281. },{"../core/component":100}],63:[function(_dereq_,module,exports){
  44282. _dereq_('./blend-character-model');
  44283. _dereq_('./camera');
  44284. _dereq_('./collada-model');
  44285. _dereq_('./cursor');
  44286. _dereq_('./geometry');
  44287. _dereq_('./gltf-model');
  44288. _dereq_('./hand-controls');
  44289. _dereq_('./light');
  44290. _dereq_('./look-controls');
  44291. _dereq_('./material');
  44292. _dereq_('./obj-model');
  44293. _dereq_('./oculus-touch-controls');
  44294. _dereq_('./position');
  44295. _dereq_('./raycaster');
  44296. _dereq_('./rotation');
  44297. _dereq_('./scale');
  44298. _dereq_('./sound');
  44299. _dereq_('./text');
  44300. _dereq_('./tracked-controls');
  44301. _dereq_('./visible');
  44302. _dereq_('./vive-controls');
  44303. _dereq_('./wasd-controls');
  44304. _dereq_('./scene/auto-enter-vr');
  44305. _dereq_('./scene/canvas');
  44306. _dereq_('./scene/debug');
  44307. _dereq_('./scene/embedded');
  44308. _dereq_('./scene/inspector');
  44309. _dereq_('./scene/fog');
  44310. _dereq_('./scene/keyboard-shortcuts');
  44311. _dereq_('./scene/pool');
  44312. _dereq_('./scene/screenshot');
  44313. _dereq_('./scene/stats');
  44314. _dereq_('./scene/vr-mode-ui');
  44315. },{"./blend-character-model":56,"./camera":57,"./collada-model":58,"./cursor":59,"./geometry":60,"./gltf-model":61,"./hand-controls":62,"./light":64,"./look-controls":65,"./material":66,"./obj-model":67,"./oculus-touch-controls":68,"./position":69,"./raycaster":70,"./rotation":71,"./scale":72,"./scene/auto-enter-vr":73,"./scene/canvas":74,"./scene/debug":75,"./scene/embedded":76,"./scene/fog":77,"./scene/inspector":78,"./scene/keyboard-shortcuts":79,"./scene/pool":80,"./scene/screenshot":81,"./scene/stats":82,"./scene/vr-mode-ui":83,"./sound":84,"./text":85,"./tracked-controls":86,"./visible":87,"./vive-controls":88,"./wasd-controls":89}],64:[function(_dereq_,module,exports){
  44316. var bind = _dereq_('../utils/bind');
  44317. var diff = _dereq_('../utils').diff;
  44318. var debug = _dereq_('../utils/debug');
  44319. var registerComponent = _dereq_('../core/component').registerComponent;
  44320. var THREE = _dereq_('../lib/three');
  44321. var degToRad = THREE.Math.degToRad;
  44322. var warn = debug('components:light:warn');
  44323. /**
  44324. * Light component.
  44325. */
  44326. module.exports.Component = registerComponent('light', {
  44327. schema: {
  44328. angle: {default: 60, if: {type: ['spot']}},
  44329. color: {type: 'color'},
  44330. groundColor: {type: 'color', if: {type: ['hemisphere']}},
  44331. decay: {default: 1, if: {type: ['point', 'spot']}},
  44332. distance: {default: 0.0, min: 0, if: {type: ['point', 'spot']}},
  44333. intensity: {default: 1.0, min: 0, if: {type: ['ambient', 'directional', 'hemisphere', 'point', 'spot']}},
  44334. penumbra: {default: 0, min: 0, max: 1, if: {type: ['spot']}},
  44335. type: {default: 'directional', oneOf: ['ambient', 'directional', 'hemisphere', 'point', 'spot']},
  44336. target: {type: 'selector', if: {type: ['spot', 'directional']}}
  44337. },
  44338. /**
  44339. * Notifies scene a light has been added to remove default lighting.
  44340. */
  44341. init: function () {
  44342. var el = this.el;
  44343. this.light = null;
  44344. this.defaultTarget = null;
  44345. this.system.registerLight(el);
  44346. },
  44347. /**
  44348. * (Re)create or update light.
  44349. */
  44350. update: function (oldData) {
  44351. var data = this.data;
  44352. var diffData = diff(data, oldData);
  44353. var light = this.light;
  44354. var self = this;
  44355. // Existing light.
  44356. if (light && !('type' in diffData)) {
  44357. // Light type has not changed. Update light.
  44358. Object.keys(diffData).forEach(function (key) {
  44359. var value = data[key];
  44360. switch (key) {
  44361. case 'color': {
  44362. light.color.set(value);
  44363. break;
  44364. }
  44365. case 'groundColor': {
  44366. light.groundColor.set(value);
  44367. break;
  44368. }
  44369. case 'angle': {
  44370. light.angle = degToRad(value);
  44371. break;
  44372. }
  44373. case 'target': {
  44374. // Reset target if selector is null.
  44375. if (value === null) {
  44376. if (data.type === 'spot' || data.type === 'directional') {
  44377. light.target = self.defaultTarget;
  44378. }
  44379. } else {
  44380. // Target specified, set target to entity's `object3D` when it is loaded.
  44381. if (value.hasLoaded) {
  44382. self.onSetTarget(value);
  44383. } else {
  44384. value.addEventListener('loaded', bind(self.onSetTarget, self, value));
  44385. }
  44386. }
  44387. break;
  44388. }
  44389. default: {
  44390. light[key] = value;
  44391. }
  44392. }
  44393. });
  44394. return;
  44395. }
  44396. // No light yet or light type has changed. Create and add light.
  44397. this.setLight(this.data);
  44398. },
  44399. setLight: function (data) {
  44400. var el = this.el;
  44401. var newLight = this.getLight(data);
  44402. if (newLight) {
  44403. if (this.light) {
  44404. el.removeObject3D('light');
  44405. }
  44406. this.light = newLight;
  44407. this.light.el = el;
  44408. el.setObject3D('light', this.light);
  44409. // HACK solution for issue #1624
  44410. if (data.type === 'spot' || data.type === 'directional' || data.type === 'hemisphere') {
  44411. el.getObject3D('light').translateY(-1);
  44412. }
  44413. // set and position default lighttarget as a child to enable spotlight orientation
  44414. if (data.type === 'spot') {
  44415. el.setObject3D('light-target', this.defaultTarget);
  44416. el.getObject3D('light-target').position.set(0, 0, -1);
  44417. }
  44418. }
  44419. },
  44420. /**
  44421. * Creates a new three.js light object given data object defining the light.
  44422. *
  44423. * @param {object} data
  44424. */
  44425. getLight: function (data) {
  44426. var angle = data.angle;
  44427. var color = new THREE.Color(data.color).getHex();
  44428. var decay = data.decay;
  44429. var distance = data.distance;
  44430. var groundColor = new THREE.Color(data.groundColor).getHex();
  44431. var intensity = data.intensity;
  44432. var type = data.type;
  44433. var target = data.target;
  44434. var light = null;
  44435. switch (type.toLowerCase()) {
  44436. case 'ambient': {
  44437. return new THREE.AmbientLight(color, intensity);
  44438. }
  44439. case 'directional': {
  44440. light = new THREE.DirectionalLight(color, intensity);
  44441. this.defaultTarget = light.target;
  44442. if (target) {
  44443. if (target.hasLoaded) {
  44444. this.onSetTarget(target);
  44445. } else {
  44446. target.addEventListener('loaded', bind(this.onSetTarget, this, target));
  44447. }
  44448. }
  44449. return light;
  44450. }
  44451. case 'hemisphere': {
  44452. return new THREE.HemisphereLight(color, groundColor, intensity);
  44453. }
  44454. case 'point': {
  44455. return new THREE.PointLight(color, intensity, distance, decay);
  44456. }
  44457. case 'spot': {
  44458. light = new THREE.SpotLight(color, intensity, distance, degToRad(angle), data.penumbra, decay);
  44459. this.defaultTarget = light.target;
  44460. if (target) {
  44461. if (target.hasLoaded) {
  44462. this.onSetTarget(target);
  44463. } else {
  44464. target.addEventListener('loaded', bind(this.onSetTarget, this, target));
  44465. }
  44466. }
  44467. return light;
  44468. }
  44469. default: {
  44470. warn('%s is not a valid light type. ' +
  44471. 'Choose from ambient, directional, hemisphere, point, spot.', type);
  44472. }
  44473. }
  44474. },
  44475. onSetTarget: function (targetEl) {
  44476. this.light.target = targetEl.object3D;
  44477. },
  44478. /**
  44479. * Remove light on remove (callback).
  44480. */
  44481. remove: function () {
  44482. this.el.removeObject3D('light');
  44483. }
  44484. });
  44485. },{"../core/component":100,"../lib/three":146,"../utils":167,"../utils/bind":161,"../utils/debug":163}],65:[function(_dereq_,module,exports){
  44486. var registerComponent = _dereq_('../core/component').registerComponent;
  44487. var THREE = _dereq_('../lib/three');
  44488. var isMobile = _dereq_('../utils/').device.isMobile();
  44489. var bind = _dereq_('../utils/bind');
  44490. // To avoid recalculation at every mouse movement tick
  44491. var PI_2 = Math.PI / 2;
  44492. var radToDeg = THREE.Math.radToDeg;
  44493. module.exports.Component = registerComponent('look-controls', {
  44494. dependencies: ['position', 'rotation'],
  44495. schema: {
  44496. enabled: {default: true},
  44497. hmdEnabled: {default: true},
  44498. reverseMouseDrag: {default: false},
  44499. standing: {default: true}
  44500. },
  44501. init: function () {
  44502. var sceneEl = this.el.sceneEl;
  44503. // Aux variables
  44504. this.previousHMDPosition = new THREE.Vector3();
  44505. this.hmdQuaternion = new THREE.Quaternion();
  44506. this.hmdEuler = new THREE.Euler();
  44507. this.setupMouseControls();
  44508. this.setupHMDControls();
  44509. this.bindMethods();
  44510. // Enable grab cursor class on canvas.
  44511. function enableGrabCursor () { sceneEl.canvas.classList.add('a-grab-cursor'); }
  44512. if (!sceneEl.canvas) {
  44513. sceneEl.addEventListener('render-target-loaded', enableGrabCursor);
  44514. } else {
  44515. enableGrabCursor();
  44516. }
  44517. },
  44518. update: function (oldData) {
  44519. var data = this.data;
  44520. var hmdEnabled = data.hmdEnabled;
  44521. if (!data.enabled) { return; }
  44522. if (!hmdEnabled && oldData && hmdEnabled !== oldData.hmdEnabled) {
  44523. this.pitchObject.rotation.set(0, 0, 0);
  44524. this.yawObject.rotation.set(0, 0, 0);
  44525. }
  44526. this.controls.standing = data.standing;
  44527. this.controls.update();
  44528. this.updateOrientation();
  44529. this.updatePosition();
  44530. },
  44531. play: function () {
  44532. this.addEventListeners();
  44533. },
  44534. pause: function () {
  44535. this.removeEventListeners();
  44536. },
  44537. tick: function (t) {
  44538. this.update();
  44539. },
  44540. remove: function () {
  44541. this.pause();
  44542. },
  44543. bindMethods: function () {
  44544. this.onMouseDown = bind(this.onMouseDown, this);
  44545. this.onMouseMove = bind(this.onMouseMove, this);
  44546. this.releaseMouse = bind(this.releaseMouse, this);
  44547. this.onTouchStart = bind(this.onTouchStart, this);
  44548. this.onTouchMove = bind(this.onTouchMove, this);
  44549. this.onTouchEnd = bind(this.onTouchEnd, this);
  44550. },
  44551. setupMouseControls: function () {
  44552. // The canvas where the scene is painted
  44553. this.mouseDown = false;
  44554. this.pitchObject = new THREE.Object3D();
  44555. this.yawObject = new THREE.Object3D();
  44556. this.yawObject.position.y = 10;
  44557. this.yawObject.add(this.pitchObject);
  44558. },
  44559. setupHMDControls: function () {
  44560. this.dolly = new THREE.Object3D();
  44561. this.euler = new THREE.Euler();
  44562. this.controls = new THREE.VRControls(this.dolly);
  44563. this.controls.userHeight = 0.0;
  44564. },
  44565. addEventListeners: function () {
  44566. var sceneEl = this.el.sceneEl;
  44567. var canvasEl = sceneEl.canvas;
  44568. // listen for canvas to load.
  44569. if (!canvasEl) {
  44570. sceneEl.addEventListener('render-target-loaded', bind(this.addEventListeners, this));
  44571. return;
  44572. }
  44573. // Mouse Events
  44574. canvasEl.addEventListener('mousedown', this.onMouseDown, false);
  44575. window.addEventListener('mousemove', this.onMouseMove, false);
  44576. window.addEventListener('mouseup', this.releaseMouse, false);
  44577. // Touch events
  44578. canvasEl.addEventListener('touchstart', this.onTouchStart);
  44579. window.addEventListener('touchmove', this.onTouchMove);
  44580. window.addEventListener('touchend', this.onTouchEnd);
  44581. },
  44582. removeEventListeners: function () {
  44583. var sceneEl = this.el.sceneEl;
  44584. var canvasEl = sceneEl && sceneEl.canvas;
  44585. if (!canvasEl) { return; }
  44586. // Mouse Events
  44587. canvasEl.removeEventListener('mousedown', this.onMouseDown);
  44588. canvasEl.removeEventListener('mousemove', this.onMouseMove);
  44589. canvasEl.removeEventListener('mouseup', this.releaseMouse);
  44590. canvasEl.removeEventListener('mouseout', this.releaseMouse);
  44591. // Touch events
  44592. canvasEl.removeEventListener('touchstart', this.onTouchStart);
  44593. canvasEl.removeEventListener('touchmove', this.onTouchMove);
  44594. canvasEl.removeEventListener('touchend', this.onTouchEnd);
  44595. },
  44596. updateOrientation: function () {
  44597. var currentRotation;
  44598. var deltaRotation;
  44599. var hmdEuler = this.hmdEuler;
  44600. var pitchObject = this.pitchObject;
  44601. var yawObject = this.yawObject;
  44602. var hmdQuaternion = this.calculateHMDQuaternion();
  44603. var sceneEl = this.el.sceneEl;
  44604. var rotation;
  44605. hmdEuler.setFromQuaternion(hmdQuaternion, 'YXZ');
  44606. if (isMobile) {
  44607. // In mobile we allow camera rotation with touch events and sensors
  44608. rotation = {
  44609. x: radToDeg(hmdEuler.x) + radToDeg(pitchObject.rotation.x),
  44610. y: radToDeg(hmdEuler.y) + radToDeg(yawObject.rotation.y),
  44611. z: radToDeg(hmdEuler.z)
  44612. };
  44613. } else if (!sceneEl.is('vr-mode') || isNullVector(hmdEuler) || !this.data.hmdEnabled) {
  44614. currentRotation = this.el.getAttribute('rotation');
  44615. deltaRotation = this.calculateDeltaRotation();
  44616. // Mouse look only if HMD disabled or no info coming from the sensors
  44617. if (this.data.reverseMouseDrag) {
  44618. rotation = {
  44619. x: currentRotation.x - deltaRotation.x,
  44620. y: currentRotation.y - deltaRotation.y,
  44621. z: currentRotation.z
  44622. };
  44623. } else {
  44624. rotation = {
  44625. x: currentRotation.x + deltaRotation.x,
  44626. y: currentRotation.y + deltaRotation.y,
  44627. z: currentRotation.z
  44628. };
  44629. }
  44630. } else {
  44631. // Mouse rotation ignored with an active headset.
  44632. // The user head rotation takes priority
  44633. rotation = {
  44634. x: radToDeg(hmdEuler.x),
  44635. y: radToDeg(hmdEuler.y),
  44636. z: radToDeg(hmdEuler.z)
  44637. };
  44638. }
  44639. this.el.setAttribute('rotation', rotation);
  44640. },
  44641. calculateDeltaRotation: function () {
  44642. var currentRotationX = radToDeg(this.pitchObject.rotation.x);
  44643. var currentRotationY = radToDeg(this.yawObject.rotation.y);
  44644. var deltaRotation;
  44645. this.previousRotationX = this.previousRotationX || currentRotationX;
  44646. this.previousRotationY = this.previousRotationY || currentRotationY;
  44647. deltaRotation = {
  44648. x: currentRotationX - this.previousRotationX,
  44649. y: currentRotationY - this.previousRotationY
  44650. };
  44651. this.previousRotationX = currentRotationX;
  44652. this.previousRotationY = currentRotationY;
  44653. return deltaRotation;
  44654. },
  44655. calculateHMDQuaternion: function () {
  44656. var hmdQuaternion = this.hmdQuaternion;
  44657. hmdQuaternion.copy(this.dolly.quaternion);
  44658. return hmdQuaternion;
  44659. },
  44660. updatePosition: (function () {
  44661. var deltaHMDPosition = new THREE.Vector3();
  44662. return function () {
  44663. var el = this.el;
  44664. var currentPosition = el.getAttribute('position');
  44665. var currentHMDPosition;
  44666. var previousHMDPosition = this.previousHMDPosition;
  44667. var sceneEl = this.el.sceneEl;
  44668. currentHMDPosition = this.calculateHMDPosition();
  44669. deltaHMDPosition.copy(currentHMDPosition).sub(previousHMDPosition);
  44670. if (!sceneEl.is('vr-mode') || isNullVector(deltaHMDPosition)) { return; }
  44671. previousHMDPosition.copy(currentHMDPosition);
  44672. // Do nothing if we have not moved.
  44673. if (!sceneEl.is('vr-mode')) { return; }
  44674. el.setAttribute('position', {
  44675. x: currentPosition.x + deltaHMDPosition.x,
  44676. y: currentPosition.y + deltaHMDPosition.y,
  44677. z: currentPosition.z + deltaHMDPosition.z
  44678. });
  44679. };
  44680. })(),
  44681. calculateHMDPosition: function () {
  44682. var dolly = this.dolly;
  44683. var position = new THREE.Vector3();
  44684. dolly.updateMatrix();
  44685. position.setFromMatrixPosition(dolly.matrix);
  44686. return position;
  44687. },
  44688. onMouseMove: function (event) {
  44689. var pitchObject = this.pitchObject;
  44690. var yawObject = this.yawObject;
  44691. var previousMouseEvent = this.previousMouseEvent;
  44692. if (!this.mouseDown || !this.data.enabled) { return; }
  44693. var movementX = event.movementX || event.mozMovementX;
  44694. var movementY = event.movementY || event.mozMovementY;
  44695. if (movementX === undefined || movementY === undefined) {
  44696. movementX = event.screenX - previousMouseEvent.screenX;
  44697. movementY = event.screenY - previousMouseEvent.screenY;
  44698. }
  44699. this.previousMouseEvent = event;
  44700. yawObject.rotation.y -= movementX * 0.002;
  44701. pitchObject.rotation.x -= movementY * 0.002;
  44702. pitchObject.rotation.x = Math.max(-PI_2, Math.min(PI_2, pitchObject.rotation.x));
  44703. },
  44704. onMouseDown: function (event) {
  44705. this.mouseDown = true;
  44706. this.previousMouseEvent = event;
  44707. document.body.classList.add('a-grabbing');
  44708. },
  44709. releaseMouse: function () {
  44710. this.mouseDown = false;
  44711. document.body.classList.remove('a-grabbing');
  44712. },
  44713. onTouchStart: function (e) {
  44714. if (e.touches.length !== 1) { return; }
  44715. this.touchStart = {
  44716. x: e.touches[0].pageX,
  44717. y: e.touches[0].pageY
  44718. };
  44719. this.touchStarted = true;
  44720. },
  44721. onTouchMove: function (e) {
  44722. var deltaY;
  44723. var yawObject = this.yawObject;
  44724. if (!this.touchStarted) { return; }
  44725. deltaY = 2 * Math.PI * (e.touches[0].pageX - this.touchStart.x) /
  44726. this.el.sceneEl.canvas.clientWidth;
  44727. // Limits touch orientaion to to yaw (y axis)
  44728. yawObject.rotation.y -= deltaY * 0.5;
  44729. this.touchStart = {
  44730. x: e.touches[0].pageX,
  44731. y: e.touches[0].pageY
  44732. };
  44733. },
  44734. onTouchEnd: function () {
  44735. this.touchStarted = false;
  44736. }
  44737. });
  44738. function isNullVector (vector) {
  44739. return vector.x === 0 && vector.y === 0 && vector.z === 0;
  44740. }
  44741. },{"../core/component":100,"../lib/three":146,"../utils/":167,"../utils/bind":161}],66:[function(_dereq_,module,exports){
  44742. /* global Promise */
  44743. var utils = _dereq_('../utils/');
  44744. var component = _dereq_('../core/component');
  44745. var THREE = _dereq_('../lib/three');
  44746. var shader = _dereq_('../core/shader');
  44747. var error = utils.debug('components:material:error');
  44748. var registerComponent = component.registerComponent;
  44749. var shaders = shader.shaders;
  44750. var shaderNames = shader.shaderNames;
  44751. /**
  44752. * Material component.
  44753. *
  44754. * @member {object} shader - Determines how material is shaded. Defaults to `standard`,
  44755. * three.js's implementation of PBR. Another standard shading model is `flat` which
  44756. * uses MeshBasicMaterial.
  44757. */
  44758. module.exports.Component = registerComponent('material', {
  44759. schema: {
  44760. depthTest: {default: true},
  44761. flatShading: {default: false},
  44762. opacity: {default: 1.0, min: 0.0, max: 1.0},
  44763. shader: {default: 'standard', oneOf: shaderNames},
  44764. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  44765. transparent: {default: false},
  44766. visible: {default: true},
  44767. offset: {type: 'vec2', default: {x: 0, y: 0}},
  44768. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  44769. npot: {default: false}
  44770. },
  44771. init: function () {
  44772. this.material = null;
  44773. },
  44774. /**
  44775. * Update or create material.
  44776. *
  44777. * @param {object|null} oldData
  44778. */
  44779. update: function (oldData) {
  44780. var data = this.data;
  44781. if (!this.shader || data.shader !== oldData.shader) {
  44782. this.updateShader(data.shader);
  44783. }
  44784. this.shader.update(this.data);
  44785. this.updateMaterial();
  44786. },
  44787. updateSchema: function (data) {
  44788. var newShader = data.shader;
  44789. var currentShader = this.data && this.data.shader;
  44790. var shader = newShader || currentShader;
  44791. var schema = shaders[shader] && shaders[shader].schema;
  44792. if (!schema) { error('Unknown shader schema ' + shader); }
  44793. if (currentShader && newShader === currentShader) { return; }
  44794. this.extendSchema(schema);
  44795. this.updateBehavior();
  44796. },
  44797. updateBehavior: function () {
  44798. var schema = this.schema;
  44799. var self = this;
  44800. var sceneEl = this.el.sceneEl;
  44801. var tickProperties = {};
  44802. var tick = function (time, delta) {
  44803. var keys = Object.keys(tickProperties);
  44804. keys.forEach(update);
  44805. function update (key) { tickProperties[key] = time; }
  44806. self.shader.update(tickProperties);
  44807. };
  44808. var keys = Object.keys(schema);
  44809. this.tick = undefined;
  44810. keys.forEach(function (key) {
  44811. if (schema[key].type === 'time') {
  44812. self.tick = tick;
  44813. tickProperties[key] = true;
  44814. }
  44815. });
  44816. if (!sceneEl) { return; }
  44817. if (!this.tick) {
  44818. sceneEl.removeBehavior(this);
  44819. } else {
  44820. sceneEl.addBehavior(this);
  44821. }
  44822. },
  44823. updateShader: function (shaderName) {
  44824. var data = this.data;
  44825. var Shader = shaders[shaderName] && shaders[shaderName].Shader;
  44826. var shaderInstance;
  44827. if (!Shader) { throw new Error('Unknown shader ' + shaderName); }
  44828. // Get material from A-Frame shader.
  44829. shaderInstance = this.shader = new Shader();
  44830. shaderInstance.el = this.el;
  44831. shaderInstance.init(data);
  44832. this.setMaterial(shaderInstance.material);
  44833. this.updateSchema(data);
  44834. },
  44835. updateMaterial: function () {
  44836. var data = this.data;
  44837. var material = this.material;
  44838. material.side = parseSide(data.side);
  44839. material.opacity = data.opacity;
  44840. material.transparent = data.transparent !== false || data.opacity < 1.0;
  44841. material.depthTest = data.depthTest !== false;
  44842. material.shading = data.flatShading ? THREE.FlatShading : THREE.SmoothShading;
  44843. material.visible = data.visible;
  44844. },
  44845. /**
  44846. * Remove material on remove (callback).
  44847. * Dispose of it from memory and unsubscribe from scene updates.
  44848. */
  44849. remove: function () {
  44850. var defaultMaterial = new THREE.MeshBasicMaterial();
  44851. var material = this.material;
  44852. var object3D = this.el.getObject3D('mesh');
  44853. if (object3D) { object3D.material = defaultMaterial; }
  44854. disposeMaterial(material, this.system);
  44855. },
  44856. /**
  44857. * (Re)create new material. Has side-effects of setting `this.material` and updating
  44858. * material registration in scene.
  44859. *
  44860. * @param {object} data - Material component data.
  44861. * @param {object} type - Material type to create.
  44862. * @returns {object} Material.
  44863. */
  44864. setMaterial: function (material) {
  44865. var mesh = this.el.getOrCreateObject3D('mesh', THREE.Mesh);
  44866. var system = this.system;
  44867. if (this.material) { disposeMaterial(this.material, system); }
  44868. this.material = mesh.material = material;
  44869. system.registerMaterial(material);
  44870. }
  44871. });
  44872. /**
  44873. * Returns a three.js constant determining which material face sides to render
  44874. * based on the side parameter (passed as a component property).
  44875. *
  44876. * @param {string} [side=front] - `front`, `back`, or `double`.
  44877. * @returns {number} THREE.FrontSide, THREE.BackSide, or THREE.DoubleSide.
  44878. */
  44879. function parseSide (side) {
  44880. switch (side) {
  44881. case 'back': {
  44882. return THREE.BackSide;
  44883. }
  44884. case 'double': {
  44885. return THREE.DoubleSide;
  44886. }
  44887. default: {
  44888. // Including case `front`.
  44889. return THREE.FrontSide;
  44890. }
  44891. }
  44892. }
  44893. /**
  44894. * Dispose of material from memory and unsubscribe material from scene updates like fog.
  44895. */
  44896. function disposeMaterial (material, system) {
  44897. material.dispose();
  44898. system.unregisterMaterial(material);
  44899. }
  44900. },{"../core/component":100,"../core/shader":109,"../lib/three":146,"../utils/":167}],67:[function(_dereq_,module,exports){
  44901. var debug = _dereq_('../utils/debug');
  44902. var registerComponent = _dereq_('../core/component').registerComponent;
  44903. var THREE = _dereq_('../lib/three');
  44904. var warn = debug('components:obj-model:warn');
  44905. module.exports.Component = registerComponent('obj-model', {
  44906. dependencies: ['material'],
  44907. schema: {
  44908. mtl: {type: 'model'},
  44909. obj: {type: 'model'}
  44910. },
  44911. init: function () {
  44912. this.model = null;
  44913. this.objLoader = new THREE.OBJLoader();
  44914. this.mtlLoader = new THREE.MTLLoader(this.objLoader.manager);
  44915. // Allow cross-origin images to be loaded.
  44916. this.mtlLoader.crossOrigin = '';
  44917. },
  44918. update: function () {
  44919. var data = this.data;
  44920. if (!data.obj) { return; }
  44921. this.remove();
  44922. this.loadObj(data.obj, data.mtl);
  44923. },
  44924. remove: function () {
  44925. if (!this.model) { return; }
  44926. this.el.removeObject3D('mesh');
  44927. },
  44928. loadObj: function (objUrl, mtlUrl) {
  44929. var self = this;
  44930. var el = this.el;
  44931. var mtlLoader = this.mtlLoader;
  44932. var objLoader = this.objLoader;
  44933. if (mtlUrl) {
  44934. // .OBJ with an .MTL.
  44935. if (el.hasAttribute('material')) {
  44936. warn('Material component properties are ignored when a .MTL is provided');
  44937. }
  44938. mtlLoader.setTexturePath(mtlUrl.substr(0, mtlUrl.lastIndexOf('/') + 1));
  44939. mtlLoader.load(mtlUrl, function (materials) {
  44940. materials.preload();
  44941. objLoader.setMaterials(materials);
  44942. objLoader.load(objUrl, function (objModel) {
  44943. self.model = objModel;
  44944. el.setObject3D('mesh', objModel);
  44945. el.emit('model-loaded', {format: 'obj', model: objModel});
  44946. });
  44947. });
  44948. return;
  44949. }
  44950. // .OBJ only.
  44951. objLoader.load(objUrl, function (objModel) {
  44952. // Apply material.
  44953. var material = el.components.material;
  44954. if (material) {
  44955. objModel.traverse(function (child) {
  44956. if (child instanceof THREE.Mesh) {
  44957. child.material = material.material;
  44958. }
  44959. });
  44960. }
  44961. self.model = objModel;
  44962. el.setObject3D('mesh', objModel);
  44963. el.emit('model-loaded', {format: 'obj', model: objModel});
  44964. });
  44965. }
  44966. });
  44967. },{"../core/component":100,"../lib/three":146,"../utils/debug":163}],68:[function(_dereq_,module,exports){
  44968. var registerComponent = _dereq_('../core/component').registerComponent;
  44969. var bind = _dereq_('../utils/bind');
  44970. var isControllerPresent = _dereq_('../utils/tracked-controls').isControllerPresent;
  44971. var TOUCH_CONTROLLER_MODEL_BASE_URL = 'https://cdn.aframe.io/controllers/oculus/oculus-touch-controller-';
  44972. var TOUCH_CONTROLLER_MODEL_OBJ_URL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.obj';
  44973. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_L = TOUCH_CONTROLLER_MODEL_BASE_URL + 'left.mtl';
  44974. var TOUCH_CONTROLLER_MODEL_OBJ_URL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.obj';
  44975. var TOUCH_CONTROLLER_MODEL_OBJ_MTL_R = TOUCH_CONTROLLER_MODEL_BASE_URL + 'right.mtl';
  44976. var GAMEPAD_ID_PREFIX = 'Oculus Touch';
  44977. var PIVOT_OFFSET = {x: 0, y: -0.015, z: 0.04};
  44978. // currently, browser bugs prevent capacitive touch events from firing on trigger and grip;
  44979. // however those have analog values, and this (below button-down values) can be used to fake them
  44980. var EMULATED_TOUCH_THRESHOLD = 0.001;
  44981. /**
  44982. * Oculus Touch Controls Component
  44983. * Interfaces with Oculus Touch controllers and maps Gamepad events to
  44984. * common controller buttons: trackpad, trigger, grip, menu and system
  44985. * It loads a controller model and highlights the pressed buttons
  44986. */
  44987. module.exports.Component = registerComponent('oculus-touch-controls', {
  44988. schema: {
  44989. hand: {default: 'left'},
  44990. buttonColor: {type: 'color', default: '#999'}, // Off-white.
  44991. buttonTouchColor: {type: 'color', default: '#8AB'},
  44992. buttonHighlightColor: {type: 'color', default: '#2DF'}, // Light blue.
  44993. model: { default: true },
  44994. rotationOffset: {default: 0} // no default offset; -999 is sentinel value to auto-determine based on hand
  44995. },
  44996. // buttonId
  44997. // 0 - thumbstick
  44998. // 1 - trigger ( intensity value from 0.5 to 1 )
  44999. // 2 - grip
  45000. // 3 - menu ( dispatch but better for menu options )
  45001. // 4 - system ( never dispatched on this layer )
  45002. mapping: {
  45003. 'left': {
  45004. axis0: 'thumbstick',
  45005. axis1: 'thumbstick',
  45006. button0: 'thumbstick',
  45007. button1: 'trigger',
  45008. button2: 'grip',
  45009. button3: 'X',
  45010. button4: 'Y',
  45011. button5: 'surface'
  45012. },
  45013. 'right': {
  45014. axis0: 'thumbstick',
  45015. axis1: 'thumbstick',
  45016. button0: 'thumbstick',
  45017. button1: 'trigger',
  45018. button2: 'grip',
  45019. button3: 'A',
  45020. button4: 'B',
  45021. button5: 'surface'
  45022. }
  45023. },
  45024. bindMethods: function () {
  45025. this.onModelLoaded = bind(this.onModelLoaded, this);
  45026. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  45027. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  45028. },
  45029. init: function () {
  45030. var self = this;
  45031. this.animationActive = 'pointing';
  45032. this.onButtonChanged = bind(this.onButtonChanged, this);
  45033. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  45034. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  45035. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  45036. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  45037. this.controllerPresent = false;
  45038. this.everGotGamepadEvent = false;
  45039. this.lastControllerCheck = 0;
  45040. this.previousButtonValues = {};
  45041. this.bindMethods();
  45042. this.isControllerPresent = isControllerPresent; // to allow mock
  45043. },
  45044. addEventListeners: function () {
  45045. var el = this.el;
  45046. el.addEventListener('buttonchanged', this.onButtonChanged);
  45047. el.addEventListener('buttondown', this.onButtonDown);
  45048. el.addEventListener('buttonup', this.onButtonUp);
  45049. el.addEventListener('touchstart', this.onButtonTouchStart);
  45050. el.addEventListener('touchend', this.onButtonTouchEnd);
  45051. el.addEventListener('model-loaded', this.onModelLoaded);
  45052. el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  45053. window.addEventListener('gamepadconnected', this.checkIfControllerPresent, false);
  45054. window.addEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45055. },
  45056. removeEventListeners: function () {
  45057. var el = this.el;
  45058. el.removeEventListener('buttonchanged', this.onButtonChanged);
  45059. el.removeEventListener('buttondown', this.onButtonDown);
  45060. el.removeEventListener('buttonup', this.onButtonUp);
  45061. el.removeEventListener('touchstart', this.onButtonTouchStart);
  45062. el.removeEventListener('touchend', this.onButtonTouchEnd);
  45063. el.removeEventListener('model-loaded', this.onModelLoaded);
  45064. el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  45065. window.removeEventListener('gamepadconnected', this.checkIfControllerPresent, false);
  45066. window.removeEventListener('gamepaddisconnected', this.checkIfControllerPresent, false);
  45067. },
  45068. checkIfControllerPresent: function () {
  45069. var data = this.data;
  45070. var isPresent = this.isControllerPresent(this.el.sceneEl, GAMEPAD_ID_PREFIX, { hand: data.hand });
  45071. if (isPresent === this.controllerPresent) { return; }
  45072. this.controllerPresent = isPresent;
  45073. if (isPresent) { this.injectTrackedControls(); } // inject track-controls
  45074. },
  45075. play: function () {
  45076. this.checkIfControllerPresent();
  45077. this.addEventListeners();
  45078. },
  45079. pause: function () {
  45080. this.removeEventListeners();
  45081. },
  45082. updateControllerModel: function () {
  45083. var objUrl, mtlUrl;
  45084. if (!this.data.model) { return; }
  45085. if (this.data.hand === 'right') {
  45086. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_R + ')';
  45087. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_R + ')';
  45088. } else {
  45089. objUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_URL_L + ')';
  45090. mtlUrl = 'url(' + TOUCH_CONTROLLER_MODEL_OBJ_MTL_L + ')';
  45091. }
  45092. this.el.setAttribute('obj-model', {obj: objUrl, mtl: mtlUrl});
  45093. },
  45094. injectTrackedControls: function () {
  45095. var el = this.el;
  45096. var data = this.data;
  45097. var isRightHand = data.hand === 'right';
  45098. // since each hand is named differently, avoid enumeration
  45099. el.setAttribute('tracked-controls', {
  45100. id: isRightHand ? 'Oculus Touch (Right)' : 'Oculus Touch (Left)',
  45101. controller: 0,
  45102. rotationOffset: data.rotationOffset !== -999 ? data.rotationOffset : isRightHand ? -90 : 90
  45103. });
  45104. this.updateControllerModel();
  45105. },
  45106. onControllersUpdate: function () {
  45107. if (!this.everGotGamepadEvent) { this.checkIfControllerPresent(); }
  45108. },
  45109. // currently, browser bugs prevent capacitive touch events from firing on trigger and grip;
  45110. // however those have analog values, and this (below button-down values) can be used to fake them
  45111. isEmulatedTouchEvent: function (analogValue) {
  45112. return analogValue && (analogValue >= EMULATED_TOUCH_THRESHOLD);
  45113. },
  45114. onButtonChanged: function (evt) {
  45115. var button = this.mapping[this.data.hand]['button' + evt.detail.id];
  45116. var buttonMeshes = this.buttonMeshes;
  45117. var isPreviousValueEmulatedTouch;
  45118. var analogValue;
  45119. var isEmulatedTouch;
  45120. // at the moment, if trigger or grip,
  45121. // touch events aren't happening (touched is stuck true);
  45122. // synthesize touch events from very low analog values
  45123. if (button !== 'trigger' && button !== 'grip') { return; }
  45124. analogValue = evt.detail.state.value;
  45125. isPreviousValueEmulatedTouch = this.isEmulatedTouchEvent(this.previousButtonValues[button]);
  45126. this.previousButtonValues[button] = analogValue;
  45127. isEmulatedTouch = this.isEmulatedTouchEvent(analogValue);
  45128. if (isEmulatedTouch !== isPreviousValueEmulatedTouch) {
  45129. (isEmulatedTouch ? this.onButtonTouchStart : this.onButtonTouchEnd)(evt);
  45130. }
  45131. if (!buttonMeshes) { return; }
  45132. if (button === 'trigger' && buttonMeshes.trigger) {
  45133. buttonMeshes.trigger.rotation.x = -analogValue * (Math.PI / 24);
  45134. }
  45135. if (button === 'grip' && buttonMeshes.grip) {
  45136. buttonMeshes.grip.rotation.y = (this.data.hand === 'left' ? -1 : 1) * analogValue * (Math.PI / 60);
  45137. }
  45138. },
  45139. onModelLoaded: function (evt) {
  45140. var controllerObject3D = evt.detail.model;
  45141. var buttonMeshes;
  45142. if (!this.data.model) { return; }
  45143. var leftHand = this.data.hand === 'left';
  45144. buttonMeshes = this.buttonMeshes = {};
  45145. buttonMeshes.grip = controllerObject3D.getObjectByName(leftHand ? 'buttonHand_oculus-touch-controller-left.004' : 'buttonHand_oculus-touch-controller-right.005');
  45146. buttonMeshes.thumbstick = controllerObject3D.getObjectByName(leftHand ? 'stick_oculus-touch-controller-left.007' : 'stick_oculus-touch-controller-right.004');
  45147. buttonMeshes.trigger = controllerObject3D.getObjectByName(leftHand ? 'buttonTrigger_oculus-touch-controller-left.005' : 'buttonTrigger_oculus-touch-controller-right.006');
  45148. buttonMeshes.X = controllerObject3D.getObjectByName('buttonX_oculus-touch-controller-left.002');
  45149. buttonMeshes.A = controllerObject3D.getObjectByName('buttonA_oculus-touch-controller-right.002');
  45150. buttonMeshes.Y = controllerObject3D.getObjectByName('buttonY_oculus-touch-controller-left.001');
  45151. buttonMeshes.B = controllerObject3D.getObjectByName('buttonB_oculus-touch-controller-right.003');
  45152. // Offset pivot point
  45153. controllerObject3D.position = PIVOT_OFFSET;
  45154. },
  45155. onButtonEvent: function (id, evtName) {
  45156. var buttonName = this.mapping[this.data.hand]['button' + id];
  45157. var i;
  45158. if (Array.isArray(buttonName)) {
  45159. for (i = 0; i < buttonName.length; i++) {
  45160. this.el.emit(buttonName[i] + evtName);
  45161. }
  45162. } else {
  45163. this.el.emit(buttonName + evtName);
  45164. }
  45165. this.updateModel(buttonName, evtName);
  45166. },
  45167. updateModel: function (buttonName, evtName) {
  45168. var i;
  45169. if (Array.isArray(buttonName)) {
  45170. for (i = 0; i < buttonName.length; i++) {
  45171. this.updateButtonModel(buttonName[i], evtName);
  45172. }
  45173. } else {
  45174. this.updateButtonModel(buttonName, evtName);
  45175. }
  45176. },
  45177. updateButtonModel: function (buttonName, state) {
  45178. var color = (state === 'up' || state === 'touchend') ? this.data.buttonColor : state === 'touchstart' ? this.data.buttonTouchColor : this.data.buttonHighlightColor;
  45179. var buttonMeshes = this.buttonMeshes;
  45180. if (!this.data.model) { return; }
  45181. if (buttonMeshes && buttonMeshes[buttonName]) {
  45182. buttonMeshes[buttonName].material.color.set(color);
  45183. }
  45184. }
  45185. });
  45186. },{"../core/component":100,"../utils/bind":161,"../utils/tracked-controls":171}],69:[function(_dereq_,module,exports){
  45187. var registerComponent = _dereq_('../core/component').registerComponent;
  45188. module.exports.Component = registerComponent('position', {
  45189. schema: {type: 'vec3'},
  45190. update: function () {
  45191. var object3D = this.el.object3D;
  45192. var data = this.data;
  45193. object3D.position.set(data.x, data.y, data.z);
  45194. }
  45195. });
  45196. },{"../core/component":100}],70:[function(_dereq_,module,exports){
  45197. var registerComponent = _dereq_('../core/component').registerComponent;
  45198. var THREE = _dereq_('../lib/three');
  45199. var bind = _dereq_('../utils/').bind;
  45200. var scaleDummy = new THREE.Vector3();
  45201. /**
  45202. * Raycaster component.
  45203. *
  45204. * Pass options to three.js Raycaster including which objects to test.
  45205. * Poll for intersections.
  45206. * Emit event on origin entity and on target entity on intersect.
  45207. *
  45208. * @member {array} intersectedEls - List of currently intersected entities.
  45209. * @member {array} objects - Cached list of meshes to intersect.
  45210. * @member {number} prevCheckTime - Previous time intersection was checked. To help interval.
  45211. * @member {object} raycaster - three.js Raycaster.
  45212. */
  45213. module.exports.Component = registerComponent('raycaster', {
  45214. schema: {
  45215. far: {default: Infinity}, // Infinity.
  45216. interval: {default: 100},
  45217. near: {default: 0},
  45218. objects: {default: ''},
  45219. recursive: {default: true}
  45220. },
  45221. init: function () {
  45222. this.direction = new THREE.Vector3();
  45223. this.intersectedEls = [];
  45224. this.objects = null;
  45225. this.prevCheckTime = undefined;
  45226. this.raycaster = new THREE.Raycaster();
  45227. this.updateOriginDirection();
  45228. this.refreshObjects = bind(this.refreshObjects, this);
  45229. },
  45230. play: function () {
  45231. this.el.sceneEl.addEventListener('child-attached', this.refreshObjects);
  45232. this.el.sceneEl.addEventListener('child-detached', this.refreshObjects);
  45233. },
  45234. pause: function () {
  45235. this.el.sceneEl.removeEventListener('child-attached', this.refreshObjects);
  45236. this.el.sceneEl.removeEventListener('child-detached', this.refreshObjects);
  45237. },
  45238. /**
  45239. * Create or update raycaster object.
  45240. */
  45241. update: function () {
  45242. var data = this.data;
  45243. var raycaster = this.raycaster;
  45244. // Set raycaster properties.
  45245. raycaster.far = data.far;
  45246. raycaster.near = data.near;
  45247. this.refreshObjects();
  45248. },
  45249. /**
  45250. * Update list of objects to test for intersection.
  45251. */
  45252. refreshObjects: function () {
  45253. var data = this.data;
  45254. var i;
  45255. var objectEls;
  45256. // Push meshes onto list of objects to intersect.
  45257. if (data.objects) {
  45258. objectEls = this.el.sceneEl.querySelectorAll(data.objects);
  45259. this.objects = [];
  45260. for (i = 0; i < objectEls.length; i++) {
  45261. this.objects.push(objectEls[i].object3D);
  45262. }
  45263. return;
  45264. }
  45265. // If objects not defined, intersect with everything.
  45266. this.objects = this.el.sceneEl.object3D.children;
  45267. },
  45268. /**
  45269. * Check for intersections and cleared intersections on an interval.
  45270. */
  45271. tick: function (time) {
  45272. var el = this.el;
  45273. var data = this.data;
  45274. var intersectedEls;
  45275. var intersections;
  45276. var prevCheckTime = this.prevCheckTime;
  45277. var prevIntersectedEls;
  45278. // Only check for intersection if interval time has passed.
  45279. if (prevCheckTime && (time - prevCheckTime < data.interval)) { return; }
  45280. // Update check time.
  45281. this.prevCheckTime = time;
  45282. // Store old previously intersected entities.
  45283. prevIntersectedEls = this.intersectedEls.slice();
  45284. // Raycast.
  45285. this.updateOriginDirection();
  45286. intersections = this.raycaster.intersectObjects(this.objects, data.recursive);
  45287. // Only keep intersections against objects that have a reference to an entity.
  45288. intersections = intersections.filter(function hasEl (intersection) {
  45289. return !!intersection.object.el;
  45290. });
  45291. // Update intersectedEls.
  45292. intersectedEls = this.intersectedEls = intersections.map(function getEl (intersection) {
  45293. return intersection.object.el;
  45294. });
  45295. // Emit intersected on intersected entity per intersected entity.
  45296. intersections.forEach(function emitEvents (intersection) {
  45297. var intersectedEl = intersection.object.el;
  45298. intersectedEl.emit('raycaster-intersected', {el: el, intersection: intersection});
  45299. });
  45300. // Emit all intersections at once on raycasting entity.
  45301. if (intersections.length) {
  45302. el.emit('raycaster-intersection', {
  45303. els: intersectedEls.slice(),
  45304. intersections: intersections
  45305. });
  45306. }
  45307. // Emit intersection cleared on both entities per formerly intersected entity.
  45308. prevIntersectedEls.forEach(function checkStillIntersected (intersectedEl) {
  45309. if (intersectedEls.indexOf(intersectedEl) !== -1) { return; }
  45310. el.emit('raycaster-intersection-cleared', {el: intersectedEl});
  45311. intersectedEl.emit('raycaster-intersected-cleared', {el: el});
  45312. });
  45313. },
  45314. /**
  45315. * Set origin and direction of raycaster using entity position and rotation.
  45316. */
  45317. updateOriginDirection: (function () {
  45318. var directionHelper = new THREE.Quaternion();
  45319. var originVec3 = new THREE.Vector3();
  45320. // Closure to make quaternion/vector3 objects private.
  45321. return function updateOriginDirection () {
  45322. var el = this.el;
  45323. var object3D = el.object3D;
  45324. // Update matrix world.
  45325. object3D.updateMatrixWorld();
  45326. // Grab the position and rotation.
  45327. object3D.matrixWorld.decompose(originVec3, directionHelper, scaleDummy);
  45328. // Apply rotation to a 0, 0, -1 vector.
  45329. this.direction.set(0, 0, -1);
  45330. this.direction.applyQuaternion(directionHelper);
  45331. this.raycaster.set(originVec3, this.direction);
  45332. };
  45333. })()
  45334. });
  45335. },{"../core/component":100,"../lib/three":146,"../utils/":167}],71:[function(_dereq_,module,exports){
  45336. var degToRad = _dereq_('../lib/three').Math.degToRad;
  45337. var registerComponent = _dereq_('../core/component').registerComponent;
  45338. module.exports.Component = registerComponent('rotation', {
  45339. schema: {type: 'vec3'},
  45340. /**
  45341. * Updates object3D rotation.
  45342. */
  45343. update: function () {
  45344. var data = this.data;
  45345. var object3D = this.el.object3D;
  45346. object3D.rotation.set(degToRad(data.x), degToRad(data.y), degToRad(data.z));
  45347. object3D.rotation.order = 'YXZ';
  45348. }
  45349. });
  45350. },{"../core/component":100,"../lib/three":146}],72:[function(_dereq_,module,exports){
  45351. var registerComponent = _dereq_('../core/component').registerComponent;
  45352. // Avoids triggering a zero-determinant which makes object3D matrix non-invertible.
  45353. var zeroScale = 0.00001;
  45354. module.exports.Component = registerComponent('scale', {
  45355. schema: {
  45356. type: 'vec3',
  45357. default: {x: 1, y: 1, z: 1}
  45358. },
  45359. update: function () {
  45360. var data = this.data;
  45361. var object3D = this.el.object3D;
  45362. var x = data.x === 0 ? zeroScale : data.x;
  45363. var y = data.y === 0 ? zeroScale : data.y;
  45364. var z = data.z === 0 ? zeroScale : data.z;
  45365. object3D.scale.set(x, y, z);
  45366. }
  45367. });
  45368. },{"../core/component":100}],73:[function(_dereq_,module,exports){
  45369. var registerComponent = _dereq_('../../core/component').registerComponent;
  45370. var utils = _dereq_('../../utils');
  45371. /**
  45372. * Automatically enter VR, either upon vrdisplayactivate (e.g. putting on Rift headset)
  45373. * or immediately (if possible) if display name contains data string.
  45374. * The default data string is 'GearVR' for Carmel browser which only does VR.
  45375. */
  45376. module.exports.Component = registerComponent('auto-enter-vr', {
  45377. schema: {
  45378. display: {type: 'string', default: 'GearVR'},
  45379. enabled: {type: 'boolean', default: true}
  45380. },
  45381. init: function () {
  45382. var scene = this.el;
  45383. var self = this;
  45384. // define methods to allow mock testing
  45385. this.enterVR = scene.enterVR.bind(scene);
  45386. this.exitVR = scene.exitVR.bind(scene);
  45387. this.shouldAutoEnterVR = this.shouldAutoEnterVR.bind(this);
  45388. // don't do anything if false
  45389. if (utils.getUrlParameter('auto-enter-vr') === 'false') { return; }
  45390. // enter VR on vrdisplayactivate (e.g. putting on Rift headset)
  45391. window.addEventListener('vrdisplayactivate', function () { self.enterVR(); }, false);
  45392. // exit VR on vrdisplaydeactivate (e.g. taking off Rift headset)
  45393. window.addEventListener('vrdisplaydeactivate', function () { self.exitVR(); }, false);
  45394. // check if we should try to enter VR... turns out we need to wait for next tick
  45395. setTimeout(function () { if (self.shouldAutoEnterVR()) { self.enterVR(); } }, 0);
  45396. },
  45397. update: function () {
  45398. return this.shouldAutoEnterVR() ? this.enterVR() : this.exitVR();
  45399. },
  45400. shouldAutoEnterVR: function () {
  45401. var scene = this.el;
  45402. var data = this.data;
  45403. // if false, we should not auto-enter VR
  45404. if (!data.enabled) { return false; }
  45405. // if we have a data string to match against display name, try and get it;
  45406. // if we can't get display name, or it doesn't match, we should not auto-enter VR
  45407. if (data.display && data.display !== 'all') {
  45408. var display = scene.effect && scene.effect.getVRDisplay && scene.effect.getVRDisplay();
  45409. if (!display || !display.displayName || display.displayName.indexOf(data.display) < 0) { return false; }
  45410. }
  45411. // we should auto-enter VR
  45412. return true;
  45413. }
  45414. });
  45415. },{"../../core/component":100,"../../utils":167}],74:[function(_dereq_,module,exports){
  45416. var bind = _dereq_('../../utils/bind');
  45417. var registerComponent = _dereq_('../../core/component').registerComponent;
  45418. module.exports.Component = registerComponent('canvas', {
  45419. init: function () {
  45420. var canvasEl;
  45421. var sceneEl = this.el;
  45422. canvasEl = document.createElement('canvas');
  45423. canvasEl.classList.add('a-canvas');
  45424. // Mark canvas as provided/injected by A-Frame.
  45425. canvasEl.dataset.aframeCanvas = true;
  45426. sceneEl.appendChild(canvasEl);
  45427. document.addEventListener('fullscreenchange', onFullScreenChange);
  45428. document.addEventListener('mozfullscreenchange', onFullScreenChange);
  45429. document.addEventListener('webkitfullscreenchange', onFullScreenChange);
  45430. // Prevent overscroll on mobile.
  45431. canvasEl.addEventListener('touchmove', function (event) {
  45432. event.preventDefault();
  45433. });
  45434. // Set canvas on scene.
  45435. sceneEl.canvas = canvasEl;
  45436. sceneEl.emit('render-target-loaded', {target: canvasEl});
  45437. // For unknown reasons a syncrhonous resize does not work on desktop when
  45438. // entering/exiting fullscreen.
  45439. setTimeout(bind(sceneEl.resize, sceneEl), 0);
  45440. function onFullScreenChange () {
  45441. var fullscreenEl =
  45442. document.fullscreenElement ||
  45443. document.mozFullScreenElement ||
  45444. document.webkitFullscreenElement;
  45445. // No fullscren element === exit fullscreen
  45446. if (!fullscreenEl) { sceneEl.exitVR(); }
  45447. document.activeElement.blur();
  45448. document.body.focus();
  45449. }
  45450. }
  45451. });
  45452. },{"../../core/component":100,"../../utils/bind":161}],75:[function(_dereq_,module,exports){
  45453. var register = _dereq_('../../core/component').registerComponent;
  45454. module.exports.Component = register('debug', {
  45455. schema: {default: true}
  45456. });
  45457. },{"../../core/component":100}],76:[function(_dereq_,module,exports){
  45458. var registerComponent = _dereq_('../../core/component').registerComponent;
  45459. /**
  45460. * Component to embed an a-frame scene within the layout of a 2D page.
  45461. */
  45462. module.exports.Component = registerComponent('embedded', {
  45463. dependencies: ['vr-mode-ui'],
  45464. schema: {default: true},
  45465. update: function () {
  45466. var sceneEl = this.el;
  45467. var enterVREl = sceneEl.querySelector('.a-enter-vr');
  45468. if (this.data === true) {
  45469. if (enterVREl) { enterVREl.classList.add('embedded'); }
  45470. sceneEl.removeFullScreenStyles();
  45471. } else {
  45472. if (enterVREl) { enterVREl.classList.remove('embedded'); }
  45473. sceneEl.addFullScreenStyles();
  45474. }
  45475. }
  45476. });
  45477. },{"../../core/component":100}],77:[function(_dereq_,module,exports){
  45478. var register = _dereq_('../../core/component').registerComponent;
  45479. var THREE = _dereq_('../../lib/three');
  45480. var debug = _dereq_('../../utils/debug');
  45481. var warn = debug('components:fog:warn');
  45482. /**
  45483. * Fog component.
  45484. * Applies only to the scene entity.
  45485. */
  45486. module.exports.Component = register('fog', {
  45487. schema: {
  45488. color: {type: 'color', default: '#000'},
  45489. density: {default: 0.00025},
  45490. far: {default: 1000, min: 0},
  45491. near: {default: 1, min: 0},
  45492. type: {default: 'linear', oneOf: ['linear', 'exponential']}
  45493. },
  45494. update: function () {
  45495. var data = this.data;
  45496. var el = this.el;
  45497. var fog = this.el.object3D.fog;
  45498. if (!el.isScene) {
  45499. warn('Fog component can only be applied to <a-scene>');
  45500. return;
  45501. }
  45502. // (Re)create fog if fog doesn't exist or fog type changed.
  45503. if (!fog || data.type !== fog.name) {
  45504. el.object3D.fog = getFog(data);
  45505. el.systems.material.updateMaterials();
  45506. return;
  45507. }
  45508. // Fog data changed. Update fog.
  45509. Object.keys(this.schema).forEach(function (key) {
  45510. var value = data[key];
  45511. if (key === 'color') { value = new THREE.Color(value); }
  45512. fog[key] = value;
  45513. });
  45514. },
  45515. /**
  45516. * Remove fog on remove (callback).
  45517. */
  45518. remove: function () {
  45519. var fog = this.el.object3D.fog;
  45520. if (!fog) { return; }
  45521. fog.far = 0;
  45522. fog.near = 0.1;
  45523. }
  45524. });
  45525. /**
  45526. * Creates a fog object. Sets fog.name to be able to detect fog type changes.
  45527. *
  45528. * @param {object} data - Fog data.
  45529. * @returns {object} fog
  45530. */
  45531. function getFog (data) {
  45532. var fog;
  45533. if (data.type === 'exponential') {
  45534. fog = new THREE.FogExp2(data.color, data.density);
  45535. } else {
  45536. fog = new THREE.Fog(data.color, data.near, data.far);
  45537. }
  45538. fog.name = data.type;
  45539. return fog;
  45540. }
  45541. },{"../../core/component":100,"../../lib/three":146,"../../utils/debug":163}],78:[function(_dereq_,module,exports){
  45542. (function (process){
  45543. /* global AFRAME */
  45544. var AFRAME_INJECTED = _dereq_('../../constants').AFRAME_INJECTED;
  45545. var bind = _dereq_('../../utils/bind');
  45546. var pkg = _dereq_('../../../package');
  45547. var registerComponent = _dereq_('../../core/component').registerComponent;
  45548. /**
  45549. * 0.4.2 to 0.4.x
  45550. * Will need to update this when A-Frame goes to 1.x.x.
  45551. */
  45552. function getFuzzyPatchVersion (version) {
  45553. var split = version.split('.');
  45554. split[2] = 'x';
  45555. return split.join('.');
  45556. }
  45557. var INSPECTOR_DEV_URL = 'https://aframe.io/aframe-inspector/dist/aframe-inspector.js';
  45558. var INSPECTOR_RELEASE_URL = 'https://unpkg.com/aframe-inspector@' + getFuzzyPatchVersion(pkg.version) + '/dist/aframe-inspector.min.js';
  45559. var INSPECTOR_URL = process.env.INSPECTOR_VERSION === 'dev' ? INSPECTOR_DEV_URL : INSPECTOR_RELEASE_URL;
  45560. var LOADING_MESSAGE = 'Loading Inspector';
  45561. module.exports.Component = registerComponent('inspector', {
  45562. schema: {
  45563. url: {default: INSPECTOR_URL}
  45564. },
  45565. init: function () {
  45566. this.onKeydown = bind(this.onKeydown, this);
  45567. this.onMessage = bind(this.onMessage, this);
  45568. this.initOverlay();
  45569. window.addEventListener('keydown', this.onKeydown);
  45570. window.addEventListener('message', this.onMessage);
  45571. },
  45572. initOverlay: function () {
  45573. var dotsHTML = '<span class="dots"><span>.</span><span>.</span><span>.</span></span>';
  45574. this.loadingMessageEl = document.createElement('div');
  45575. this.loadingMessageEl.classList.add('a-inspector-loader');
  45576. this.loadingMessageEl.innerHTML = LOADING_MESSAGE + dotsHTML;
  45577. },
  45578. remove: function () {
  45579. this.removeEventListeners();
  45580. },
  45581. /**
  45582. * <ctrl> + <alt> + i keyboard shortcut.
  45583. */
  45584. onKeydown: function (evt) {
  45585. var shortcutPressed = evt.keyCode === 73 && evt.ctrlKey && evt.altKey;
  45586. if (!this.data || !shortcutPressed) { return; }
  45587. this.injectInspector();
  45588. },
  45589. showLoader: function () {
  45590. document.body.appendChild(this.loadingMessageEl);
  45591. },
  45592. hideLoader: function () {
  45593. this.el.removeChild(this.loadingMessageEl);
  45594. },
  45595. /**
  45596. * postMessage. aframe.io uses this to create a button on examples to open Inspector.
  45597. */
  45598. onMessage: function (evt) {
  45599. if (evt.data === 'INJECT_AFRAME_INSPECTOR') { this.injectInspector(); }
  45600. },
  45601. injectInspector: function () {
  45602. var self = this;
  45603. var script;
  45604. if (AFRAME.INSPECTOR || AFRAME.inspectorInjected) { return; }
  45605. this.showLoader();
  45606. // Inject.
  45607. script = document.createElement('script');
  45608. script.src = this.data.url;
  45609. script.setAttribute('data-name', 'aframe-inspector');
  45610. script.setAttribute(AFRAME_INJECTED, '');
  45611. script.onload = function () {
  45612. AFRAME.INSPECTOR.open();
  45613. self.hideLoader();
  45614. self.removeEventListeners();
  45615. };
  45616. document.head.appendChild(script);
  45617. AFRAME.inspectorInjected = true;
  45618. },
  45619. removeEventListeners: function () {
  45620. window.removeEventListener('keydown', this.onKeydown);
  45621. window.removeEventListener('message', this.onMessage);
  45622. }
  45623. });
  45624. }).call(this,_dereq_('_process'))
  45625. },{"../../../package":55,"../../constants":91,"../../core/component":100,"../../utils/bind":161,"_process":9}],79:[function(_dereq_,module,exports){
  45626. var registerComponent = _dereq_('../../core/component').registerComponent;
  45627. var shouldCaptureKeyEvent = _dereq_('../../utils/').shouldCaptureKeyEvent;
  45628. var THREE = _dereq_('../../lib/three');
  45629. var controls = new THREE.VRControls(new THREE.Object3D());
  45630. module.exports.Component = registerComponent('keyboard-shortcuts', {
  45631. schema: {
  45632. enterVR: {default: true},
  45633. exitVR: {default: true},
  45634. resetSensor: {default: true}
  45635. },
  45636. init: function () {
  45637. var self = this;
  45638. var scene = this.el;
  45639. this.listener = window.addEventListener('keyup', function (event) {
  45640. if (!shouldCaptureKeyEvent(event)) { return; }
  45641. if (self.enterVREnabled && event.keyCode === 70) { // f.
  45642. scene.enterVR();
  45643. }
  45644. if (self.enterVREnabled && event.keyCode === 27) { // escape.
  45645. scene.exitVR();
  45646. }
  45647. if (self.resetSensorEnabled && event.keyCode === 90) { // z.
  45648. controls.resetSensor();
  45649. }
  45650. }, false);
  45651. },
  45652. update: function (oldData) {
  45653. var data = this.data;
  45654. this.enterVREnabled = data.enterVR;
  45655. this.resetSensorEnabled = data.resetSensor;
  45656. },
  45657. remove: function () {
  45658. window.removeEventListener('keyup', this.listener);
  45659. }
  45660. });
  45661. },{"../../core/component":100,"../../lib/three":146,"../../utils/":167}],80:[function(_dereq_,module,exports){
  45662. var debug = _dereq_('../../utils/debug');
  45663. var registerComponent = _dereq_('../../core/component').registerComponent;
  45664. var warn = debug('components:pool:warn');
  45665. /**
  45666. * Pool component.
  45667. * A pool of entities that will be reused.
  45668. * It avoids creating and destroying the same kind of entities
  45669. * in dynamic scenes. It will help reduce GC pauses. Useful for example
  45670. * in a game where you want to reuse enemies entities.
  45671. *
  45672. * @member {array} availableEls - Available entities in the pool.
  45673. * @member {array} usedEls - Entities of the pool in use.
  45674. *
  45675. */
  45676. module.exports.Component = registerComponent('pool', {
  45677. schema: {
  45678. mixin: {default: ''},
  45679. size: {default: 0},
  45680. dynamic: {default: false}
  45681. },
  45682. multiple: true,
  45683. init: function () {
  45684. this.initPool();
  45685. },
  45686. initPool: function () {
  45687. var i;
  45688. var mixin = this.data.mixin;
  45689. if (!mixin) { return; }
  45690. this.availableEls = [];
  45691. this.usedEls = [];
  45692. for (i = 0; i < this.data.size; ++i) {
  45693. this.createEntity();
  45694. }
  45695. },
  45696. update: function (oldData) {
  45697. var data = this.data;
  45698. if (oldData.mixin !== data.mixin || oldData.size !== data.size) {
  45699. this.initPool();
  45700. }
  45701. },
  45702. /**
  45703. * Add a new entity to the list of available entities.
  45704. */
  45705. createEntity: function () {
  45706. var el = document.createElement('a-entity');
  45707. el.play = this.wrapPlay(el.play);
  45708. el.setAttribute('mixin', this.data.mixin);
  45709. el.setAttribute('visible', false);
  45710. this.el.appendChild(el);
  45711. this.availableEls.push(el);
  45712. },
  45713. /**
  45714. * Play wrapper for pooled entities. When pausing and playing
  45715. * a scene we don't want to play the entities that are not in use
  45716. */
  45717. wrapPlay: function (playMethod) {
  45718. var usedEls = this.usedEls;
  45719. return function () {
  45720. if (usedEls.indexOf(this) === -1) { return; }
  45721. playMethod.call(this);
  45722. };
  45723. },
  45724. /**
  45725. * Used to request one of the available entities of the pool
  45726. */
  45727. requestEntity: function () {
  45728. var el;
  45729. if (this.availableEls.length === 0) {
  45730. if (this.data.dynamic === false) {
  45731. warn('Requested entity from empty pool ' + this.name);
  45732. return;
  45733. } else {
  45734. warn('Requested entity from empty pool. This pool is dynamic' +
  45735. 'and will resize automatically. You might want to increase its initial size' + this.name);
  45736. }
  45737. this.createEntity();
  45738. }
  45739. el = this.availableEls.shift();
  45740. this.usedEls.push(el);
  45741. el.setAttribute('visible', true);
  45742. return el;
  45743. },
  45744. /**
  45745. * Used to return a used entity to the pool
  45746. */
  45747. returnEntity: function (el) {
  45748. var index = this.usedEls.indexOf(el);
  45749. if (index === -1) {
  45750. warn('The returned entity was not previously pooled from ' + this.name);
  45751. return;
  45752. }
  45753. this.usedEls.splice(index, 1);
  45754. this.availableEls.push(el);
  45755. el.setAttribute('visible', false);
  45756. el.pause();
  45757. }
  45758. });
  45759. },{"../../core/component":100,"../../utils/debug":163}],81:[function(_dereq_,module,exports){
  45760. /* global ImageData, URL */
  45761. var registerComponent = _dereq_('../../core/component').registerComponent;
  45762. var THREE = _dereq_('../../lib/three');
  45763. var VERTEX_SHADER = [
  45764. 'attribute vec3 position;',
  45765. 'attribute vec2 uv;',
  45766. 'uniform mat4 projectionMatrix;',
  45767. 'uniform mat4 modelViewMatrix;',
  45768. 'varying vec2 vUv;',
  45769. 'void main() {',
  45770. ' vUv = vec2( 1.- uv.x, uv.y );',
  45771. ' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
  45772. '}'
  45773. ].join('\n');
  45774. var FRAGMENT_SHADER = [
  45775. 'precision mediump float;',
  45776. 'uniform samplerCube map;',
  45777. 'varying vec2 vUv;',
  45778. '#define M_PI 3.141592653589793238462643383279',
  45779. 'void main() {',
  45780. ' vec2 uv = vUv;',
  45781. ' float longitude = uv.x * 2. * M_PI - M_PI + M_PI / 2.;',
  45782. ' float latitude = uv.y * M_PI;',
  45783. ' vec3 dir = vec3(',
  45784. ' - sin( longitude ) * sin( latitude ),',
  45785. ' cos( latitude ),',
  45786. ' - cos( longitude ) * sin( latitude )',
  45787. ' );',
  45788. ' normalize( dir );',
  45789. ' gl_FragColor = vec4( textureCube( map, dir ).rgb, 1.0 );',
  45790. '}'
  45791. ].join('\n');
  45792. /**
  45793. * Component to take screenshots of the scene using a keboard shortcut (alt+s).
  45794. * It can be configured to either take 360&deg; captures (`equirectangular`)
  45795. * or regular screenshots (`projection`)
  45796. *
  45797. * This is based on https://github.com/spite/THREE.CubemapToEquirectangular
  45798. * To capture an equirectangular projection of the scene a THREE.CubeCamera is used
  45799. * The cube map produced by the CubeCamera is projected on a quad and then rendered to
  45800. * WebGLRenderTarget with an ortographic camera.
  45801. */
  45802. module.exports.Component = registerComponent('screenshot', {
  45803. schema: {
  45804. width: {default: 4096},
  45805. height: {default: 2048}
  45806. },
  45807. init: function () {
  45808. var el = this.el;
  45809. var self = this;
  45810. if (el.renderer) {
  45811. setup();
  45812. } else {
  45813. el.addEventListener('render-target-loaded', setup);
  45814. }
  45815. function setup () {
  45816. var gl = el.renderer.getContext();
  45817. self.cubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  45818. self.material = new THREE.RawShaderMaterial({
  45819. uniforms: {map: {type: 't', value: null}},
  45820. vertexShader: VERTEX_SHADER,
  45821. fragmentShader: FRAGMENT_SHADER,
  45822. side: THREE.DoubleSide
  45823. });
  45824. self.quad = new THREE.Mesh(
  45825. new THREE.PlaneBufferGeometry(1, 1),
  45826. self.material
  45827. );
  45828. self.quad.visible = false;
  45829. self.camera = new THREE.OrthographicCamera(-1 / 2, 1 / 2, 1 / 2, -1 / 2, -10000, 10000);
  45830. self.canvas = document.createElement('canvas');
  45831. self.ctx = self.canvas.getContext('2d');
  45832. if (el.camera) { el.camera.add(self.quad); }
  45833. self.onKeyDown = self.onKeyDown.bind(self);
  45834. self.onCameraActive = self.onCameraActive.bind(self);
  45835. el.addEventListener('camera-set-active', self.onCameraActive);
  45836. }
  45837. },
  45838. getRenderTarget: function (width, height) {
  45839. return new THREE.WebGLRenderTarget(width, height, {
  45840. minFilter: THREE.LinearFilter,
  45841. magFilter: THREE.LinearFilter,
  45842. wrapS: THREE.ClampToEdgeWrapping,
  45843. wrapT: THREE.ClampToEdgeWrapping,
  45844. format: THREE.RGBAFormat,
  45845. type: THREE.UnsignedByteType
  45846. });
  45847. },
  45848. resize: function (width, height) {
  45849. // Resize quad.
  45850. this.quad.scale.set(width, height, 1);
  45851. // Resize camera.
  45852. this.camera.left = -1 * width / 2;
  45853. this.camera.right = width / 2;
  45854. this.camera.top = height / 2;
  45855. this.camera.bottom = -1 * height / 2;
  45856. this.camera.updateProjectionMatrix();
  45857. // Resize canvas.
  45858. this.canvas.width = width;
  45859. this.canvas.height = height;
  45860. },
  45861. play: function () {
  45862. window.addEventListener('keydown', this.onKeyDown);
  45863. },
  45864. onCameraActive: function (evt) {
  45865. var cameraParent = this.quad.parent;
  45866. if (cameraParent) { cameraParent.remove(this.quad); }
  45867. evt.detail.cameraEl.getObject3D('camera').add(this.quad);
  45868. },
  45869. /**
  45870. * <ctrl> + <alt> + s = Regular screenshot.
  45871. * <ctrl> + <alt> + <shift> + s = Equirectangular screenshot.
  45872. */
  45873. onKeyDown: function (evt) {
  45874. var shortcutPressed = evt.keyCode === 83 && evt.ctrlKey && evt.altKey;
  45875. if (!this.data || !shortcutPressed) { return; }
  45876. var projection = evt.shiftKey ? 'equirectangular' : 'perspective';
  45877. this.capture(projection);
  45878. },
  45879. /**
  45880. * Capture a screenshot of the scene.
  45881. *
  45882. * @param {string} projection - Screenshot projection (equirectangular or perspective).
  45883. */
  45884. setCapture: function (projection) {
  45885. var el = this.el;
  45886. var renderer = el.renderer;
  45887. var size;
  45888. var camera;
  45889. var cubeCamera;
  45890. // Configure camera.
  45891. if (projection === 'perspective') {
  45892. // Quad is only used in equirectangular mode. Hide it in this case.
  45893. this.quad.visible = false;
  45894. // Use scene camera.
  45895. camera = el.camera;
  45896. size = renderer.getSize();
  45897. } else {
  45898. // Use ortho camera.
  45899. camera = this.camera;
  45900. // Copy position and rotation of scene camera into the ortho one.
  45901. camera.position.copy(el.camera.getWorldPosition());
  45902. camera.rotation.copy(el.camera.getWorldRotation());
  45903. // Create cube camera and copy position from scene camera.
  45904. cubeCamera = new THREE.CubeCamera(el.camera.near, el.camera.far,
  45905. Math.min(this.cubeMapSize, 2048));
  45906. cubeCamera.position.copy(el.camera.getWorldPosition());
  45907. cubeCamera.rotation.copy(el.camera.getWorldRotation());
  45908. // Render scene with cube camera.
  45909. cubeCamera.updateCubeMap(el.renderer, el.object3D);
  45910. this.quad.material.uniforms.map.value = cubeCamera.renderTarget.texture;
  45911. size = {width: this.data.width, height: this.data.height};
  45912. // Use quad to project image taken by the cube camera.
  45913. this.quad.visible = true;
  45914. }
  45915. return {
  45916. camera: camera,
  45917. size: size,
  45918. projection: projection
  45919. };
  45920. },
  45921. /**
  45922. * Maintained for backwards compatibility.
  45923. */
  45924. capture: function (projection) {
  45925. var params = this.setCapture(projection);
  45926. this.renderCapture(params.camera, params.size, params.projection);
  45927. // Trigger file download.
  45928. this.saveCapture();
  45929. },
  45930. /**
  45931. * Return canvas instead of triggering download (e.g., for uploading blob to server).
  45932. */
  45933. getCanvas: function (projection) {
  45934. var params = this.setCapture(projection);
  45935. this.renderCapture(params.camera, params.size, params.projection);
  45936. return this.canvas;
  45937. },
  45938. renderCapture: function (camera, size, projection) {
  45939. var autoClear = this.el.renderer.autoClear;
  45940. var el = this.el;
  45941. var imageData;
  45942. var output;
  45943. var pixels;
  45944. var renderer = this.el.renderer;
  45945. // Create rendering target and buffer to store the read pixels.
  45946. output = this.getRenderTarget(size.width, size.height);
  45947. pixels = new Uint8Array(4 * size.width * size.height);
  45948. // Resize quad, camera, and canvas.
  45949. this.resize(size.width, size.height);
  45950. // Render scene to render target.
  45951. renderer.autoClear = true;
  45952. renderer.render(el.object3D, camera, output, true);
  45953. renderer.autoClear = autoClear;
  45954. // Read image pizels back.
  45955. renderer.readRenderTargetPixels(output, 0, 0, size.width, size.height, pixels);
  45956. if (projection === 'perspective') {
  45957. pixels = this.flipPixelsVertically(pixels, size.width, size.height);
  45958. }
  45959. imageData = new ImageData(new Uint8ClampedArray(pixels), size.width, size.height);
  45960. // Hide quad after projecting the image.
  45961. this.quad.visible = false;
  45962. // Copy pixels into canvas.
  45963. this.ctx.putImageData(imageData, 0, 0);
  45964. },
  45965. flipPixelsVertically: function (pixels, width, height) {
  45966. var flippedPixels = pixels.slice(0);
  45967. for (var x = 0; x < width; ++x) {
  45968. for (var y = 0; y < height; ++y) {
  45969. flippedPixels[x * 4 + y * width * 4] = pixels[x * 4 + (height - y) * width * 4];
  45970. flippedPixels[x * 4 + 1 + y * width * 4] = pixels[x * 4 + 1 + (height - y) * width * 4];
  45971. flippedPixels[x * 4 + 2 + y * width * 4] = pixels[x * 4 + 2 + (height - y) * width * 4];
  45972. flippedPixels[x * 4 + 3 + y * width * 4] = pixels[x * 4 + 3 + (height - y) * width * 4];
  45973. }
  45974. }
  45975. return flippedPixels;
  45976. },
  45977. /**
  45978. * Download capture to file.
  45979. */
  45980. saveCapture: function () {
  45981. this.canvas.toBlob(function (blob) {
  45982. var fileName = 'screenshot-' + document.title.toLowerCase() + '-' + Date.now() + '.png';
  45983. var linkEl = document.createElement('a');
  45984. var url = URL.createObjectURL(blob);
  45985. linkEl.href = url;
  45986. linkEl.setAttribute('download', fileName);
  45987. linkEl.innerHTML = 'downloading...';
  45988. linkEl.style.display = 'none';
  45989. document.body.appendChild(linkEl);
  45990. setTimeout(function () {
  45991. linkEl.click();
  45992. document.body.removeChild(linkEl);
  45993. }, 1);
  45994. }, 'image/png');
  45995. }
  45996. });
  45997. },{"../../core/component":100,"../../lib/three":146}],82:[function(_dereq_,module,exports){
  45998. var registerComponent = _dereq_('../../core/component').registerComponent;
  45999. var RStats = _dereq_('../../../vendor/rStats');
  46000. var utils = _dereq_('../../utils');
  46001. _dereq_('../../../vendor/rStats.extras');
  46002. _dereq_('../../lib/rStatsAframe');
  46003. var AFrameStats = window.aframeStats;
  46004. var bind = utils.bind;
  46005. var HIDDEN_CLASS = 'a-hidden';
  46006. var ThreeStats = window.threeStats;
  46007. /**
  46008. * Stats appended to document.body by RStats.
  46009. */
  46010. module.exports.Component = registerComponent('stats', {
  46011. schema: {default: true},
  46012. init: function () {
  46013. var scene = this.el;
  46014. if (utils.getUrlParameter('stats') === 'false') { return; }
  46015. this.stats = createStats(scene);
  46016. this.statsEl = document.querySelector('.rs-base');
  46017. this.hideBound = bind(this.hide, this);
  46018. this.showBound = bind(this.show, this);
  46019. scene.addEventListener('enter-vr', this.hideBound);
  46020. scene.addEventListener('exit-vr', this.showBound);
  46021. },
  46022. update: function () {
  46023. if (!this.stats) { return; }
  46024. return (!this.data) ? this.hide() : this.show();
  46025. },
  46026. remove: function () {
  46027. this.el.removeEventListener('enter-vr', this.hideBound);
  46028. this.el.removeEventListener('exit-vr', this.showBound);
  46029. if (!this.statsEl) { return; } // Scene detached.
  46030. this.statsEl.parentNode.removeChild(this.statsEl);
  46031. },
  46032. tick: function () {
  46033. var stats = this.stats;
  46034. if (!stats) { return; }
  46035. stats('rAF').tick();
  46036. stats('FPS').frame();
  46037. stats().update();
  46038. },
  46039. hide: function () {
  46040. this.statsEl.classList.add(HIDDEN_CLASS);
  46041. },
  46042. show: function () {
  46043. this.statsEl.classList.remove(HIDDEN_CLASS);
  46044. }
  46045. });
  46046. function createStats (scene) {
  46047. var threeStats = new ThreeStats(scene.renderer);
  46048. var aframeStats = new AFrameStats(scene);
  46049. var plugins = scene.isMobile ? [] : [threeStats, aframeStats];
  46050. return new RStats({
  46051. css: [], // Our stylesheet is injected from `src/index.js`.
  46052. values: {
  46053. fps: {caption: 'fps', below: 30}
  46054. },
  46055. groups: [
  46056. {caption: 'Framerate', values: ['fps', 'raf']}
  46057. ],
  46058. plugins: plugins
  46059. });
  46060. }
  46061. },{"../../../vendor/rStats":175,"../../../vendor/rStats.extras":174,"../../core/component":100,"../../lib/rStatsAframe":145,"../../utils":167}],83:[function(_dereq_,module,exports){
  46062. var registerComponent = _dereq_('../../core/component').registerComponent;
  46063. var constants = _dereq_('../../constants/');
  46064. var utils = _dereq_('../../utils/');
  46065. var bind = utils.bind;
  46066. var ENTER_VR_CLASS = 'a-enter-vr';
  46067. var ENTER_VR_BTN_CLASS = 'a-enter-vr-button';
  46068. var HIDDEN_CLASS = 'a-hidden';
  46069. var ORIENTATION_MODAL_CLASS = 'a-orientation-modal';
  46070. /**
  46071. * UI for entering VR mode.
  46072. */
  46073. module.exports.Component = registerComponent('vr-mode-ui', {
  46074. dependencies: ['canvas'],
  46075. schema: {
  46076. enabled: {default: true}
  46077. },
  46078. init: function () {
  46079. var self = this;
  46080. var sceneEl = this.el;
  46081. if (utils.getUrlParameter('ui') === 'false') { return; }
  46082. this.enterVR = bind(sceneEl.enterVR, sceneEl);
  46083. this.exitVR = bind(sceneEl.exitVR, sceneEl);
  46084. this.insideLoader = false;
  46085. this.enterVREl = null;
  46086. this.orientationModalEl = null;
  46087. // Hide/show VR UI when entering/exiting VR mode.
  46088. sceneEl.addEventListener('enter-vr', bind(this.updateEnterVRInterface, this));
  46089. sceneEl.addEventListener('exit-vr', bind(this.updateEnterVRInterface, this));
  46090. window.addEventListener('message', function (event) {
  46091. if (event.data.type === 'loaderReady') {
  46092. self.insideLoader = true;
  46093. self.remove();
  46094. }
  46095. });
  46096. // Modal that tells the user to change orientation if in portrait.
  46097. window.addEventListener('orientationchange', bind(this.toggleOrientationModalIfNeeded, this));
  46098. },
  46099. update: function () {
  46100. var sceneEl = this.el;
  46101. if (!this.data.enabled || this.insideLoader || utils.getUrlParameter('ui') === 'false') {
  46102. return this.remove();
  46103. }
  46104. if (this.enterVREl || this.orientationModalEl) { return; }
  46105. // Add UI if enabled and not already present.
  46106. this.enterVREl = createEnterVRButton(this.enterVR);
  46107. sceneEl.appendChild(this.enterVREl);
  46108. this.orientationModalEl = createOrientationModal(this.exitVR);
  46109. sceneEl.appendChild(this.orientationModalEl);
  46110. this.updateEnterVRInterface();
  46111. },
  46112. remove: function () {
  46113. [this.enterVREl, this.orientationModalEl].forEach(function (uiElement) {
  46114. if (uiElement) {
  46115. uiElement.parentNode.removeChild(uiElement);
  46116. }
  46117. });
  46118. },
  46119. updateEnterVRInterface: function () {
  46120. this.toggleEnterVRButtonIfNeeded();
  46121. this.toggleOrientationModalIfNeeded();
  46122. },
  46123. toggleEnterVRButtonIfNeeded: function () {
  46124. var sceneEl = this.el;
  46125. if (!this.enterVREl) { return; }
  46126. if (sceneEl.is('vr-mode')) {
  46127. this.enterVREl.classList.add(HIDDEN_CLASS);
  46128. } else {
  46129. this.enterVREl.classList.remove(HIDDEN_CLASS);
  46130. }
  46131. },
  46132. toggleOrientationModalIfNeeded: function () {
  46133. var sceneEl = this.el;
  46134. var orientationModalEl = this.orientationModalEl;
  46135. if (!orientationModalEl || !sceneEl.isMobile) { return; }
  46136. if (!utils.device.isLandscape() && sceneEl.is('vr-mode')) {
  46137. // Show if in VR mode on portrait.
  46138. orientationModalEl.classList.remove(HIDDEN_CLASS);
  46139. } else {
  46140. orientationModalEl.classList.add(HIDDEN_CLASS);
  46141. }
  46142. }
  46143. });
  46144. /**
  46145. * Creates a button that when clicked will enter into stereo-rendering mode for VR.
  46146. *
  46147. * Structure: <div><button></div>
  46148. *
  46149. * @returns {Element} Wrapper <div>.
  46150. */
  46151. function createEnterVRButton (enterVRHandler) {
  46152. var vrButton;
  46153. var wrapper;
  46154. // Create elements.
  46155. wrapper = document.createElement('div');
  46156. wrapper.classList.add(ENTER_VR_CLASS);
  46157. wrapper.setAttribute(constants.AFRAME_INJECTED, '');
  46158. vrButton = document.createElement('button');
  46159. vrButton.className = ENTER_VR_BTN_CLASS;
  46160. vrButton.setAttribute(constants.AFRAME_INJECTED, '');
  46161. // Insert elements.
  46162. wrapper.appendChild(vrButton);
  46163. vrButton.addEventListener('click', enterVRHandler);
  46164. return wrapper;
  46165. }
  46166. /**
  46167. * Create a modal that tells mobile users to orient the phone to landscape.
  46168. * Add a close button that if clicked, exits VR and closes the modal.
  46169. */
  46170. function createOrientationModal (exitVRHandler) {
  46171. var modal = document.createElement('div');
  46172. modal.className = ORIENTATION_MODAL_CLASS;
  46173. modal.classList.add(HIDDEN_CLASS);
  46174. modal.setAttribute(constants.AFRAME_INJECTED, '');
  46175. var exit = document.createElement('button');
  46176. exit.setAttribute(constants.AFRAME_INJECTED, '');
  46177. exit.innerHTML = 'Exit VR';
  46178. // Exit VR on close.
  46179. exit.addEventListener('click', exitVRHandler);
  46180. modal.appendChild(exit);
  46181. return modal;
  46182. }
  46183. },{"../../constants/":91,"../../core/component":100,"../../utils/":167}],84:[function(_dereq_,module,exports){
  46184. var registerComponent = _dereq_('../core/component').registerComponent;
  46185. var debug = _dereq_('../utils/debug');
  46186. var bind = _dereq_('../utils/bind');
  46187. var THREE = _dereq_('../lib/three');
  46188. var warn = debug('components:sound:warn');
  46189. /**
  46190. * Sound component.
  46191. */
  46192. module.exports.Component = registerComponent('sound', {
  46193. schema: {
  46194. autoplay: {default: false},
  46195. loop: {default: false},
  46196. on: {default: ''},
  46197. poolSize: {default: 1},
  46198. src: {type: 'audio'},
  46199. volume: {default: 1}
  46200. },
  46201. multiple: true,
  46202. init: function () {
  46203. this.listener = null;
  46204. this.audioLoader = new THREE.AudioLoader();
  46205. this.pool = new THREE.Group();
  46206. this.playSound = bind(this.playSound, this);
  46207. },
  46208. update: function (oldData) {
  46209. var data = this.data;
  46210. var srcChanged = data.src !== oldData.src;
  46211. // Create new sound if not yet created or changing `src`.
  46212. if (srcChanged) {
  46213. if (!data.src) {
  46214. warn('Audio source was not specified with `src`');
  46215. return;
  46216. }
  46217. this.setupSound();
  46218. }
  46219. this.pool.children.forEach(function (sound) {
  46220. sound.autoplay = data.autoplay;
  46221. sound.setLoop(data.loop);
  46222. sound.setVolume(data.volume);
  46223. });
  46224. if (data.on !== oldData.on) {
  46225. this.updateEventListener(oldData.on);
  46226. }
  46227. // All sound values set. Load in `src`.
  46228. if (srcChanged) {
  46229. var self = this;
  46230. this.audioLoader.load(data.src, function (buffer) {
  46231. self.pool.children.forEach(function (sound) {
  46232. sound.setBuffer(buffer);
  46233. });
  46234. // Remove this key from cache, otherwise we can't play it again
  46235. THREE.Cache.remove(data.src);
  46236. });
  46237. }
  46238. },
  46239. pause: function () {
  46240. this.pauseSound();
  46241. this.removeEventListener();
  46242. },
  46243. play: function () {
  46244. if (this.data.autoplay) { this.playSound(); }
  46245. this.updateEventListener();
  46246. },
  46247. remove: function () {
  46248. this.removeEventListener();
  46249. this.el.removeObject3D(this.attrName);
  46250. try {
  46251. this.pool.children.forEach(function (sound) {
  46252. sound.disconnect();
  46253. });
  46254. } catch (e) {
  46255. // disconnect() will throw if it was never connected initially.
  46256. warn('Audio source not properly disconnected');
  46257. }
  46258. },
  46259. /**
  46260. * Update listener attached to the user defined on event.
  46261. */
  46262. updateEventListener: function (oldEvt) {
  46263. var el = this.el;
  46264. if (oldEvt) { el.removeEventListener(oldEvt, this.playSound); }
  46265. el.addEventListener(this.data.on, this.playSound);
  46266. },
  46267. removeEventListener: function () {
  46268. this.el.removeEventListener(this.data.on, this.playSound);
  46269. },
  46270. /**
  46271. * Removes current sound object, creates new sound object, adds to entity.
  46272. *
  46273. * @returns {object} sound
  46274. */
  46275. setupSound: function () {
  46276. var el = this.el;
  46277. var sceneEl = el.sceneEl;
  46278. if (this.pool.children.length > 0) {
  46279. this.stopSound();
  46280. el.removeObject3D('sound');
  46281. }
  46282. // Only want one AudioListener. Cache it on the scene.
  46283. var listener = this.listener = sceneEl.audioListener || new THREE.AudioListener();
  46284. sceneEl.audioListener = listener;
  46285. if (sceneEl.camera) {
  46286. sceneEl.camera.add(listener);
  46287. }
  46288. // Wait for camera if necessary.
  46289. sceneEl.addEventListener('camera-set-active', function (evt) {
  46290. evt.detail.cameraEl.getObject3D('camera').add(listener);
  46291. });
  46292. // Create [poolSize] audio instances and attach them to pool
  46293. this.pool = new THREE.Group();
  46294. for (var i = 0; i < this.data.poolSize; i++) {
  46295. var sound = new THREE.PositionalAudio(listener);
  46296. this.pool.add(sound);
  46297. }
  46298. el.setObject3D(this.attrName, this.pool);
  46299. this.pool.children.forEach(function (sound) {
  46300. sound.onEnded = function () {
  46301. sound.isPlaying = false;
  46302. el.emit('sound-ended', {index: i});
  46303. };
  46304. });
  46305. },
  46306. /**
  46307. * Pause all the sounds in the pool.
  46308. */
  46309. pauseSound: function () {
  46310. this.pool.children.forEach(function (sound) {
  46311. if (!sound.source || !sound.source.buffer || !sound.isPlaying || !sound.pause) { return; }
  46312. sound.pause();
  46313. });
  46314. },
  46315. /**
  46316. * Look for an unused sound in the pool and play it if found.
  46317. */
  46318. playSound: function () {
  46319. var found = false;
  46320. this.pool.children.forEach(function (sound) {
  46321. if (!sound.isPlaying && sound.buffer && !found) {
  46322. sound.play();
  46323. found = true;
  46324. return;
  46325. }
  46326. });
  46327. if (!found) {
  46328. warn('All the sounds are playing. If you need to play more sounds simultaneously ' +
  46329. 'consider increasing the size of pool with the `poolSize` attribute.');
  46330. }
  46331. },
  46332. /**
  46333. * Stop all the sounds in the pool.
  46334. */
  46335. stopSound: function () {
  46336. this.pool.children.forEach(function (sound) {
  46337. if (!sound.source || !sound.source.buffer) { return; }
  46338. sound.stop();
  46339. });
  46340. }
  46341. });
  46342. },{"../core/component":100,"../lib/three":146,"../utils/bind":161,"../utils/debug":163}],85:[function(_dereq_,module,exports){
  46343. var createTextGeometry = _dereq_('three-bmfont-text');
  46344. var loadBMFont = _dereq_('load-bmfont');
  46345. var path = _dereq_('path');
  46346. var registerComponent = _dereq_('../core/component').registerComponent;
  46347. var coreShader = _dereq_('../core/shader');
  46348. var THREE = _dereq_('../lib/three');
  46349. var utils = _dereq_('../utils/');
  46350. var error = utils.debug('components:text:error');
  46351. var shaders = coreShader.shaders;
  46352. var warn = utils.debug('components:text:warn');
  46353. // 1 to match other A-Frame default widths.
  46354. var DEFAULT_WIDTH = 1;
  46355. // @bryik set anisotropy to 16. Improves look of large amounts of text when viewed from angle.
  46356. var MAX_ANISOTROPY = 16;
  46357. var FONT_BASE_URL = 'https://cdn.aframe.io/fonts/';
  46358. var FONTS = {
  46359. aileronsemibold: FONT_BASE_URL + 'Aileron-Semibold.fnt',
  46360. dejavu: FONT_BASE_URL + 'DejaVu-sdf.fnt',
  46361. exo2bold: FONT_BASE_URL + 'Exo2Bold.fnt',
  46362. exo2semibold: FONT_BASE_URL + 'Exo2SemiBold.fnt',
  46363. kelsonsans: FONT_BASE_URL + 'KelsonSans.fnt',
  46364. monoid: FONT_BASE_URL + 'Monoid.fnt',
  46365. mozillavr: FONT_BASE_URL + 'mozillavr.fnt',
  46366. roboto: FONT_BASE_URL + 'Roboto-msdf.json',
  46367. sourcecodepro: FONT_BASE_URL + 'SourceCodePro.fnt'
  46368. };
  46369. var MSDF_FONTS = ['roboto'];
  46370. var DEFAULT_FONT = 'roboto';
  46371. module.exports.FONTS = FONTS;
  46372. var cache = new PromiseCache();
  46373. var fontWidthFactors = {};
  46374. /**
  46375. * SDF-based text component.
  46376. * Based on https://github.com/Jam3/three-bmfont-text.
  46377. *
  46378. * All the stock fonts are for the `sdf` registered shader, an improved version of jam3's
  46379. * original `sdf` shader.
  46380. */
  46381. module.exports.Component = registerComponent('text', {
  46382. multiple: true,
  46383. schema: {
  46384. align: {type: 'string', default: 'left', oneOf: ['left', 'right', 'center']},
  46385. alphaTest: {default: 0.5},
  46386. // `anchor` defaults to center to match geometries.
  46387. anchor: {default: 'center', oneOf: ['left', 'right', 'center', 'align']},
  46388. baseline: {default: 'center', oneOf: ['top', 'center', 'bottom']},
  46389. color: {type: 'color', default: '#FFF'},
  46390. font: {type: 'string', default: DEFAULT_FONT},
  46391. // `fontImage` defaults to the font name as a .png (e.g., mozillavr.fnt -> mozillavr.png).
  46392. fontImage: {type: 'string'},
  46393. // `height` has no default, will be populated at layout.
  46394. height: {type: 'number'},
  46395. letterSpacing: {type: 'number', default: 0},
  46396. // `lineHeight` defaults to font's `lineHeight` value.
  46397. lineHeight: {type: 'number'},
  46398. opacity: {type: 'number', default: '1.0'},
  46399. shader: {default: 'sdf', oneOf: shaders},
  46400. side: {default: 'front', oneOf: ['front', 'back', 'double']},
  46401. tabSize: {default: 4},
  46402. transparent: {default: true},
  46403. value: {type: 'string'},
  46404. whiteSpace: {default: 'normal', oneOf: ['normal', 'pre', 'nowrap']},
  46405. // `width` defaults to geometry width if present, else `DEFAULT_WIDTH`.
  46406. width: {type: 'number'},
  46407. // `wrapCount` units are about one default font character. Wrap roughly at this number.
  46408. wrapCount: {type: 'number', default: 40},
  46409. // `wrapPixels` will wrap using bmfont pixel units (e.g., dejavu's is 32 pixels).
  46410. wrapPixels: {type: 'number'},
  46411. // `yOffset` to adjust generated fonts from tools that may have incorrect metrics.
  46412. yOffset: {type: 'number', default: 0},
  46413. // `zOffset` will provide a small z offset to avoid z-fighting.
  46414. zOffset: {type: 'number', default: 0.001}
  46415. },
  46416. init: function () {
  46417. this.texture = new THREE.Texture();
  46418. this.texture.anisotropy = MAX_ANISOTROPY;
  46419. this.geometry = createTextGeometry();
  46420. this.createOrUpdateMaterial();
  46421. this.mesh = new THREE.Mesh(this.geometry, this.material);
  46422. this.el.setObject3D(this.attrName, this.mesh);
  46423. },
  46424. update: function (oldData) {
  46425. var data = coerceData(this.data);
  46426. var font = this.currentFont;
  46427. // Update material.
  46428. this.createOrUpdateMaterial();
  46429. // New font. `updateFont` will later change data and layout.
  46430. if (oldData.font !== data.font) {
  46431. this.updateFont();
  46432. return;
  46433. }
  46434. // Update geometry and layout.
  46435. if (font) {
  46436. updateGeometry(this.geometry, data, font);
  46437. this.updateLayout(data);
  46438. }
  46439. },
  46440. /**
  46441. * Clean up geometry, material, texture, mesh, objects.
  46442. */
  46443. remove: function () {
  46444. this.geometry.dispose();
  46445. this.geometry = null;
  46446. this.el.removeObject3D(this.attrName);
  46447. this.material.dispose();
  46448. this.material = null;
  46449. this.texture.dispose();
  46450. this.texture = null;
  46451. if (this.shaderObject) {
  46452. delete this.shaderObject;
  46453. }
  46454. },
  46455. /**
  46456. * Update the shader of the material.
  46457. */
  46458. createOrUpdateMaterial: function () {
  46459. var data = this.data;
  46460. var hasChangedShader;
  46461. var material = this.material;
  46462. var NewShader;
  46463. var shaderData;
  46464. var shaderName;
  46465. // Infer shader if using a stock font (or from `-msdf` filename convention).
  46466. shaderName = data.shader;
  46467. if (MSDF_FONTS.indexOf(data.font) !== -1 || data.font.indexOf('-msdf.') >= 0) {
  46468. shaderName = 'msdf';
  46469. } else if (data.font in FONTS && MSDF_FONTS.indexOf(data.font) === -1) {
  46470. shaderName = 'sdf';
  46471. }
  46472. hasChangedShader = (this.shaderObject && this.shaderObject.name) !== shaderName;
  46473. shaderData = {
  46474. alphaTest: data.alphaTest,
  46475. color: data.color,
  46476. map: this.texture,
  46477. opacity: data.opacity,
  46478. side: parseSide(data.side),
  46479. transparent: data.transparent
  46480. };
  46481. // Shader has not changed, do an update.
  46482. if (!hasChangedShader) {
  46483. // Update shader material.
  46484. this.shaderObject.update(shaderData);
  46485. // Apparently, was not set on `init` nor `update`.
  46486. material.transparent = shaderData.transparent;
  46487. updateBaseMaterial(material, shaderData);
  46488. return;
  46489. }
  46490. // Shader has changed. Create a shader material.
  46491. NewShader = createShader(this.el, shaderName, shaderData);
  46492. this.material = NewShader.material;
  46493. this.shaderObject = NewShader.shader;
  46494. // Set new shader material.
  46495. updateBaseMaterial(this.material, shaderData);
  46496. if (this.mesh) { this.mesh.material = this.material; }
  46497. },
  46498. /**
  46499. * Load font for geometry, load font image for material, and apply.
  46500. */
  46501. updateFont: function () {
  46502. var data = this.data;
  46503. var el = this.el;
  46504. var fontSrc;
  46505. var geometry = this.geometry;
  46506. var self = this;
  46507. if (!data.font) { warn('No font specified. Using the default font.'); }
  46508. // Make invisible during font swap.
  46509. this.mesh.visible = false;
  46510. // Look up font URL to use, and perform cached load.
  46511. fontSrc = this.lookupFont(data.font || DEFAULT_FONT) || data.font;
  46512. cache.get(fontSrc, function doLoadFont () {
  46513. return loadFont(fontSrc, data.yOffset);
  46514. }).then(function setFont (font) {
  46515. var coercedData;
  46516. var fontImgSrc;
  46517. if (font.pages.length !== 1) {
  46518. throw new Error('Currently only single-page bitmap fonts are supported.');
  46519. }
  46520. if (!fontWidthFactors[fontSrc]) {
  46521. font.widthFactor = fontWidthFactors[font] = computeFontWidthFactor(font);
  46522. }
  46523. // Update geometry given font metrics.
  46524. coercedData = coerceData(data);
  46525. updateGeometry(geometry, data, font);
  46526. // Set font and update layout.
  46527. self.currentFont = font;
  46528. self.updateLayout(coercedData);
  46529. // Look up font image URL to use, and perform cached load.
  46530. fontImgSrc = data.fontImage || fontSrc.replace(/(\.fnt)|(\.json)/, '.png') ||
  46531. path.dirname(data.font) + '/' + font.pages[0];
  46532. cache.get(fontImgSrc, function () {
  46533. return loadTexture(fontImgSrc);
  46534. }).then(function (image) {
  46535. // Make mesh visible and apply font image as texture.
  46536. self.mesh.visible = true;
  46537. self.texture.image = image;
  46538. self.texture.needsUpdate = true;
  46539. el.emit('textfontset', {font: data.font, fontObj: font});
  46540. }).catch(function (err) {
  46541. error(err);
  46542. throw err;
  46543. });
  46544. }).catch(function (err) {
  46545. error(err);
  46546. throw err;
  46547. });
  46548. },
  46549. /**
  46550. * Update layout with anchor, alignment, baseline, and considering any meshes.
  46551. */
  46552. updateLayout: function (data) {
  46553. var anchor;
  46554. var baseline;
  46555. var el = this.el;
  46556. var geometry = this.geometry;
  46557. var geometryComponent = el.getAttribute('geometry');
  46558. var height;
  46559. var layout = geometry.layout;
  46560. var mesh = this.mesh;
  46561. var textRenderWidth;
  46562. var textScale;
  46563. var width;
  46564. var x;
  46565. var y;
  46566. // Determine width to use (defined width, geometry's width, or default width).
  46567. geometryComponent = el.getAttribute('geometry');
  46568. width = data.width || (geometryComponent && geometryComponent.width) || DEFAULT_WIDTH;
  46569. // Determine wrap pixel count. Either specified or by experimental fudge factor.
  46570. // Note that experimental factor will never be correct for variable width fonts.
  46571. textRenderWidth = computeWidth(data.wrapPixels, data.wrapCount,
  46572. this.currentFont.widthFactor);
  46573. textScale = width / textRenderWidth;
  46574. // Determine height to use.
  46575. height = textScale * (layout.height + layout.descender);
  46576. // Update geometry dimensions to match text layout if width and height are set to 0.
  46577. // For example, scales a plane to fit text.
  46578. if (geometryComponent) {
  46579. if (!geometryComponent.width) { el.setAttribute('geometry', 'width', width); }
  46580. if (!geometryComponent.height) { el.setAttribute('geometry', 'height', height); }
  46581. }
  46582. // Calculate X position to anchor text left, center, or right.
  46583. anchor = data.anchor === 'align' ? data.align : data.anchor;
  46584. if (anchor === 'left') {
  46585. x = 0;
  46586. } else if (anchor === 'right') {
  46587. x = -1 * layout.width;
  46588. } else if (anchor === 'center') {
  46589. x = -1 * layout.width / 2;
  46590. } else {
  46591. throw new TypeError('Invalid text.anchor property value', anchor);
  46592. }
  46593. // Calculate Y position to anchor text top, center, or bottom.
  46594. baseline = data.baseline;
  46595. if (baseline === 'bottom') {
  46596. y = 0;
  46597. } else if (baseline === 'top') {
  46598. y = -1 * layout.height + layout.ascender;
  46599. } else if (baseline === 'center') {
  46600. y = -1 * layout.height / 2;
  46601. } else {
  46602. throw new TypeError('Invalid text.baseline property value', baseline);
  46603. }
  46604. // Position and scale mesh to apply layout.
  46605. mesh.position.x = x * textScale;
  46606. mesh.position.y = y * textScale;
  46607. // Place text slightly in front to avoid Z-fighting.
  46608. mesh.position.z = data.zOffset;
  46609. mesh.scale.set(textScale, -1 * textScale, textScale);
  46610. this.geometry.computeBoundingSphere();
  46611. },
  46612. /**
  46613. * Grab font from the constant.
  46614. * Set as a method for test stubbing purposes.
  46615. */
  46616. lookupFont: function (key) {
  46617. return FONTS[key];
  46618. }
  46619. });
  46620. function parseSide (side) {
  46621. switch (side) {
  46622. case 'back': {
  46623. return THREE.BackSide;
  46624. }
  46625. case 'double': {
  46626. return THREE.DoubleSide;
  46627. }
  46628. default: {
  46629. return THREE.FrontSide;
  46630. }
  46631. }
  46632. }
  46633. /**
  46634. * Coerce some data to numbers.
  46635. * as they will be passed directly into text creation and update
  46636. */
  46637. function coerceData (data) {
  46638. data = utils.clone(data);
  46639. if (data.lineHeight !== undefined) {
  46640. data.lineHeight = parseFloat(data.lineHeight);
  46641. if (!isFinite(data.lineHeight)) { data.lineHeight = undefined; }
  46642. }
  46643. if (data.width !== undefined) {
  46644. data.width = parseFloat(data.width);
  46645. if (!isFinite(data.width)) { data.width = undefined; }
  46646. }
  46647. return data;
  46648. }
  46649. /**
  46650. * @returns {Promise}
  46651. */
  46652. function loadFont (src, yOffset) {
  46653. return new Promise(function (resolve, reject) {
  46654. loadBMFont(src, function (err, font) {
  46655. if (err) {
  46656. error('Error loading font', src);
  46657. reject(err);
  46658. return;
  46659. }
  46660. // Fix negative Y offsets for Roboto MSDF font from tool. Experimentally determined.
  46661. if (src.indexOf('/Roboto-msdf.json') >= 0) { yOffset = 30; }
  46662. if (yOffset) { font.chars.map(function doOffset (ch) { ch.yoffset += yOffset; }); }
  46663. resolve(font);
  46664. });
  46665. });
  46666. }
  46667. /**
  46668. * @returns {Promise}
  46669. */
  46670. function loadTexture (src) {
  46671. return new Promise(function (resolve, reject) {
  46672. new THREE.ImageLoader().load(src, function (image) {
  46673. resolve(image);
  46674. }, undefined, function () {
  46675. error('Error loading font image', src);
  46676. reject(null);
  46677. });
  46678. });
  46679. }
  46680. function createShader (el, shaderName, data) {
  46681. var shader;
  46682. var shaderObject;
  46683. // Set up Shader.
  46684. shaderObject = new shaders[shaderName].Shader();
  46685. shaderObject.el = el;
  46686. shaderObject.init(data);
  46687. shaderObject.update(data);
  46688. // Get material.
  46689. shader = shaderObject.material;
  46690. // Apparently, was not set on `init` nor `update`.
  46691. shader.transparent = data.transparent;
  46692. return {
  46693. material: shader,
  46694. shader: shaderObject
  46695. };
  46696. }
  46697. /**
  46698. * @todo Add more supported material properties (e.g., `visible`).
  46699. */
  46700. function updateBaseMaterial (material, data) {
  46701. material.side = data.side;
  46702. }
  46703. /**
  46704. * Update the text geometry using `three-bmfont-text.update`.
  46705. */
  46706. function updateGeometry (geometry, data, font) {
  46707. geometry.update(utils.extend({}, data, {
  46708. font: font,
  46709. width: computeWidth(data.wrapPixels, data.wrapCount, font.widthFactor),
  46710. text: data.value.replace(/\\n/g, '\n').replace(/\\t/g, '\t'),
  46711. lineHeight: data.lineHeight || font.common.lineHeight
  46712. }));
  46713. }
  46714. /**
  46715. * Determine wrap pixel count. Either specified or by experimental fudge factor.
  46716. * Note that experimental factor will never be correct for variable width fonts.
  46717. */
  46718. function computeWidth (wrapPixels, wrapCount, widthFactor) {
  46719. return wrapPixels || ((0.5 + wrapCount) * widthFactor);
  46720. }
  46721. /**
  46722. * Compute default font width factor to use.
  46723. */
  46724. function computeFontWidthFactor (font) {
  46725. var sum = 0;
  46726. var digitsum = 0;
  46727. var digits = 0;
  46728. font.chars.map(function (ch) {
  46729. sum += ch.xadvance;
  46730. if (ch.id >= 48 && ch.id <= 57) {
  46731. digits++;
  46732. digitsum += ch.xadvance;
  46733. }
  46734. });
  46735. return digits ? digitsum / digits : sum / font.chars.length;
  46736. }
  46737. /**
  46738. * Get or create a promise given a key and promise generator.
  46739. * @todo Move to a utility and use in other parts of A-Frame.
  46740. */
  46741. function PromiseCache () {
  46742. var cache = this.cache = {};
  46743. this.get = function (key, promiseGenerator) {
  46744. if (key in cache) {
  46745. return cache[key];
  46746. }
  46747. cache[key] = promiseGenerator();
  46748. return cache[key];
  46749. };
  46750. }
  46751. },{"../core/component":100,"../core/shader":109,"../lib/three":146,"../utils/":167,"load-bmfont":26,"path":8,"three-bmfont-text":38}],86:[function(_dereq_,module,exports){
  46752. var registerComponent = _dereq_('../core/component').registerComponent;
  46753. var THREE = _dereq_('../lib/three');
  46754. /**
  46755. * Tracked controls component.
  46756. * Interface with the gamepad API to handled tracked controllers.
  46757. * Select the appropriate controller and apply pose to the entity.
  46758. * Observe buttons state and emit appropriate events.
  46759. *
  46760. * @property {number} controller - Index of the controller in array returned by Gamepad API.
  46761. * @property {string} id - Selected controller among those returned by Gamepad API.
  46762. */
  46763. module.exports.Component = registerComponent('tracked-controls', {
  46764. schema: {
  46765. controller: {default: 0},
  46766. id: {type: 'string', default: ''},
  46767. idPrefix: {type: 'string', default: ''},
  46768. rotationOffset: {default: 0}
  46769. },
  46770. init: function () {
  46771. this.buttonStates = {};
  46772. this.previousAxis = [];
  46773. this.previousControllerPosition = new THREE.Vector3();
  46774. },
  46775. update: function () {
  46776. var controllers = this.system.controllers;
  46777. var data = this.data;
  46778. controllers = controllers.filter(hasIdOrPrefix);
  46779. // handId: 0 - right, 1 - left
  46780. this.controller = controllers[data.controller];
  46781. function hasIdOrPrefix (controller) { return data.idPrefix ? controller.id.indexOf(data.idPrefix) === 0 : controller.id === data.id; }
  46782. },
  46783. tick: function (time, delta) {
  46784. var mesh = this.el.getObject3D('mesh');
  46785. // Update mesh animations.
  46786. if (mesh && mesh.update) { mesh.update(delta / 1000); }
  46787. this.updatePose();
  46788. this.updateButtons();
  46789. },
  46790. updatePose: (function () {
  46791. var controllerEuler = new THREE.Euler();
  46792. var controllerPosition = new THREE.Vector3();
  46793. var controllerQuaternion = new THREE.Quaternion();
  46794. var deltaControllerPosition = new THREE.Vector3();
  46795. var dolly = new THREE.Object3D();
  46796. var standingMatrix = new THREE.Matrix4();
  46797. controllerEuler.order = 'YXZ';
  46798. return function () {
  46799. var controller;
  46800. var pose;
  46801. var orientation;
  46802. var position;
  46803. var el = this.el;
  46804. var vrDisplay = this.system.vrDisplay;
  46805. this.update();
  46806. controller = this.controller;
  46807. if (!controller) { return; }
  46808. pose = controller.pose;
  46809. orientation = pose.orientation || [0, 0, 0, 1];
  46810. position = pose.position || [0, 0, 0];
  46811. controllerQuaternion.fromArray(orientation);
  46812. dolly.quaternion.fromArray(orientation);
  46813. dolly.position.fromArray(position);
  46814. dolly.updateMatrix();
  46815. if (vrDisplay && vrDisplay.stageParameters) {
  46816. standingMatrix.fromArray(vrDisplay.stageParameters.sittingToStandingTransform);
  46817. dolly.applyMatrix(standingMatrix);
  46818. }
  46819. controllerEuler.setFromRotationMatrix(dolly.matrix);
  46820. controllerPosition.setFromMatrixPosition(dolly.matrix);
  46821. el.setAttribute('rotation', {
  46822. x: THREE.Math.radToDeg(controllerEuler.x),
  46823. y: THREE.Math.radToDeg(controllerEuler.y),
  46824. z: THREE.Math.radToDeg(controllerEuler.z) + this.data.rotationOffset
  46825. });
  46826. deltaControllerPosition.copy(controllerPosition).sub(this.previousControllerPosition);
  46827. this.previousControllerPosition.copy(controllerPosition);
  46828. var currentPosition = el.getAttribute('position');
  46829. el.setAttribute('position', {
  46830. x: currentPosition.x + deltaControllerPosition.x,
  46831. y: currentPosition.y + deltaControllerPosition.y,
  46832. z: currentPosition.z + deltaControllerPosition.z
  46833. });
  46834. };
  46835. })(),
  46836. updateButtons: function () {
  46837. var i;
  46838. var buttonState;
  46839. var controller = this.controller;
  46840. if (!this.controller) { return; }
  46841. for (i = 0; i < controller.buttons.length; ++i) {
  46842. buttonState = controller.buttons[i];
  46843. this.handleButton(i, buttonState);
  46844. }
  46845. this.handleAxes(controller.axes);
  46846. },
  46847. handleAxes: function (controllerAxes) {
  46848. var previousAxis = this.previousAxis;
  46849. var changed = false;
  46850. var i;
  46851. for (i = 0; i < controllerAxes.length; ++i) {
  46852. if (previousAxis[i] !== controllerAxes[i]) {
  46853. changed = true;
  46854. break;
  46855. }
  46856. }
  46857. if (!changed) { return; }
  46858. this.previousAxis = controllerAxes.slice();
  46859. this.el.emit('axismove', {axis: this.previousAxis});
  46860. },
  46861. handleButton: function (id, buttonState) {
  46862. var changed = false;
  46863. changed = changed || this.handlePress(id, buttonState);
  46864. changed = changed || this.handleTouch(id, buttonState);
  46865. changed = changed || this.handleValue(id, buttonState);
  46866. if (!changed) { return; }
  46867. this.el.emit('buttonchanged', {id: id, state: buttonState});
  46868. },
  46869. /**
  46870. * Determine whether a button press has occured and emit events as appropriate.
  46871. *
  46872. * @param {string} id - id of the button to check.
  46873. * @param {object} buttonState - state of the button to check.
  46874. * @returns {boolean} true if button press state changed, false otherwise.
  46875. */
  46876. handlePress: function (id, buttonState) {
  46877. var buttonStates = this.buttonStates;
  46878. var evtName;
  46879. var previousButtonState = buttonStates[id] = buttonStates[id] || {};
  46880. if (buttonState.pressed === previousButtonState.pressed) { return false; }
  46881. if (buttonState.pressed) {
  46882. evtName = 'down';
  46883. } else {
  46884. evtName = 'up';
  46885. }
  46886. this.el.emit('button' + evtName, {id: id});
  46887. previousButtonState.pressed = buttonState.pressed;
  46888. return true;
  46889. },
  46890. /**
  46891. * Determine whether a button touch has occured and emit events as appropriate.
  46892. *
  46893. * @param {string} id - id of the button to check.
  46894. * @param {object} buttonState - state of the button to check.
  46895. * @returns {boolean} true if button touch state changed, false otherwise.
  46896. */
  46897. handleTouch: function (id, buttonState) {
  46898. var buttonStates = this.buttonStates;
  46899. var evtName;
  46900. var previousButtonState = buttonStates[id] = buttonStates[id] || {};
  46901. if (buttonState.touched === previousButtonState.touched) { return false; }
  46902. if (buttonState.touched) {
  46903. evtName = 'start';
  46904. } else {
  46905. evtName = 'end';
  46906. }
  46907. previousButtonState.touched = buttonState.touched;
  46908. this.el.emit('touch' + evtName, {id: id, state: previousButtonState});
  46909. return true;
  46910. },
  46911. /**
  46912. * Determine whether a button value has changed.
  46913. *
  46914. * @param {string} id - id of the button to check.
  46915. * @param {object} buttonState - state of the button to check.
  46916. * @returns {boolean} true if button value changed, false otherwise.
  46917. */
  46918. handleValue: function (id, buttonState) {
  46919. var buttonStates = this.buttonStates;
  46920. var previousButtonState = buttonStates[id] = buttonStates[id] || {};
  46921. if (buttonState.value === previousButtonState.value) { return false; }
  46922. previousButtonState.value = buttonState.value;
  46923. return true;
  46924. }
  46925. });
  46926. },{"../core/component":100,"../lib/three":146}],87:[function(_dereq_,module,exports){
  46927. var registerComponent = _dereq_('../core/component').registerComponent;
  46928. /**
  46929. * Visibility component.
  46930. */
  46931. module.exports.Component = registerComponent('visible', {
  46932. schema: {default: true},
  46933. update: function () {
  46934. this.el.object3D.visible = this.data;
  46935. }
  46936. });
  46937. },{"../core/component":100}],88:[function(_dereq_,module,exports){
  46938. var registerComponent = _dereq_('../core/component').registerComponent;
  46939. var bind = _dereq_('../utils/bind');
  46940. var isControllerPresent = _dereq_('../utils/tracked-controls').isControllerPresent;
  46941. var VIVE_CONTROLLER_MODEL_OBJ_URL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.obj';
  46942. var VIVE_CONTROLLER_MODEL_OBJ_MTL = 'https://cdn.aframe.io/controllers/vive/vr_controller_vive.mtl';
  46943. var GAMEPAD_ID_PREFIX = 'OpenVR ';
  46944. /**
  46945. * Vive Controls Component
  46946. * Interfaces with vive controllers and maps Gamepad events to
  46947. * common controller buttons: trackpad, trigger, grip, menu and system
  46948. * It loads a controller model and highlights the pressed buttons
  46949. */
  46950. module.exports.Component = registerComponent('vive-controls', {
  46951. schema: {
  46952. hand: {default: 'left'},
  46953. buttonColor: {type: 'color', default: '#FAFAFA'}, // Off-white.
  46954. buttonHighlightColor: {type: 'color', default: '#22D1EE'}, // Light blue.
  46955. model: {default: true},
  46956. rotationOffset: {default: 0} // use -999 as sentinel value to auto-determine based on hand
  46957. },
  46958. // buttonId
  46959. // 0 - trackpad
  46960. // 1 - trigger ( intensity value from 0.5 to 1 )
  46961. // 2 - grip
  46962. // 3 - menu ( dispatch but better for menu options )
  46963. // 4 - system ( never dispatched on this layer )
  46964. mapping: {
  46965. axis0: 'trackpad',
  46966. axis1: 'trackpad',
  46967. button0: 'trackpad',
  46968. button1: 'trigger',
  46969. button2: 'grip',
  46970. button3: 'menu',
  46971. button4: 'system'
  46972. },
  46973. bindMethods: function () {
  46974. this.onModelLoaded = bind(this.onModelLoaded, this);
  46975. this.onControllersUpdate = bind(this.onControllersUpdate, this);
  46976. this.checkIfControllerPresent = bind(this.checkIfControllerPresent, this);
  46977. this.removeControllersUpdateListener = bind(this.removeControllersUpdateListener, this);
  46978. this.onGamepadConnected = bind(this.onGamepadConnected, this);
  46979. this.onGamepadDisconnected = bind(this.onGamepadDisconnected, this);
  46980. },
  46981. init: function () {
  46982. var self = this;
  46983. this.animationActive = 'pointing';
  46984. this.onButtonChanged = bind(this.onButtonChanged, this);
  46985. this.onButtonDown = function (evt) { self.onButtonEvent(evt.detail.id, 'down'); };
  46986. this.onButtonUp = function (evt) { self.onButtonEvent(evt.detail.id, 'up'); };
  46987. this.onButtonTouchStart = function (evt) { self.onButtonEvent(evt.detail.id, 'touchstart'); };
  46988. this.onButtonTouchEnd = function (evt) { self.onButtonEvent(evt.detail.id, 'touchend'); };
  46989. this.controllerPresent = false;
  46990. this.everGotGamepadEvent = false;
  46991. this.lastControllerCheck = 0;
  46992. this.bindMethods();
  46993. this.isControllerPresent = isControllerPresent; // to allow mock
  46994. },
  46995. addEventListeners: function () {
  46996. var el = this.el;
  46997. el.addEventListener('buttonchanged', this.onButtonChanged);
  46998. el.addEventListener('buttondown', this.onButtonDown);
  46999. el.addEventListener('buttonup', this.onButtonUp);
  47000. el.addEventListener('touchstart', this.onButtonTouchStart);
  47001. el.addEventListener('touchend', this.onButtonTouchEnd);
  47002. el.addEventListener('model-loaded', this.onModelLoaded);
  47003. },
  47004. removeEventListeners: function () {
  47005. var el = this.el;
  47006. el.removeEventListener('buttonchanged', this.onButtonChanged);
  47007. el.removeEventListener('buttondown', this.onButtonDown);
  47008. el.removeEventListener('buttonup', this.onButtonUp);
  47009. el.removeEventListener('touchstart', this.onButtonTouchStart);
  47010. el.removeEventListener('touchend', this.onButtonTouchEnd);
  47011. el.removeEventListener('model-loaded', this.onModelLoaded);
  47012. },
  47013. checkIfControllerPresent: function () {
  47014. var data = this.data;
  47015. var controller = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47016. var isPresent = this.isControllerPresent(this.el.sceneEl, GAMEPAD_ID_PREFIX, { index: controller });
  47017. if (isPresent === this.controllerPresent) { return; }
  47018. this.controllerPresent = isPresent;
  47019. if (isPresent) { this.injectTrackedControls(); } // inject track-controls
  47020. },
  47021. onGamepadConnected: function (evt) {
  47022. // for now, don't disable controller update listening, due to
  47023. // apparent issue with FF Nightly only sending one event and seeing one controller;
  47024. // this.everGotGamepadEvent = true;
  47025. // this.removeControllersUpdateListener();
  47026. this.checkIfControllerPresent();
  47027. },
  47028. onGamepadDisconnected: function (evt) {
  47029. // for now, don't disable controller update listening, due to
  47030. // apparent issue with FF Nightly only sending one event and seeing one controller;
  47031. // this.everGotGamepadEvent = true;
  47032. // this.removeControllersUpdateListener();
  47033. this.checkIfControllerPresent();
  47034. },
  47035. play: function () {
  47036. this.checkIfControllerPresent();
  47037. window.addEventListener('gamepadconnected', this.onGamepadConnected, false);
  47038. window.addEventListener('gamepaddisconnected', this.onGamepadDisconnected, false);
  47039. this.addControllersUpdateListener();
  47040. this.addEventListeners();
  47041. },
  47042. pause: function () {
  47043. window.removeEventListener('gamepadconnected', this.onGamepadConnected, false);
  47044. window.removeEventListener('gamepaddisconnected', this.onGamepadDisconnected, false);
  47045. this.removeControllersUpdateListener();
  47046. this.removeEventListeners();
  47047. },
  47048. injectTrackedControls: function () {
  47049. var el = this.el;
  47050. var data = this.data;
  47051. // handId: 0 - right, 1 - left, 2 - anything else...
  47052. var controller = data.hand === 'right' ? 0 : data.hand === 'left' ? 1 : 2;
  47053. // if we have an OpenVR Gamepad, use the fixed mapping
  47054. el.setAttribute('tracked-controls', {idPrefix: GAMEPAD_ID_PREFIX, controller: controller, rotationOffset: data.rotationOffset});
  47055. if (!this.data.model) { return; }
  47056. this.el.setAttribute('obj-model', {
  47057. obj: VIVE_CONTROLLER_MODEL_OBJ_URL,
  47058. mtl: VIVE_CONTROLLER_MODEL_OBJ_MTL
  47059. });
  47060. },
  47061. addControllersUpdateListener: function () {
  47062. this.el.sceneEl.addEventListener('controllersupdated', this.onControllersUpdate, false);
  47063. },
  47064. removeControllersUpdateListener: function () {
  47065. this.el.sceneEl.removeEventListener('controllersupdated', this.onControllersUpdate, false);
  47066. },
  47067. onControllersUpdate: function () {
  47068. if (!this.everGotGamepadEvent) { this.checkIfControllerPresent(); }
  47069. },
  47070. onButtonChanged: function (evt) {
  47071. var button = this.mapping['button' + evt.detail.id];
  47072. var buttonMeshes = this.buttonMeshes;
  47073. var value;
  47074. if (!button || !buttonMeshes || button !== 'trigger') { return; }
  47075. value = evt.detail.state.value;
  47076. buttonMeshes.trigger.rotation.x = -value * (Math.PI / 12);
  47077. },
  47078. onModelLoaded: function (evt) {
  47079. var controllerObject3D = evt.detail.model;
  47080. var buttonMeshes;
  47081. if (!this.data.model) { return; }
  47082. buttonMeshes = this.buttonMeshes = {};
  47083. buttonMeshes.grip = {
  47084. left: controllerObject3D.getObjectByName('leftgrip'),
  47085. right: controllerObject3D.getObjectByName('rightgrip')
  47086. };
  47087. buttonMeshes.menu = controllerObject3D.getObjectByName('menubutton');
  47088. buttonMeshes.system = controllerObject3D.getObjectByName('systembutton');
  47089. buttonMeshes.trackpad = controllerObject3D.getObjectByName('touchpad');
  47090. buttonMeshes.trigger = controllerObject3D.getObjectByName('trigger');
  47091. // Offset pivot point
  47092. controllerObject3D.position.set(0, -0.015, 0.04);
  47093. },
  47094. onButtonEvent: function (id, evtName) {
  47095. var buttonName = this.mapping['button' + id];
  47096. var i;
  47097. if (Array.isArray(buttonName)) {
  47098. for (i = 0; i < buttonName.length; i++) {
  47099. this.el.emit(buttonName[i] + evtName);
  47100. }
  47101. } else {
  47102. this.el.emit(buttonName + evtName);
  47103. }
  47104. this.updateModel(buttonName, evtName);
  47105. },
  47106. updateModel: function (buttonName, evtName) {
  47107. var i;
  47108. if (!this.data.model) { return; }
  47109. if (Array.isArray(buttonName)) {
  47110. for (i = 0; i < buttonName.length; i++) {
  47111. this.updateButtonModel(buttonName[i], evtName);
  47112. }
  47113. } else {
  47114. this.updateButtonModel(buttonName, evtName);
  47115. }
  47116. },
  47117. updateButtonModel: function (buttonName, state) {
  47118. var color = state === 'up' ? this.data.buttonColor : this.data.buttonHighlightColor;
  47119. var buttonMeshes = this.buttonMeshes;
  47120. if (!buttonMeshes) { return; }
  47121. if (buttonName === 'grip') {
  47122. buttonMeshes.grip.left.material.color.set(color);
  47123. buttonMeshes.grip.right.material.color.set(color);
  47124. return;
  47125. }
  47126. buttonMeshes[buttonName].material.color.set(color);
  47127. }
  47128. });
  47129. },{"../core/component":100,"../utils/bind":161,"../utils/tracked-controls":171}],89:[function(_dereq_,module,exports){
  47130. var KEYCODE_TO_CODE = _dereq_('../constants').keyboardevent.KEYCODE_TO_CODE;
  47131. var registerComponent = _dereq_('../core/component').registerComponent;
  47132. var THREE = _dereq_('../lib/three');
  47133. var utils = _dereq_('../utils/');
  47134. var bind = utils.bind;
  47135. var shouldCaptureKeyEvent = utils.shouldCaptureKeyEvent;
  47136. var CLAMP_VELOCITY = 0.00001;
  47137. var MAX_DELTA = 0.2;
  47138. /**
  47139. * WASD component to control entities using WASD keys.
  47140. */
  47141. module.exports.Component = registerComponent('wasd-controls', {
  47142. schema: {
  47143. acceleration: {default: 65},
  47144. adAxis: {default: 'x', oneOf: ['x', 'y', 'z']},
  47145. adEnabled: {default: true},
  47146. adInverted: {default: false},
  47147. easing: {default: 20},
  47148. enabled: {default: true},
  47149. fly: {default: false},
  47150. wsAxis: {default: 'z', oneOf: ['x', 'y', 'z']},
  47151. wsEnabled: {default: true},
  47152. wsInverted: {default: false}
  47153. },
  47154. init: function () {
  47155. // To keep track of the pressed keys.
  47156. this.keys = {};
  47157. this.velocity = new THREE.Vector3();
  47158. // Bind methods and add event listeners.
  47159. this.onBlur = bind(this.onBlur, this);
  47160. this.onFocus = bind(this.onFocus, this);
  47161. this.onKeyDown = bind(this.onKeyDown, this);
  47162. this.onKeyUp = bind(this.onKeyUp, this);
  47163. this.onVisibilityChange = bind(this.onVisibilityChange, this);
  47164. this.attachVisibilityEventListeners();
  47165. },
  47166. tick: function (time, delta) {
  47167. var data = this.data;
  47168. var el = this.el;
  47169. var movementVector;
  47170. var position;
  47171. var velocity = this.velocity;
  47172. // Use seconds.
  47173. delta = delta / 1000;
  47174. // Get velocity.
  47175. this.updateVelocity(delta);
  47176. if (!velocity[data.adAxis] && !velocity[data.wsAxis]) { return; }
  47177. // Get movement vector and translate position.
  47178. movementVector = this.getMovementVector(delta);
  47179. position = el.getAttribute('position');
  47180. el.setAttribute('position', {
  47181. x: position.x + movementVector.x,
  47182. y: position.y + movementVector.y,
  47183. z: position.z + movementVector.z
  47184. });
  47185. },
  47186. remove: function () {
  47187. this.removeKeyEventListeners();
  47188. this.removeVisibilityEventListeners();
  47189. },
  47190. play: function () {
  47191. this.attachKeyEventListeners();
  47192. },
  47193. pause: function () {
  47194. this.keys = {};
  47195. this.removeKeyEventListeners();
  47196. },
  47197. updateVelocity: function (delta) {
  47198. var acceleration;
  47199. var adAxis;
  47200. var adSign;
  47201. var data = this.data;
  47202. var keys = this.keys;
  47203. var velocity = this.velocity;
  47204. var wsAxis;
  47205. var wsSign;
  47206. adAxis = data.adAxis;
  47207. wsAxis = data.wsAxis;
  47208. // If FPS too low, reset velocity.
  47209. if (delta > MAX_DELTA) {
  47210. velocity[adAxis] = 0;
  47211. velocity[wsAxis] = 0;
  47212. return;
  47213. }
  47214. // Decay velocity.
  47215. if (velocity[adAxis] !== 0) {
  47216. velocity[adAxis] -= velocity[adAxis] * data.easing * delta;
  47217. }
  47218. if (velocity[wsAxis] !== 0) {
  47219. velocity[wsAxis] -= velocity[wsAxis] * data.easing * delta;
  47220. }
  47221. // Clamp velocity easing.
  47222. if (Math.abs(velocity[adAxis]) < CLAMP_VELOCITY) { velocity[adAxis] = 0; }
  47223. if (Math.abs(velocity[wsAxis]) < CLAMP_VELOCITY) { velocity[wsAxis] = 0; }
  47224. if (!data.enabled) { return; }
  47225. // Update velocity using keys pressed.
  47226. acceleration = data.acceleration;
  47227. if (data.adEnabled) {
  47228. adSign = data.adInverted ? -1 : 1;
  47229. if (keys.KeyA || keys.ArrowLeft) { velocity[adAxis] -= adSign * acceleration * delta; }
  47230. if (keys.KeyD || keys.ArrowRight) { velocity[adAxis] += adSign * acceleration * delta; }
  47231. }
  47232. if (data.wsEnabled) {
  47233. wsSign = data.wsInverted ? -1 : 1;
  47234. if (keys.KeyW || keys.ArrowUp) { velocity[wsAxis] -= wsSign * acceleration * delta; }
  47235. if (keys.KeyS || keys.ArrowDown) { velocity[wsAxis] += wsSign * acceleration * delta; }
  47236. }
  47237. },
  47238. getMovementVector: (function () {
  47239. var directionVector = new THREE.Vector3(0, 0, 0);
  47240. var rotationEuler = new THREE.Euler(0, 0, 0, 'YXZ');
  47241. return function (delta) {
  47242. var rotation = this.el.getAttribute('rotation');
  47243. var velocity = this.velocity;
  47244. directionVector.copy(velocity);
  47245. directionVector.multiplyScalar(delta);
  47246. // Absolute.
  47247. if (!rotation) { return directionVector; }
  47248. if (!this.data.fly) { rotation.x = 0; }
  47249. // Transform direction relative to heading.
  47250. rotationEuler.set(THREE.Math.degToRad(rotation.x), THREE.Math.degToRad(rotation.y), 0);
  47251. directionVector.applyEuler(rotationEuler);
  47252. return directionVector;
  47253. };
  47254. })(),
  47255. attachVisibilityEventListeners: function () {
  47256. window.addEventListener('blur', this.onBlur);
  47257. window.addEventListener('focus', this.onFocus);
  47258. document.addEventListener('visibilitychange', this.onVisibilityChange);
  47259. },
  47260. removeVisibilityEventListeners: function () {
  47261. window.removeEventListener('blur', this.onBlur);
  47262. window.removeEventListener('focus', this.onFocus);
  47263. document.removeEventListener('visibilitychange', this.onVisibilityChange);
  47264. },
  47265. attachKeyEventListeners: function () {
  47266. window.addEventListener('keydown', this.onKeyDown);
  47267. window.addEventListener('keyup', this.onKeyUp);
  47268. },
  47269. removeKeyEventListeners: function () {
  47270. window.removeEventListener('keydown', this.onKeyDown);
  47271. window.removeEventListener('keyup', this.onKeyUp);
  47272. },
  47273. onBlur: function () {
  47274. this.pause();
  47275. },
  47276. onFocus: function () {
  47277. this.play();
  47278. },
  47279. onVisibilityChange: function () {
  47280. if (document.hidden) {
  47281. this.onBlur();
  47282. } else {
  47283. this.onFocus();
  47284. }
  47285. },
  47286. onKeyDown: function (event) {
  47287. var code;
  47288. if (!shouldCaptureKeyEvent(event)) { return; }
  47289. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47290. this.keys[code] = true;
  47291. },
  47292. onKeyUp: function (event) {
  47293. var code;
  47294. code = event.code || KEYCODE_TO_CODE[event.keyCode];
  47295. this.keys[code] = false;
  47296. }
  47297. });
  47298. },{"../constants":91,"../core/component":100,"../lib/three":146,"../utils/":167}],90:[function(_dereq_,module,exports){
  47299. /**
  47300. * Animation configuration options for TWEEN.js animations.
  47301. * Used by `<a-animation>`.
  47302. */
  47303. var TWEEN = _dereq_('tween.js');
  47304. var DIRECTIONS = {
  47305. alternate: 'alternate',
  47306. alternateReverse: 'alternate-reverse',
  47307. normal: 'normal',
  47308. reverse: 'reverse'
  47309. };
  47310. var EASING_FUNCTIONS = {
  47311. 'linear': TWEEN.Easing.Linear.None,
  47312. 'ease': TWEEN.Easing.Cubic.InOut,
  47313. 'ease-in': TWEEN.Easing.Cubic.In,
  47314. 'ease-out': TWEEN.Easing.Cubic.Out,
  47315. 'ease-in-out': TWEEN.Easing.Cubic.InOut,
  47316. 'ease-cubic': TWEEN.Easing.Cubic.In,
  47317. 'ease-in-cubic': TWEEN.Easing.Cubic.In,
  47318. 'ease-out-cubic': TWEEN.Easing.Cubic.Out,
  47319. 'ease-in-out-cubic': TWEEN.Easing.Cubic.InOut,
  47320. 'ease-quad': TWEEN.Easing.Quadratic.InOut,
  47321. 'ease-in-quad': TWEEN.Easing.Quadratic.In,
  47322. 'ease-out-quad': TWEEN.Easing.Quadratic.Out,
  47323. 'ease-in-out-quad': TWEEN.Easing.Quadratic.InOut,
  47324. 'ease-quart': TWEEN.Easing.Quartic.InOut,
  47325. 'ease-in-quart': TWEEN.Easing.Quartic.In,
  47326. 'ease-out-quart': TWEEN.Easing.Quartic.Out,
  47327. 'ease-in-out-quart': TWEEN.Easing.Quartic.InOut,
  47328. 'ease-quint': TWEEN.Easing.Quintic.InOut,
  47329. 'ease-in-quint': TWEEN.Easing.Quintic.In,
  47330. 'ease-out-quint': TWEEN.Easing.Quintic.Out,
  47331. 'ease-in-out-quint': TWEEN.Easing.Quintic.InOut,
  47332. 'ease-sine': TWEEN.Easing.Sinusoidal.InOut,
  47333. 'ease-in-sine': TWEEN.Easing.Sinusoidal.In,
  47334. 'ease-out-sine': TWEEN.Easing.Sinusoidal.Out,
  47335. 'ease-in-out-sine': TWEEN.Easing.Sinusoidal.InOut,
  47336. 'ease-expo': TWEEN.Easing.Exponential.InOut,
  47337. 'ease-in-expo': TWEEN.Easing.Exponential.In,
  47338. 'ease-out-expo': TWEEN.Easing.Exponential.Out,
  47339. 'ease-in-out-expo': TWEEN.Easing.Exponential.InOut,
  47340. 'ease-circ': TWEEN.Easing.Circular.InOut,
  47341. 'ease-in-circ': TWEEN.Easing.Circular.In,
  47342. 'ease-out-circ': TWEEN.Easing.Circular.Out,
  47343. 'ease-in-out-circ': TWEEN.Easing.Circular.InOut,
  47344. 'ease-elastic': TWEEN.Easing.Elastic.InOut,
  47345. 'ease-in-elastic': TWEEN.Easing.Elastic.In,
  47346. 'ease-out-elastic': TWEEN.Easing.Elastic.Out,
  47347. 'ease-in-out-elastic': TWEEN.Easing.Elastic.InOut,
  47348. 'ease-back': TWEEN.Easing.Back.InOut,
  47349. 'ease-in-back': TWEEN.Easing.Back.In,
  47350. 'ease-out-back': TWEEN.Easing.Back.Out,
  47351. 'ease-in-out-back': TWEEN.Easing.Back.InOut,
  47352. 'ease-bounce': TWEEN.Easing.Bounce.InOut,
  47353. 'ease-in-bounce': TWEEN.Easing.Bounce.In,
  47354. 'ease-out-bounce': TWEEN.Easing.Bounce.Out,
  47355. 'ease-in-out-bounce': TWEEN.Easing.Bounce.InOut
  47356. };
  47357. var FILLS = {
  47358. backwards: 'backwards',
  47359. both: 'both',
  47360. forwards: 'forwards',
  47361. none: 'none'
  47362. };
  47363. var REPEATS = {
  47364. indefinite: 'indefinite'
  47365. };
  47366. var DEFAULTS = {
  47367. attribute: 'rotation',
  47368. begin: '',
  47369. end: '',
  47370. delay: 0,
  47371. dur: 1000,
  47372. easing: 'ease',
  47373. direction: DIRECTIONS.normal,
  47374. fill: FILLS.forwards,
  47375. from: undefined,
  47376. repeat: 0,
  47377. to: undefined
  47378. };
  47379. module.exports.defaults = DEFAULTS;
  47380. module.exports.directions = DIRECTIONS;
  47381. module.exports.easingFunctions = EASING_FUNCTIONS;
  47382. module.exports.fills = FILLS;
  47383. module.exports.repeats = REPEATS;
  47384. },{"tween.js":49}],91:[function(_dereq_,module,exports){
  47385. module.exports = {
  47386. AFRAME_INJECTED: 'aframe-injected',
  47387. DEFAULT_CAMERA_HEIGHT: 1.6,
  47388. animation: _dereq_('./animation'),
  47389. keyboardevent: _dereq_('./keyboardevent')
  47390. };
  47391. },{"./animation":90,"./keyboardevent":92}],92:[function(_dereq_,module,exports){
  47392. module.exports = {
  47393. // Tiny KeyboardEvent.code polyfill.
  47394. KEYCODE_TO_CODE: {
  47395. '38': 'ArrowUp',
  47396. '37': 'ArrowLeft',
  47397. '40': 'ArrowDown',
  47398. '39': 'ArrowRight',
  47399. '87': 'KeyW',
  47400. '65': 'KeyA',
  47401. '83': 'KeyS',
  47402. '68': 'KeyD'
  47403. }
  47404. };
  47405. },{}],93:[function(_dereq_,module,exports){
  47406. var ANode = _dereq_('./a-node');
  47407. var animationConstants = _dereq_('../constants/animation');
  47408. var coordinates = _dereq_('../utils/').coordinates;
  47409. var parseProperty = _dereq_('./schema').parseProperty;
  47410. var registerElement = _dereq_('./a-register-element').registerElement;
  47411. var TWEEN = _dereq_('tween.js');
  47412. var THREE = _dereq_('../lib/three');
  47413. var utils = _dereq_('../utils/');
  47414. var bind = utils.bind;
  47415. var getComponentProperty = utils.entity.getComponentProperty;
  47416. var DEFAULTS = animationConstants.defaults;
  47417. var DIRECTIONS = animationConstants.directions;
  47418. var EASING_FUNCTIONS = animationConstants.easingFunctions;
  47419. var FILLS = animationConstants.fills;
  47420. var REPEATS = animationConstants.repeats;
  47421. var isCoordinate = coordinates.isCoordinate;
  47422. /**
  47423. * Animation element that applies Tween animation to parent element (entity).
  47424. * Takes after the Web Animations spec.
  47425. *
  47426. * @member {number} count - Decrementing counter for how many cycles of animations left to
  47427. * run.
  47428. * @member {Element} el - Entity which the animation is modifying.
  47429. * @member initialValue - Value before animation started. Used to restore state.
  47430. * @member {bool} isRunning - Whether animation is currently running.
  47431. * @member {function} partialSetAttribute -
  47432. * setAttribute function that is agnostic to whether we are setting an attribute value
  47433. * or a component property value. The el and the attribute names are bundled with
  47434. * the function.
  47435. * @member {object} tween - tween.js object.
  47436. */
  47437. module.exports.AAnimation = registerElement('a-animation', {
  47438. prototype: Object.create(ANode.prototype, {
  47439. createdCallback: {
  47440. value: function () {
  47441. this.bindMethods();
  47442. this.isRunning = false;
  47443. this.partialSetAttribute = function () { /* no-op */ };
  47444. this.tween = null;
  47445. }
  47446. },
  47447. attachedCallback: {
  47448. value: function () {
  47449. this.el = this.parentNode;
  47450. this.handleMixinUpdate();
  47451. this.update();
  47452. this.load();
  47453. }
  47454. },
  47455. attributeChangedCallback: {
  47456. value: function (attr, oldVal, newVal) {
  47457. if (!this.hasLoaded || !this.isRunning) { return; }
  47458. this.stop();
  47459. this.handleMixinUpdate();
  47460. this.update();
  47461. }
  47462. },
  47463. detachedCallback: {
  47464. value: function () {
  47465. if (!this.isRunning) { return; }
  47466. this.stop();
  47467. }
  47468. },
  47469. /**
  47470. * Builds a Tween object to handle animations.
  47471. * Uses tween.js's from, to, delay, easing, repeat, onUpdate, and onComplete.
  47472. * Note: tween.js takes objects for its `from` and `to` values.
  47473. *
  47474. * @returns {object}
  47475. */
  47476. getTween: {
  47477. value: function () {
  47478. var self = this;
  47479. var data = self.data;
  47480. var el = self.el;
  47481. var animationValues;
  47482. var attribute = data.attribute;
  47483. var delay = parseInt(data.delay, 10);
  47484. var currentValue = getComponentProperty(el, attribute);
  47485. var direction = self.getDirection(data.direction);
  47486. var easing = EASING_FUNCTIONS[data.easing];
  47487. var fill = data.fill;
  47488. var from;
  47489. var repeat = data.repeat === REPEATS.indefinite ? Infinity : 0;
  47490. var to;
  47491. var toTemp;
  47492. var yoyo = false;
  47493. animationValues = getAnimationValues(el, attribute, data.from || self.initialValue, data.to, currentValue);
  47494. from = animationValues.from;
  47495. to = animationValues.to;
  47496. self.partialSetAttribute = animationValues.partialSetAttribute;
  47497. if (self.count === undefined) {
  47498. self.count = repeat === Infinity ? 0 : parseInt(data.repeat, 10);
  47499. }
  47500. if (isNaN(delay)) { delay = 0; }
  47501. // Store initial state.
  47502. self.initialValue = self.initialValue || cloneValue(currentValue);
  47503. // Handle indefinite + forwards + alternate yoyo edge-case (#405).
  47504. if (repeat === Infinity && fill === FILLS.forwards &&
  47505. [DIRECTIONS.alternate,
  47506. DIRECTIONS.alternateReverse].indexOf(data.direction) !== -1) {
  47507. yoyo = true;
  47508. }
  47509. // If reversing, swap from and to.
  47510. if (direction === DIRECTIONS.reverse) {
  47511. toTemp = to;
  47512. to = cloneValue(from);
  47513. from = cloneValue(toTemp);
  47514. }
  47515. // If fill is backwards or both, start animation at the specified from.
  47516. if ([FILLS.backwards, FILLS.both].indexOf(fill) !== -1) {
  47517. self.partialSetAttribute(from);
  47518. }
  47519. // Create Tween.
  47520. return new TWEEN.Tween(cloneValue(from))
  47521. .to(to, data.dur)
  47522. .delay(delay)
  47523. .easing(easing)
  47524. .repeat(repeat)
  47525. .yoyo(yoyo)
  47526. .onUpdate(function () {
  47527. self.partialSetAttribute(this);
  47528. })
  47529. .onComplete(bind(self.onCompleted, self));
  47530. }
  47531. },
  47532. /**
  47533. * Animation parameters changed. Stop current animation, get a new one, and start it.
  47534. */
  47535. update: {
  47536. value: function () {
  47537. var data = this.data;
  47538. // Terminology warning if infinite used instead of indefinite
  47539. if (data.repeat === 'infinite') {
  47540. console.warn("Using 'infinite' as 'repeat' value is invalid. Use 'indefinite' instead.");
  47541. }
  47542. // Deprecation warning for begin when used as a delay.
  47543. if (data.begin !== '' && !isNaN(data.begin)) {
  47544. console.warn("Using 'begin' to specify a delay is deprecated. Use 'delay' instead.");
  47545. data.delay = data.begin;
  47546. data.begin = '';
  47547. }
  47548. var begin = data.begin;
  47549. var end = data.end;
  47550. // Cancel previous event listeners
  47551. if (this.evt) { this.removeEventListeners(this.evt); }
  47552. // Store new event name.
  47553. this.evt = {begin: begin, end: end};
  47554. // Add new event listeners
  47555. this.addEventListeners(this.evt);
  47556. // If `begin` is not defined, start the animation right away.
  47557. if (begin === '') {
  47558. this.stop();
  47559. this.start();
  47560. }
  47561. },
  47562. writable: window.debug
  47563. },
  47564. /**
  47565. * Callback for when a cycle of an animation is complete. Handles when to completely
  47566. * finish the animation.
  47567. *
  47568. * If `repeat` is set to a value, this method is called after each repeat. Repeats are
  47569. * handled by ending the current animation and creating a new one with `count` updated.
  47570. * Note that this method is *not* called if repeat is set to `indefinite`.
  47571. */
  47572. onCompleted: {
  47573. value: function () {
  47574. var data = this.data;
  47575. this.isRunning = false;
  47576. if ([FILLS.backwards, FILLS.none].indexOf(data.fill) !== -1) {
  47577. this.partialSetAttribute(this.initialValue);
  47578. }
  47579. if (this.count === 0) {
  47580. this.count = undefined;
  47581. this.emit('animationend');
  47582. return;
  47583. }
  47584. this.isRunning = false;
  47585. this.count--;
  47586. this.start();
  47587. }
  47588. },
  47589. start: {
  47590. value: function () {
  47591. var self = this;
  47592. // Postpone animation start until the entity has loaded
  47593. if (!this.el.hasLoaded) {
  47594. this.el.addEventListener('loaded', function () { self.start(); });
  47595. return;
  47596. }
  47597. if (this.isRunning || !this.el.isPlaying) { return; }
  47598. this.tween = this.getTween();
  47599. this.isRunning = true;
  47600. this.tween.start();
  47601. this.emit('animationstart');
  47602. },
  47603. writable: true
  47604. },
  47605. stop: {
  47606. value: function () {
  47607. var tween = this.tween;
  47608. if (!tween) { return; }
  47609. tween.stop();
  47610. this.isRunning = false;
  47611. if ([FILLS.backwards, FILLS.none].indexOf(this.data.fill) !== -1) {
  47612. this.partialSetAttribute(this.initialValue);
  47613. }
  47614. this.emit('animationstop');
  47615. },
  47616. writable: true
  47617. },
  47618. /**
  47619. * Handle alternating directions. Given the current direction, calculate the next one,
  47620. * and store the current one.
  47621. *
  47622. * @param {string} direction
  47623. * @returns {string} Direction that the next individual cycle of the animation will go
  47624. * towards.
  47625. */
  47626. getDirection: {
  47627. value: function (direction) {
  47628. if (direction === DIRECTIONS.alternate) {
  47629. this.prevDirection =
  47630. this.prevDirection === DIRECTIONS.normal ? DIRECTIONS.reverse : DIRECTIONS.normal;
  47631. return this.prevDirection;
  47632. }
  47633. if (direction === DIRECTIONS.alternateReverse) {
  47634. this.prevDirection =
  47635. this.prevDirection === DIRECTIONS.reverse ? DIRECTIONS.normal : DIRECTIONS.reverse;
  47636. return this.prevDirection;
  47637. }
  47638. return direction;
  47639. }
  47640. },
  47641. /**
  47642. * Preemptive binding to attach/detach event listeners (see `update`).
  47643. */
  47644. bindMethods: {
  47645. value: function () {
  47646. this.start = bind(this.start, this);
  47647. this.stop = bind(this.stop, this);
  47648. this.onStateAdded = bind(this.onStateAdded, this);
  47649. this.onStateRemoved = bind(this.onStateRemoved, this);
  47650. }
  47651. },
  47652. addEventListeners: {
  47653. value: function (evts) {
  47654. var el = this.el;
  47655. var self = this;
  47656. utils.splitString(evts.begin).forEach(function (evt) {
  47657. el.addEventListener(evt, self.start);
  47658. });
  47659. utils.splitString(evts.end).forEach(function (evt) {
  47660. el.addEventListener(evt, self.stop);
  47661. });
  47662. // If "begin" is an event name, wait. If it is not defined, start.
  47663. if (evts.begin === '') { el.addEventListener('play', this.start); }
  47664. el.addEventListener('pause', this.stop);
  47665. el.addEventListener('stateadded', this.onStateAdded);
  47666. el.addEventListener('stateremoved', this.onStateRemoved);
  47667. }
  47668. },
  47669. removeEventListeners: {
  47670. value: function (evts) {
  47671. var el = this.el;
  47672. var start = this.start;
  47673. var stop = this.stop;
  47674. utils.splitString(evts.begin).forEach(function (evt) {
  47675. el.removeEventListener(evt, start);
  47676. });
  47677. utils.splitString(evts.end).forEach(function (evt) {
  47678. el.removeEventListener(evt, stop);
  47679. });
  47680. el.removeEventListener('stateadded', this.onStateAdded);
  47681. el.removeEventListener('stateremoved', this.onStateRemoved);
  47682. }
  47683. },
  47684. onStateAdded: {
  47685. value: function (evt) {
  47686. if (evt.detail.state === this.data.begin) { this.start(); }
  47687. },
  47688. writable: true
  47689. },
  47690. onStateRemoved: {
  47691. value: function (evt) {
  47692. if (evt.detail.state === this.data.begin) { this.stop(); }
  47693. },
  47694. writable: true
  47695. },
  47696. /**
  47697. * Applies animation data from a mixin element.
  47698. * Works the same as component mixins but reimplemented because animations
  47699. * aren't components.
  47700. */
  47701. handleMixinUpdate: {
  47702. value: function () {
  47703. var data = {};
  47704. var elData;
  47705. var mixinData;
  47706. var mixinEl;
  47707. // Get mixin data.
  47708. mixinEl = document.querySelector('#' + this.getAttribute('mixin'));
  47709. mixinData = mixinEl ? utils.getElData(mixinEl, DEFAULTS) : {};
  47710. elData = utils.getElData(this, DEFAULTS);
  47711. utils.extend(data, DEFAULTS, mixinData, elData);
  47712. this.data = data;
  47713. }
  47714. }
  47715. })
  47716. });
  47717. function cloneValue (val) {
  47718. return utils.extend({}, val);
  47719. }
  47720. /**
  47721. * Deduces different animation values based on whether we are:
  47722. * - animating an inner attribute of a component.
  47723. * - animating a coordinate component.
  47724. * - animating a boolean.
  47725. * - animating a number.
  47726. *
  47727. * @param {Element} el
  47728. * @param {string} attribute - Tells what to animate based on whether it is dot-separated.
  47729. * @param {string} dataFrom - Data `from` value.
  47730. * @param {string} dataTo - Data `to` value.
  47731. * @param currentValue
  47732. * @returns {object}
  47733. * Object with keys [from, to, partialSetAttribute].
  47734. * `from` and `to`
  47735. * Objects where key is attribute being animated and value is value.
  47736. * `partialSetAttribute`
  47737. * Closured-function that tells tween how to update the component.
  47738. */
  47739. function getAnimationValues (el, attribute, dataFrom, dataTo, currentValue) {
  47740. var attributeSplit = attribute.split('.');
  47741. var schema;
  47742. var component;
  47743. var componentPropName;
  47744. var componentName;
  47745. var from = {};
  47746. var partialSetAttribute;
  47747. var to = {};
  47748. if (attributeSplit.length === 2) {
  47749. if (isColor()) {
  47750. getForColorComponent();
  47751. } else {
  47752. getForComponentAttribute();
  47753. }
  47754. } else if (dataTo && isCoordinate(dataTo)) {
  47755. getForCoordinateComponent();
  47756. } else if (['true', 'false'].indexOf(dataTo) !== -1) {
  47757. getForBoolean();
  47758. } else if (isNaN(dataTo)) {
  47759. getForColorComponent();
  47760. } else {
  47761. getForNumber();
  47762. }
  47763. return {
  47764. from: from,
  47765. partialSetAttribute: partialSetAttribute,
  47766. to: to
  47767. };
  47768. /**
  47769. * Match the schema type to color
  47770. * @return {bool} if the schema is of type color
  47771. */
  47772. function isColor () {
  47773. var componentName = attributeSplit[0];
  47774. var propertyName = attributeSplit[1];
  47775. var component = el.components[componentName];
  47776. var schema = component && component.schema;
  47777. return schema && schema[propertyName] && schema[propertyName].type === 'color';
  47778. }
  47779. /**
  47780. * Animating a component that has multiple attributes (e.g., geometry.width).
  47781. */
  47782. function getForComponentAttribute () {
  47783. componentName = attributeSplit[0];
  47784. componentPropName = attributeSplit[1];
  47785. component = el.components[componentName];
  47786. if (!component) {
  47787. el.setAttribute(componentName, '');
  47788. component = el.components[componentName];
  47789. }
  47790. schema = component.schema;
  47791. if (dataFrom === undefined) { // dataFrom can be 0.
  47792. from[attribute] = getComponentProperty(el, attribute);
  47793. } else {
  47794. from[attribute] = dataFrom;
  47795. }
  47796. from[attribute] = parseProperty(from[attribute], schema[componentPropName]);
  47797. to[attribute] = parseProperty(dataTo, schema[componentPropName]);
  47798. partialSetAttribute = function (value) {
  47799. if (!(attribute in value)) { return; }
  47800. el.setAttribute(componentName, componentPropName, value[attribute]);
  47801. };
  47802. }
  47803. /**
  47804. * Animating a component that is an XYZ coordinate (e.g., position).
  47805. * Will be tweening {x, y, z} all at once.
  47806. */
  47807. function getForCoordinateComponent () {
  47808. from = dataFrom ? coordinates.parse(dataFrom) : currentValue;
  47809. to = coordinates.parse(dataTo);
  47810. partialSetAttribute = function (value) {
  47811. el.setAttribute(attribute, value);
  47812. };
  47813. }
  47814. /**
  47815. * Animation a boolean (e.g., visible).
  47816. * Have to convert from boolean to an integer (0 is false, > 0 is true) for tween.
  47817. */
  47818. function getForBoolean () {
  47819. if (dataFrom === undefined) {
  47820. from[attribute] = false;
  47821. } else {
  47822. from[attribute] = strToBool(dataFrom);
  47823. }
  47824. from[attribute] = boolToNum(from[attribute]);
  47825. to[attribute] = boolToNum(strToBool(dataTo));
  47826. partialSetAttribute = function (value) {
  47827. el.setAttribute(attribute, !!value[attribute]);
  47828. };
  47829. }
  47830. /**
  47831. * Animating a color component
  47832. * Will convert a hex value to a THREE.Color
  47833. * Then converts to hex for the setAttribute
  47834. */
  47835. function getForColorComponent () {
  47836. from = new THREE.Color(dataFrom);
  47837. to = new THREE.Color(dataTo);
  47838. partialSetAttribute = function (value) {
  47839. if (attributeSplit.length > 1) {
  47840. el.setAttribute(attributeSplit[0], attributeSplit[1], rgbVectorToHex(value));
  47841. }
  47842. el.setAttribute(attribute, rgbVectorToHex(value));
  47843. };
  47844. }
  47845. /**
  47846. * Animating a numbered attribute (e.g., opacity).
  47847. */
  47848. function getForNumber () {
  47849. if (dataFrom === undefined) { // dataFrom can be 0.
  47850. from[attribute] = parseFloat(el.getAttribute(attribute));
  47851. } else {
  47852. from[attribute] = parseFloat(dataFrom);
  47853. }
  47854. to[attribute] = parseFloat(dataTo);
  47855. partialSetAttribute = function (value) {
  47856. el.setAttribute(attribute, value[attribute]);
  47857. };
  47858. }
  47859. }
  47860. module.exports.getAnimationValues = getAnimationValues;
  47861. /**
  47862. * Converts string to bool.
  47863. *
  47864. * @param {string} str - `true` or `false`.
  47865. * @returns {bool}
  47866. */
  47867. function strToBool (str) {
  47868. if (str === 'true') { return true; }
  47869. return false;
  47870. }
  47871. /**
  47872. * Converts boolean to number.
  47873. *
  47874. * @param {bool}
  47875. * @returns {number}
  47876. */
  47877. function boolToNum (bool) {
  47878. return bool ? 1 : 0;
  47879. }
  47880. /**
  47881. * Converts a number 0-255 to hex
  47882. * @param {number} color number 0 - 255
  47883. * @returns {string} hex value of number bassed
  47884. */
  47885. function componentToHex (color) {
  47886. var hex = color.toString(16);
  47887. return hex.length === 1 ? '0' + hex : hex;
  47888. }
  47889. /**
  47890. * Clamps a number to 0-1
  47891. * Then converts that number to 0-255
  47892. * @param {number} color number 0 - 1
  47893. * @returns {number} color number 0 - 255
  47894. */
  47895. function convertToIntegerColor (color) {
  47896. return Math.floor(Math.min(Math.abs(color), 1) * 255);
  47897. }
  47898. /**
  47899. * Converts a rgb object into a hex string
  47900. * @param {object} color { r: 1, g: 1, b: 1 }
  47901. * @returns {string} hex value #ffffff
  47902. */
  47903. function rgbVectorToHex (color) {
  47904. return '#' + ['r', 'g', 'b'].map(function (prop) {
  47905. return componentToHex(convertToIntegerColor(color[prop]));
  47906. }).join('');
  47907. }
  47908. },{"../constants/animation":90,"../lib/three":146,"../utils/":167,"./a-node":98,"./a-register-element":99,"./schema":108,"tween.js":49}],94:[function(_dereq_,module,exports){
  47909. var ANode = _dereq_('./a-node');
  47910. var bind = _dereq_('../utils/bind');
  47911. var debug = _dereq_('../utils/debug');
  47912. var registerElement = _dereq_('./a-register-element').registerElement;
  47913. var THREE = _dereq_('../lib/three');
  47914. var fileLoader = new THREE.FileLoader();
  47915. var warn = debug('core:a-assets:warn');
  47916. /**
  47917. * Asset management system. Handles blocking on asset loading.
  47918. */
  47919. module.exports = registerElement('a-assets', {
  47920. prototype: Object.create(ANode.prototype, {
  47921. createdCallback: {
  47922. value: function () {
  47923. this.isAssets = true;
  47924. this.fileLoader = fileLoader;
  47925. this.timeout = null;
  47926. }
  47927. },
  47928. attachedCallback: {
  47929. value: function () {
  47930. var self = this;
  47931. var i;
  47932. var loaded = [];
  47933. var mediaEl;
  47934. var mediaEls;
  47935. var imgEl;
  47936. var imgEls;
  47937. var timeout;
  47938. if (!this.parentNode.isScene) {
  47939. throw new Error('<a-assets> must be a child of a <a-scene>.');
  47940. }
  47941. // Wait for <img>s.
  47942. imgEls = this.querySelectorAll('img');
  47943. for (i = 0; i < imgEls.length; i++) {
  47944. imgEl = fixUpMediaElement(imgEls[i]);
  47945. loaded.push(new Promise(function (resolve, reject) {
  47946. imgEl.onload = resolve;
  47947. imgEl.onerror = reject;
  47948. }));
  47949. }
  47950. // Wait for <audio>s and <video>s.
  47951. mediaEls = this.querySelectorAll('audio, video');
  47952. for (i = 0; i < mediaEls.length; i++) {
  47953. mediaEl = fixUpMediaElement(mediaEls[i]);
  47954. loaded.push(mediaElementLoaded(mediaEl));
  47955. }
  47956. // Trigger loaded for scene to start rendering.
  47957. Promise.all(loaded).then(bind(this.load, this));
  47958. // Timeout to start loading anyways.
  47959. timeout = parseInt(this.getAttribute('timeout'), 10) || 3000;
  47960. this.timeout = setTimeout(function () {
  47961. if (self.hasLoaded) { return; }
  47962. warn('Asset loading timed out in ', timeout, 'ms');
  47963. self.emit('timeout');
  47964. self.load();
  47965. }, timeout);
  47966. }
  47967. },
  47968. detachedCallback: {
  47969. value: function () {
  47970. if (this.timeout) { clearTimeout(this.timeout); }
  47971. }
  47972. },
  47973. load: {
  47974. value: function () {
  47975. ANode.prototype.load.call(this, null, function waitOnFilter (el) {
  47976. return el.isAssetItem && el.hasAttribute('src');
  47977. });
  47978. }
  47979. }
  47980. })
  47981. });
  47982. /**
  47983. * Preload using XHRLoader for any type of asset.
  47984. */
  47985. registerElement('a-asset-item', {
  47986. prototype: Object.create(ANode.prototype, {
  47987. createdCallback: {
  47988. value: function () {
  47989. this.data = null;
  47990. this.isAssetItem = true;
  47991. }
  47992. },
  47993. attachedCallback: {
  47994. value: function () {
  47995. var self = this;
  47996. var src = this.getAttribute('src');
  47997. fileLoader.load(src, function handleOnLoad (textResponse) {
  47998. THREE.Cache.files[src] = textResponse;
  47999. self.data = textResponse;
  48000. /*
  48001. Workaround for a Chrome bug. If another XHR is sent to the same url before the
  48002. previous one closes, the second request never finishes.
  48003. setTimeout finishes the first request and lets the logic triggered by load open
  48004. subsequent requests.
  48005. setTimeout can be removed once the fix for the bug below ships:
  48006. 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
  48007. */
  48008. setTimeout(function load () { ANode.prototype.load.call(self); });
  48009. }, function handleOnProgress (xhr) {
  48010. self.emit('progress', {
  48011. loadedBytes: xhr.loaded,
  48012. totalBytes: xhr.total,
  48013. xhr: xhr
  48014. });
  48015. }, function handleOnError (xhr) {
  48016. self.emit('error', {xhr: xhr});
  48017. });
  48018. }
  48019. }
  48020. })
  48021. });
  48022. /**
  48023. * Create a Promise that resolves once the media element has finished buffering.
  48024. *
  48025. * @param {Element} el - HTMLMediaElement.
  48026. * @returns {Promise}
  48027. */
  48028. function mediaElementLoaded (el) {
  48029. if (!el.hasAttribute('autoplay') && el.getAttribute('preload') !== 'auto') {
  48030. return;
  48031. }
  48032. // If media specifies autoplay or preload, wait until media is completely buffered.
  48033. return new Promise(function (resolve, reject) {
  48034. if (el.readyState === 4) { return resolve(); } // Already loaded.
  48035. if (el.error) { return reject(); } // Error.
  48036. el.addEventListener('loadeddata', checkProgress, false);
  48037. el.addEventListener('progress', checkProgress, false);
  48038. el.addEventListener('error', reject, false);
  48039. function checkProgress () {
  48040. // Add up the seconds buffered.
  48041. var secondsBuffered = 0;
  48042. for (var i = 0; i < el.buffered.length; i++) {
  48043. secondsBuffered += el.buffered.end(i) - el.buffered.start(i);
  48044. }
  48045. // Compare seconds buffered to media duration.
  48046. if (secondsBuffered >= el.duration) {
  48047. resolve();
  48048. }
  48049. }
  48050. });
  48051. }
  48052. /**
  48053. * Automatically add attributes to media elements where convenient.
  48054. * crossorigin, playsinline.
  48055. */
  48056. function fixUpMediaElement (mediaEl) {
  48057. // Cross-origin.
  48058. var newMediaEl = setCrossOrigin(mediaEl);
  48059. // Plays inline for mobile.
  48060. if (newMediaEl.tagName === 'VIDEO') {
  48061. newMediaEl.setAttribute('playsinline', '');
  48062. newMediaEl.setAttribute('webkit-playsinline', '');
  48063. }
  48064. if (newMediaEl !== mediaEl) {
  48065. mediaEl.parentNode.appendChild(newMediaEl);
  48066. mediaEl.parentNode.removeChild(mediaEl);
  48067. }
  48068. return newMediaEl;
  48069. }
  48070. /**
  48071. * Automatically set `crossorigin` if not defined on the media element.
  48072. * If it is not defined, we must create and re-append a new media element <img> and
  48073. * have the browser re-request it with `crossorigin` set.
  48074. *
  48075. * @param {Element} Media element (e.g., <img>, <audio>, <video>).
  48076. * @returns {Element} Media element to be used to listen to for loaded events.
  48077. */
  48078. function setCrossOrigin (mediaEl) {
  48079. var newMediaEl;
  48080. var src;
  48081. // Already has crossorigin set.
  48082. if (mediaEl.hasAttribute('crossorigin')) { return mediaEl; }
  48083. src = mediaEl.getAttribute('src');
  48084. if (src !== null) {
  48085. // Does not have protocol.
  48086. if (src.indexOf('://') === -1) { return mediaEl; }
  48087. // Determine if cross origin is actually needed.
  48088. if (extractDomain(src) === window.location.host) { return mediaEl; }
  48089. }
  48090. warn('Cross-origin element was requested without `crossorigin` set. ' +
  48091. 'A-Frame will re-request the asset with `crossorigin` attribute set.', src);
  48092. mediaEl.crossOrigin = 'anonymous';
  48093. newMediaEl = mediaEl.cloneNode(true);
  48094. return newMediaEl;
  48095. }
  48096. /**
  48097. * Extract domain out of URL.
  48098. *
  48099. * @param {string} url
  48100. * @returns {string}
  48101. */
  48102. function extractDomain (url) {
  48103. // Find and remove protocol (e.g., http, ftp, etc.) to get domain.
  48104. var domain = url.indexOf('://') > -1 ? url.split('/')[2] : url.split('/')[0];
  48105. // Find and remove port number.
  48106. return domain.split(':')[0];
  48107. }
  48108. },{"../lib/three":146,"../utils/bind":161,"../utils/debug":163,"./a-node":98,"./a-register-element":99}],95:[function(_dereq_,module,exports){
  48109. /* global HTMLElement */
  48110. var debug = _dereq_('../utils/debug');
  48111. var registerElement = _dereq_('./a-register-element').registerElement;
  48112. var warn = debug('core:cubemap:warn');
  48113. /**
  48114. * Cubemap element that handles validation and exposes list of URLs.
  48115. * Does not listen to updates.
  48116. */
  48117. module.exports = registerElement('a-cubemap', {
  48118. prototype: Object.create(HTMLElement.prototype, {
  48119. /**
  48120. * Calculates this.srcs.
  48121. */
  48122. attachedCallback: {
  48123. value: function () {
  48124. this.srcs = this.validate();
  48125. },
  48126. writable: window.debug
  48127. },
  48128. /**
  48129. * Checks for exactly six elements with [src].
  48130. * Does not check explicitly for <img>s in case user does not want
  48131. * prefetching.
  48132. *
  48133. * @returns {Array|null} - six URLs if valid, else null.
  48134. */
  48135. validate: {
  48136. value: function () {
  48137. var elements = this.querySelectorAll('[src]');
  48138. var i;
  48139. var srcs = [];
  48140. if (elements.length === 6) {
  48141. for (i = 0; i < elements.length; i++) {
  48142. srcs.push(elements[i].getAttribute('src'));
  48143. }
  48144. return srcs;
  48145. }
  48146. // Else if there are not six elements, throw a warning.
  48147. warn(
  48148. '<a-cubemap> did not contain exactly six elements each with a ' +
  48149. '`src` attribute.');
  48150. },
  48151. writable: window.debug
  48152. }
  48153. })
  48154. });
  48155. },{"../utils/debug":163,"./a-register-element":99}],96:[function(_dereq_,module,exports){
  48156. /* global HTMLElement */
  48157. var ANode = _dereq_('./a-node');
  48158. var COMPONENTS = _dereq_('./component').components;
  48159. var registerElement = _dereq_('./a-register-element').registerElement;
  48160. var THREE = _dereq_('../lib/three');
  48161. var utils = _dereq_('../utils/');
  48162. var AEntity;
  48163. var bind = utils.bind;
  48164. var debug = utils.debug('core:a-entity:debug');
  48165. var warn = utils.debug('core:a-entity:warn');
  48166. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48167. /**
  48168. * Entity is a container object that components are plugged into to comprise everything in
  48169. * the scene. In A-Frame, they inherently have position, rotation, and scale.
  48170. *
  48171. * To be able to take components, the scene element inherits from the entity definition.
  48172. *
  48173. * @member {object} components - entity's currently initialized components.
  48174. * @member {object} object3D - three.js object.
  48175. * @member {array} states
  48176. * @member {boolean} isPlaying - false if dynamic behavior of the entity is paused.
  48177. */
  48178. var proto = Object.create(ANode.prototype, {
  48179. defaultComponents: {
  48180. value: {
  48181. position: '',
  48182. rotation: '',
  48183. scale: '',
  48184. visible: ''
  48185. }
  48186. },
  48187. createdCallback: {
  48188. value: function () {
  48189. this.components = {};
  48190. this.isEntity = true;
  48191. this.isPlaying = false;
  48192. this.object3D = new THREE.Group();
  48193. this.object3D.el = this;
  48194. this.object3DMap = {};
  48195. this.parentEl = null;
  48196. this.states = [];
  48197. }
  48198. },
  48199. /**
  48200. * Handle changes coming from the browser DOM inspector.
  48201. */
  48202. attributeChangedCallback: {
  48203. value: function (attr, oldVal, newVal) {
  48204. var component = this.components[attr];
  48205. // If the empty string is passed by the component initialization
  48206. // logic we ignore the component update.
  48207. if (component && component.justInitialized && newVal === '') {
  48208. delete component.justInitialized;
  48209. return;
  48210. }
  48211. // When a component is removed after calling el.removeAttribute('material')
  48212. if (!component && newVal === null) { return; }
  48213. this.setEntityAttribute(attr, oldVal, newVal);
  48214. }
  48215. },
  48216. /**
  48217. * Add to parent, load, play.
  48218. */
  48219. attachedCallback: {
  48220. value: function () {
  48221. var assetsEl; // Asset management system element.
  48222. var sceneEl = this.sceneEl;
  48223. var self = this; // Component.
  48224. this.addToParent();
  48225. // Don't .load() scene on attachedCallback.
  48226. if (this.isScene) { return; }
  48227. // Gracefully not error when outside of <a-scene> (e.g., tests).
  48228. if (!sceneEl) {
  48229. this.load();
  48230. return;
  48231. }
  48232. // Wait for asset management system to finish before loading.
  48233. assetsEl = sceneEl.querySelector('a-assets');
  48234. if (assetsEl && !assetsEl.hasLoaded) {
  48235. assetsEl.addEventListener('loaded', function () { self.load(); });
  48236. return;
  48237. }
  48238. this.load();
  48239. }
  48240. },
  48241. /**
  48242. * Tell parent to remove this element's object3D from its object3D.
  48243. * Do not call on scene element because that will cause a call to document.body.remove().
  48244. */
  48245. detachedCallback: {
  48246. value: function () {
  48247. if (!this.parentEl) { return; }
  48248. // Remove components.
  48249. Object.keys(this.components).forEach(bind(this.removeComponent, this));
  48250. if (this.isScene) { return; }
  48251. this.removeFromParent();
  48252. ANode.prototype.detachedCallback.call(this);
  48253. }
  48254. },
  48255. /**
  48256. * Apply mixin to component.
  48257. */
  48258. handleMixinUpdate: {
  48259. value: function (attrName) {
  48260. if (!attrName) {
  48261. this.updateComponents();
  48262. return;
  48263. }
  48264. this.updateComponent(attrName, this.getDOMAttribute(attrName));
  48265. }
  48266. },
  48267. mapStateMixins: {
  48268. value: function (state, op) {
  48269. var mixins = this.getAttribute('mixin');
  48270. var mixinIds;
  48271. if (!mixins) { return; }
  48272. mixinIds = mixins.split(' ');
  48273. mixinIds.forEach(function (id) {
  48274. var mixinId = id + '-' + state;
  48275. op(mixinId);
  48276. });
  48277. this.updateComponents();
  48278. }
  48279. },
  48280. updateStateMixins: {
  48281. value: function (newMixins, oldMixins) {
  48282. var self = this;
  48283. oldMixins = oldMixins || '';
  48284. var newMixinsIds = newMixins.split(' ');
  48285. var oldMixinsIds = oldMixins ? oldMixins.split(' ') : [];
  48286. // The list of mixins that might have been removed on update
  48287. var diff = oldMixinsIds.filter(function (i) { return newMixinsIds.indexOf(i) < 0; });
  48288. // Remove the mixins that are gone on update
  48289. diff.forEach(function (mixinId) {
  48290. var forEach = Array.prototype.forEach;
  48291. // State Mixins
  48292. var stateMixinsEls = document.querySelectorAll('[id^=' + mixinId + '-]');
  48293. forEach.call(stateMixinsEls, function (el) {
  48294. self.unregisterMixin(el.id);
  48295. });
  48296. });
  48297. this.states.forEach(function (state) {
  48298. newMixinsIds.forEach(function (id) {
  48299. var mixinId = id + '-' + state;
  48300. self.registerMixin(mixinId);
  48301. });
  48302. });
  48303. }
  48304. },
  48305. getObject3D: {
  48306. value: function (type) {
  48307. return this.object3DMap[type];
  48308. }
  48309. },
  48310. /**
  48311. * Set a THREE.Object3D into the map.
  48312. *
  48313. * @param {string} type - Developer-set name of the type of object, will be unique per type.
  48314. * @param {object} obj - A THREE.Object3D.
  48315. */
  48316. setObject3D: {
  48317. value: function (type, obj) {
  48318. var oldObj;
  48319. var self = this;
  48320. if (!(obj instanceof THREE.Object3D)) {
  48321. throw new Error(
  48322. '`Entity.setObject3D` was called with an object that was not an instance of ' +
  48323. 'THREE.Object3D.'
  48324. );
  48325. }
  48326. // Remove existing object of the type.
  48327. oldObj = this.getObject3D(type);
  48328. if (oldObj) { this.object3D.remove(oldObj); }
  48329. // Set references to A-Frame entity.
  48330. obj.el = this;
  48331. if (obj.children.length) {
  48332. obj.traverse(function bindEl (child) {
  48333. child.el = self;
  48334. });
  48335. }
  48336. // Add.
  48337. this.object3D.add(obj);
  48338. this.object3DMap[type] = obj;
  48339. this.emit('object3dset', {object: obj, type: type});
  48340. }
  48341. },
  48342. /**
  48343. * Remove object from scene and entity object3D map.
  48344. */
  48345. removeObject3D: {
  48346. value: function (type) {
  48347. var obj = this.getObject3D(type);
  48348. if (!obj) {
  48349. warn('Tried to remove `Object3D` of type:', type, 'which was not defined.');
  48350. return;
  48351. }
  48352. this.object3D.remove(obj);
  48353. delete this.object3DMap[type];
  48354. this.emit('object3dremove', {type: type});
  48355. }
  48356. },
  48357. /**
  48358. * Gets or creates an object3D of a given type.
  48359. *
  48360. * @param {string} type - Type of the object3D.
  48361. * @param {string} Constructor - Constructor to use to create the object3D if needed.
  48362. * @returns {object}
  48363. */
  48364. getOrCreateObject3D: {
  48365. value: function (type, Constructor) {
  48366. var object3D = this.getObject3D(type);
  48367. if (!object3D && Constructor) {
  48368. object3D = new Constructor();
  48369. this.setObject3D(type, object3D);
  48370. }
  48371. return object3D;
  48372. }
  48373. },
  48374. /**
  48375. * Add child entity.
  48376. *
  48377. * @param {Element} el - Child entity.
  48378. */
  48379. add: {
  48380. value: function (el) {
  48381. if (!el.object3D) {
  48382. throw new Error("Trying to add an element that doesn't have an `object3D`");
  48383. }
  48384. this.object3D.add(el.object3D);
  48385. this.emit('child-attached', { el: el });
  48386. }
  48387. },
  48388. /**
  48389. * Tell parentNode to add this entity to itself.
  48390. */
  48391. addToParent: {
  48392. value: function () {
  48393. var parentNode = this.parentEl = this.parentNode;
  48394. // `!parentNode` check primarily for unit tests.
  48395. if (!parentNode || !parentNode.add || this.attachedToParent) { return; }
  48396. parentNode.add(this);
  48397. this.attachedToParent = true; // To prevent multiple attachments to same parent.
  48398. }
  48399. },
  48400. /**
  48401. * Tell parentNode to remove this entity from itself.
  48402. */
  48403. removeFromParent: {
  48404. value: function () {
  48405. var parentEl = this.parentEl;
  48406. this.parentEl.remove(this);
  48407. this.attachedToParent = false;
  48408. this.parentEl = this.parentNode = null;
  48409. parentEl.emit('child-detached', {el: this});
  48410. }
  48411. },
  48412. load: {
  48413. value: function () {
  48414. var self = this;
  48415. if (this.hasLoaded) { return; }
  48416. ANode.prototype.load.call(this, function entityLoadCallback () {
  48417. self.updateComponents();
  48418. if (self.isScene || self.parentEl.isPlaying) { self.play(); }
  48419. });
  48420. },
  48421. writable: window.debug
  48422. },
  48423. /**
  48424. * Remove child entity.
  48425. *
  48426. * @param {Element} el - Child entity.
  48427. */
  48428. remove: {
  48429. value: function (el) {
  48430. this.object3D.remove(el.object3D);
  48431. }
  48432. },
  48433. /**
  48434. * @returns {array} Direct children that are entities.
  48435. */
  48436. getChildEntities: {
  48437. value: function () {
  48438. var children = this.children;
  48439. var childEntities = [];
  48440. for (var i = 0; i < children.length; i++) {
  48441. var child = children[i];
  48442. if (child instanceof AEntity) {
  48443. childEntities.push(child);
  48444. }
  48445. }
  48446. return childEntities;
  48447. }
  48448. },
  48449. /**
  48450. * Initialize component.
  48451. *
  48452. * @param {string} attrName - Attribute name asociated to the component.
  48453. * @param {object} data - Component data
  48454. * @param {boolean} isDependency - True if the component is a dependency.
  48455. */
  48456. initComponent: {
  48457. value: function (attrName, data, isDependency) {
  48458. var component;
  48459. var componentInfo = attrName.split(MULTIPLE_COMPONENT_DELIMITER);
  48460. var componentId = componentInfo[1];
  48461. var componentName = componentInfo[0];
  48462. var isComponentDefined = checkComponentDefined(this, attrName) || data !== undefined;
  48463. // Not a registered component.
  48464. if (!COMPONENTS[componentName]) { return; }
  48465. // Component is not a dependency and is undefined.
  48466. // If a component is a dependency, then it is okay to have no data.
  48467. if (!isComponentDefined && !isDependency) { return; }
  48468. // Component already initialized.
  48469. if (attrName in this.components) { return; }
  48470. // Initialize dependencies first
  48471. this.initComponentDependencies(componentName);
  48472. // If component name has an id we check component type multiplic
  48473. if (componentId && !COMPONENTS[componentName].multiple) {
  48474. throw new Error('Trying to initialize multiple ' +
  48475. 'components of type `' + componentName +
  48476. '`. There can only be one component of this type per entity.');
  48477. }
  48478. component = this.components[attrName] = new COMPONENTS[componentName].Component(
  48479. this, data, componentId);
  48480. if (this.isPlaying) { component.play(); }
  48481. // Components are reflected in the DOM as attributes but the state is not shown
  48482. // hence we set the attribute to empty string.
  48483. // The flag justInitialized is for attributeChangedCallback to not overwrite
  48484. // the component with the empty string.
  48485. if (!this.hasAttribute(attrName)) {
  48486. component.justInitialized = true;
  48487. HTMLElement.prototype.setAttribute.call(this, attrName, '');
  48488. }
  48489. debug('Component initialized: %s', attrName);
  48490. },
  48491. writable: window.debug
  48492. },
  48493. /**
  48494. * Initialize dependencies of a component.
  48495. *
  48496. * @param {string} name - Root component name.
  48497. */
  48498. initComponentDependencies: {
  48499. value: function (name) {
  48500. var self = this;
  48501. var component = COMPONENTS[name];
  48502. var dependencies;
  48503. // Not a component.
  48504. if (!component) { return; }
  48505. // No dependencies.
  48506. dependencies = COMPONENTS[name].dependencies;
  48507. if (!dependencies) { return; }
  48508. // Initialize dependencies.
  48509. dependencies.forEach(function initializeDependency (componentName) {
  48510. // Call getAttribute to initialize the data from the DOM.
  48511. self.initComponent(
  48512. componentName,
  48513. HTMLElement.prototype.getAttribute.call(self, componentName) || undefined,
  48514. true
  48515. );
  48516. });
  48517. }
  48518. },
  48519. removeComponent: {
  48520. value: function (name) {
  48521. var component;
  48522. var isDefault;
  48523. var isMixedIn;
  48524. // Don't remove default or mixed-in components.
  48525. isDefault = name in this.defaultComponents;
  48526. isMixedIn = isComponentMixedIn(name, this.mixinEls);
  48527. if (isDefault || isMixedIn) { return; }
  48528. component = this.components[name];
  48529. component.pause();
  48530. component.remove();
  48531. delete this.components[name];
  48532. this.emit('componentremoved', {
  48533. id: component.id,
  48534. name: name
  48535. });
  48536. }
  48537. },
  48538. /**
  48539. * Initialize or update all components.
  48540. * Build data using initial components, defined attributes, mixins, and defaults.
  48541. * Update default components before the rest.
  48542. *
  48543. * @member {function} getExtraComponents - Can be implemented to include component data
  48544. * from other sources (e.g., implemented by primitives).
  48545. */
  48546. updateComponents: {
  48547. value: function () {
  48548. var componentsToUpdate = {};
  48549. var extraComponents = {};
  48550. var i;
  48551. var self = this;
  48552. if (!this.hasLoaded) { return; }
  48553. // Gather mixin-defined components.
  48554. getMixedInComponents(this).forEach(addComponent);
  48555. // Gather from extra initial component data if defined (e.g., primitives).
  48556. if (this.getExtraComponents) {
  48557. extraComponents = this.getExtraComponents();
  48558. Object.keys(extraComponents).forEach(addComponent);
  48559. }
  48560. // Gather entity-defined components.
  48561. for (i = 0; i < this.attributes.length; ++i) {
  48562. addComponent(this.attributes[i].name);
  48563. }
  48564. // Initialze or update default components first.
  48565. Object.keys(this.defaultComponents).forEach(doUpdateComponent);
  48566. // Initialize or update rest of components.
  48567. Object.keys(componentsToUpdate).forEach(doUpdateComponent);
  48568. /**
  48569. * Add component to the list to initialize or update.
  48570. */
  48571. function addComponent (componentName) {
  48572. var name = componentName.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  48573. if (!COMPONENTS[name]) { return; }
  48574. componentsToUpdate[componentName] = true;
  48575. }
  48576. /**
  48577. * Get component data and initialize or update component.
  48578. */
  48579. function doUpdateComponent (name) {
  48580. // Build defined component data.
  48581. var data = mergeComponentData(self.getDOMAttribute(name), extraComponents[name]);
  48582. delete componentsToUpdate[name];
  48583. self.updateComponent(name, data);
  48584. }
  48585. }
  48586. },
  48587. /**
  48588. * Initialize, update, or remove a single component.
  48589. *
  48590. * When initializing, we set the component on `this.components`.
  48591. *
  48592. * @param {string} attr - Component name.
  48593. * @param {object} attrValue - The value of the DOM attribute.
  48594. */
  48595. updateComponent: {
  48596. value: function (attr, attrValue) {
  48597. var component = this.components[attr];
  48598. var isDefault = attr in this.defaultComponents;
  48599. if (component) {
  48600. if (attrValue === null && !isDefault) {
  48601. this.removeComponent(attr);
  48602. return;
  48603. }
  48604. // Component already initialized. Update component.
  48605. component.updateProperties(attrValue);
  48606. return;
  48607. }
  48608. // Component not yet initialized. Initialize component.
  48609. this.initComponent(attr, attrValue, false);
  48610. }
  48611. },
  48612. /**
  48613. * Updates one property of the component
  48614. *
  48615. * @param {string} name - Component name
  48616. * @param {string} property - Component property name
  48617. * @param {any} propertyValue - New property value
  48618. */
  48619. updateComponentProperty: {
  48620. value: function (name, property, propertyValue) {
  48621. var component = this.components[name];
  48622. // Cached attribute value
  48623. var attrValue = component && component.attrValue;
  48624. // Copy cached value
  48625. var componentObj = attrValue ? utils.extend({}, attrValue) : {};
  48626. componentObj[property] = propertyValue;
  48627. this.updateComponent(name, componentObj);
  48628. }
  48629. },
  48630. /**
  48631. * If `attr` is a component name, detach the component from the entity.
  48632. *
  48633. * If `propertyName` is given, reset the component property value to its default.
  48634. *
  48635. * @param {string} attr - Attribute name, which could also be a component name.
  48636. * @param {string} propertyName - Component prop name, if resetting an individual prop.
  48637. */
  48638. removeAttribute: {
  48639. value: function (attr, propertyName) {
  48640. var component = this.components[attr];
  48641. // Remove component.
  48642. if (component && propertyName === undefined) {
  48643. this.setEntityAttribute(attr, undefined, null);
  48644. // Do not remove the component from the DOM if default component.
  48645. if (this.components[attr]) { return; }
  48646. }
  48647. // Reset component property value.
  48648. if (component && propertyName !== undefined) {
  48649. component.resetProperty(propertyName);
  48650. return;
  48651. }
  48652. HTMLElement.prototype.removeAttribute.call(this, attr);
  48653. }
  48654. },
  48655. /**
  48656. * Start dynamic behavior associated with entity such as dynamic components and animations.
  48657. * Tell all children entities to also play.
  48658. */
  48659. play: {
  48660. value: function () {
  48661. var components = this.components;
  48662. var componentKeys = Object.keys(components);
  48663. // Already playing.
  48664. if (this.isPlaying || !this.hasLoaded) { return; }
  48665. this.isPlaying = true;
  48666. // Wake up all components.
  48667. componentKeys.forEach(function playComponent (key) {
  48668. components[key].play();
  48669. });
  48670. // Tell all child entities to play.
  48671. this.getChildEntities().forEach(function play (entity) {
  48672. entity.play();
  48673. });
  48674. this.emit('play');
  48675. },
  48676. writable: true
  48677. },
  48678. /**
  48679. * Pause dynamic behavior associated with entity such as dynamic components and animations.
  48680. * Tell all children entities to also pause.
  48681. */
  48682. pause: {
  48683. value: function () {
  48684. var components = this.components;
  48685. var componentKeys = Object.keys(components);
  48686. if (!this.isPlaying) { return; }
  48687. this.isPlaying = false;
  48688. // Sleep all components.
  48689. componentKeys.forEach(function pauseComponent (key) {
  48690. components[key].pause();
  48691. });
  48692. // Tell all child entities to pause.
  48693. this.getChildEntities().forEach(function pause (obj) {
  48694. obj.pause();
  48695. });
  48696. this.emit('pause');
  48697. },
  48698. writable: true
  48699. },
  48700. /**
  48701. * Deals with updates on entity-specific attributes (i.e., components and mixins).
  48702. *
  48703. * @param {string} attr
  48704. * @param {string} oldVal
  48705. * @param {string|object} newVal
  48706. */
  48707. setEntityAttribute: {
  48708. value: function (attr, oldVal, newVal) {
  48709. if (COMPONENTS[attr] || this.components[attr]) {
  48710. this.updateComponent(attr, newVal);
  48711. return;
  48712. }
  48713. if (attr === 'mixin') {
  48714. this.mixinUpdate(newVal, oldVal);
  48715. return;
  48716. }
  48717. }
  48718. },
  48719. mixinUpdate: {
  48720. value: function (newMixins, oldMixins) {
  48721. oldMixins = oldMixins || this.getAttribute('mixin');
  48722. this.updateStateMixins(newMixins, oldMixins);
  48723. this.updateComponents();
  48724. }
  48725. },
  48726. /**
  48727. * setAttribute can:
  48728. *
  48729. * 1. Set a single property of a multi-property component.
  48730. * 2. Set multiple properties of a multi-property component.
  48731. * 3. Replace properties of a multi-property component.
  48732. * 4. Set a value for a single-property component, mixin, or normal HTML attribute.
  48733. *
  48734. * @param {string} attrName - Component or attribute name.
  48735. * @param {string|object} arg1 - Can be a property name or object of properties.
  48736. * @param {string|bool} arg2 - Can be a value, or boolean indicating whether to update or
  48737. * replace.
  48738. */
  48739. setAttribute: {
  48740. value: function (attrName, arg1, arg2) {
  48741. var componentName;
  48742. var isDebugMode;
  48743. // Determine which type of setAttribute to call based on the types of the arguments.
  48744. componentName = attrName.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  48745. if (COMPONENTS[componentName]) {
  48746. if (typeof arg1 === 'string' && typeof arg2 !== 'undefined') {
  48747. singlePropertyUpdate(this, attrName, arg1, arg2);
  48748. } else if (typeof arg1 === 'object' && arg2 === true) {
  48749. multiPropertyClobber(this, attrName, arg1);
  48750. } else {
  48751. componentUpdate(this, attrName, arg1);
  48752. }
  48753. // In debug mode, write component data up to the DOM.
  48754. isDebugMode = this.sceneEl && this.sceneEl.getAttribute('debug');
  48755. if (isDebugMode) { this.components[attrName].flushToDOM(); }
  48756. return;
  48757. } else {
  48758. normalSetAttribute(this, attrName, arg1);
  48759. }
  48760. /**
  48761. * Just update one of the component properties.
  48762. * >> setAttribute('foo', 'bar', 'baz')
  48763. */
  48764. function singlePropertyUpdate (el, componentName, propName, propertyValue) {
  48765. el.updateComponentProperty(componentName, propName, propertyValue);
  48766. }
  48767. /**
  48768. * Just update multiple component properties at once for a multi-property component.
  48769. * >> setAttribute('foo', {bar: 'baz'})
  48770. */
  48771. function componentUpdate (el, componentName, propValue) {
  48772. var component = el.components[componentName];
  48773. if (component && typeof propValue === 'object') {
  48774. // Extend existing component attribute value.
  48775. el.updateComponent(
  48776. componentName,
  48777. utils.extendDeep(utils.extendDeep({}, component.attrValue), propValue));
  48778. } else {
  48779. el.updateComponent(componentName, propValue);
  48780. }
  48781. }
  48782. /**
  48783. * Pass in complete data set for a multi-property component.
  48784. * >> setAttribute('foo', {bar: 'baz'}, true)
  48785. */
  48786. function multiPropertyClobber (el, componentName, propObject) {
  48787. el.updateComponent(componentName, propObject);
  48788. }
  48789. /**
  48790. * Just update one of the component properties.
  48791. * >> setAttribute('id', 'myEntity')
  48792. */
  48793. function normalSetAttribute (el, attrName, value) {
  48794. ANode.prototype.setAttribute.call(el, attrName, value);
  48795. if (attrName === 'mixin') { el.mixinUpdate(value); }
  48796. }
  48797. },
  48798. writable: window.debug
  48799. },
  48800. /**
  48801. * Reflect component data in the DOM (as seen from the browser DOM Inspector).
  48802. *
  48803. * @param {bool} recursive - Also flushToDOM on the children.
  48804. **/
  48805. flushToDOM: {
  48806. value: function (recursive) {
  48807. var components = this.components;
  48808. var defaultComponents = this.defaultComponents;
  48809. var child;
  48810. var children = this.children;
  48811. var i;
  48812. // Flush entity's components to DOM.
  48813. Object.keys(components).forEach(function flushComponent (componentName) {
  48814. components[componentName].flushToDOM(componentName in defaultComponents);
  48815. });
  48816. // Recurse.
  48817. if (!recursive) { return; }
  48818. for (i = 0; i < children.length; ++i) {
  48819. child = children[i];
  48820. if (!child.flushToDOM) { continue; }
  48821. child.flushToDOM(recursive);
  48822. }
  48823. }
  48824. },
  48825. /**
  48826. * If `attr` is a component, returns ALL component data including applied mixins and
  48827. * defaults.
  48828. *
  48829. * If `attr` is not a component, fall back to HTML getAttribute.
  48830. *
  48831. * @param {string} attr
  48832. * @returns {object|string} Object if component, else string.
  48833. */
  48834. getAttribute: {
  48835. value: function (attr) {
  48836. // If component, return component data.
  48837. var component = this.components[attr];
  48838. if (component) { return component.getData(); }
  48839. return HTMLElement.prototype.getAttribute.call(this, attr);
  48840. },
  48841. writable: window.debug
  48842. },
  48843. /**
  48844. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  48845. * what `getAttribute` is now. Now legacy code.
  48846. *
  48847. * @param {string} attr
  48848. * @returns {object|string} Object if component, else string.
  48849. */
  48850. getComputedAttribute: {
  48851. value: function (attr) {
  48852. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  48853. return this.getAttribute(attr);
  48854. }
  48855. },
  48856. /**
  48857. * If `attr` is a component, returns JUST the component data defined on the entity.
  48858. * Like a partial version of `getComputedAttribute` as returned component data
  48859. * does not include applied mixins or defaults.
  48860. *
  48861. * If `attr` is not a component, fall back to HTML getAttribute.
  48862. *
  48863. * @param {string} attr
  48864. * @returns {object|string} Object if component, else string.
  48865. */
  48866. getDOMAttribute: {
  48867. value: function (attr) {
  48868. // If cached value exists, return partial component data.
  48869. var component = this.components[attr];
  48870. if (component) { return component.attrValue; }
  48871. return HTMLElement.prototype.getAttribute.call(this, attr);
  48872. },
  48873. writable: window.debug
  48874. },
  48875. addState: {
  48876. value: function (state) {
  48877. if (this.is(state)) { return; }
  48878. this.states.push(state);
  48879. this.mapStateMixins(state, bind(this.registerMixin, this));
  48880. this.emit('stateadded', {state: state});
  48881. }
  48882. },
  48883. removeState: {
  48884. value: function (state) {
  48885. var stateIndex = this.states.indexOf(state);
  48886. if (stateIndex === -1) { return; }
  48887. this.states.splice(stateIndex, 1);
  48888. this.mapStateMixins(state, bind(this.unregisterMixin, this));
  48889. this.emit('stateremoved', {state: state});
  48890. }
  48891. },
  48892. /**
  48893. * Checks if the element is in a given state. e.g. el.is('alive');
  48894. * @type {string} state - Name of the state we want to check
  48895. */
  48896. is: {
  48897. value: function (state) {
  48898. return this.states.indexOf(state) !== -1;
  48899. }
  48900. }
  48901. });
  48902. /**
  48903. * Check if a component is *defined* for an entity, including defaults and mixins.
  48904. * Does not check whether the component has been *initialized* for an entity.
  48905. *
  48906. * @param {string} el - Entity.
  48907. * @param {string} name - Component name.
  48908. * @returns {boolean}
  48909. */
  48910. function checkComponentDefined (el, name) {
  48911. // Check if default components contain the component.
  48912. if (el.defaultComponents[name] !== undefined) { return true; }
  48913. // Check if element contains the component.
  48914. if (el.components[name] && el.components[name].attrValue) { return true; }
  48915. return isComponentMixedIn(name, el.mixinEls);
  48916. }
  48917. function getMixedInComponents (entityEl) {
  48918. var components = [];
  48919. entityEl.mixinEls.forEach(function getMixedComponents (mixinEl) {
  48920. Object.keys(mixinEl.componentCache).forEach(addComponent);
  48921. function addComponent (key) {
  48922. components.push(key);
  48923. }
  48924. });
  48925. return components;
  48926. }
  48927. /**
  48928. * Check if any mixins contains a component.
  48929. *
  48930. * @param {string} name - Component name.
  48931. * @param {array} mixinEls - Array of <a-mixin>s.
  48932. */
  48933. function isComponentMixedIn (name, mixinEls) {
  48934. var i;
  48935. var inMixin = false;
  48936. for (i = 0; i < mixinEls.length; ++i) {
  48937. inMixin = mixinEls[i].hasAttribute(name);
  48938. if (inMixin) { break; }
  48939. }
  48940. return inMixin;
  48941. }
  48942. /**
  48943. * Given entity defined value, merge in extra data if necessary.
  48944. * Handle both single and multi-property components.
  48945. *
  48946. * @param {string} attrValue - Entity data.
  48947. * @param extraData - Entity data from another source to merge in.
  48948. */
  48949. function mergeComponentData (attrValue, extraData) {
  48950. // Extra data not defined, just return attrValue.
  48951. if (!extraData) { return attrValue; }
  48952. // Merge multi-property data.
  48953. if (extraData.constructor === Object) {
  48954. return utils.extend(extraData, utils.styleParser.parse(attrValue || {}));
  48955. }
  48956. // Return data, precendence to the defined value.
  48957. return attrValue || extraData;
  48958. }
  48959. AEntity = registerElement('a-entity', {
  48960. prototype: proto
  48961. });
  48962. module.exports = AEntity;
  48963. },{"../lib/three":146,"../utils/":167,"./a-node":98,"./a-register-element":99,"./component":100}],97:[function(_dereq_,module,exports){
  48964. /* global HTMLElement */
  48965. var ANode = _dereq_('./a-node');
  48966. var registerElement = _dereq_('./a-register-element').registerElement;
  48967. var components = _dereq_('./component').components;
  48968. var MULTIPLE_COMPONENT_DELIMITER = '__';
  48969. /**
  48970. * @member {object} componentCache - Cache of pre-parsed values. An object where the keys
  48971. * are component names and the values are already parsed by the component.
  48972. */
  48973. module.exports = registerElement('a-mixin', {
  48974. prototype: Object.create(ANode.prototype, {
  48975. createdCallback: {
  48976. value: function () {
  48977. this.componentCache = {};
  48978. this.id = this.getAttribute('id');
  48979. }
  48980. },
  48981. attributeChangedCallback: {
  48982. value: function (attr, oldVal, newVal) {
  48983. this.cacheAttribute(attr, newVal);
  48984. }
  48985. },
  48986. attachedCallback: {
  48987. value: function () {
  48988. this.sceneEl = this.closestScene();
  48989. this.cacheAttributes();
  48990. this.updateEntities();
  48991. this.load();
  48992. }
  48993. },
  48994. /**
  48995. * setAttribute that parses and caches component values.
  48996. */
  48997. setAttribute: {
  48998. value: function (attr, value) {
  48999. this.cacheAttribute(attr, value);
  49000. HTMLElement.prototype.setAttribute.call(this, attr, value);
  49001. }
  49002. },
  49003. /**
  49004. * If `attr` is a component, then parse the value using the schema and store it.
  49005. */
  49006. cacheAttribute: {
  49007. value: function (attr, value) {
  49008. var componentName = attr.split(MULTIPLE_COMPONENT_DELIMITER)[0];
  49009. var component = components[componentName];
  49010. if (!component) { return; }
  49011. if (value === undefined) {
  49012. value = HTMLElement.prototype.getAttribute.call(this, attr);
  49013. }
  49014. this.componentCache[attr] = component.parseAttrValueForCache(value);
  49015. }
  49016. },
  49017. /**
  49018. * If `attr` is a component, then grab pre-parsed value from the cache.
  49019. * Else do a normal getAttribute.
  49020. */
  49021. getAttribute: {
  49022. value: function (attr) {
  49023. return this.componentCache[attr] ||
  49024. HTMLElement.prototype.getAttribute.call(this, attr);
  49025. }
  49026. },
  49027. /**
  49028. * Parse and cache every component defined on the mixin.
  49029. */
  49030. cacheAttributes: {
  49031. value: function () {
  49032. var attributes = this.attributes;
  49033. var attrName;
  49034. var i;
  49035. for (i = 0; i < attributes.length; i++) {
  49036. attrName = attributes[i].name;
  49037. this.cacheAttribute(attrName);
  49038. }
  49039. }
  49040. },
  49041. /**
  49042. * For entities that already have been loaded by the time the mixin was attached, tell
  49043. * those entities to register the mixin and refresh their component data.
  49044. */
  49045. updateEntities: {
  49046. value: function () {
  49047. if (!this.sceneEl) { return; }
  49048. var entities = this.sceneEl.querySelectorAll('[mixin~=' + this.id + ']');
  49049. for (var i = 0; i < entities.length; i++) {
  49050. var entity = entities[i];
  49051. if (!entity.hasLoaded) { continue; }
  49052. entity.registerMixin(this.id);
  49053. Object.keys(this.componentCache).forEach(function updateComponent (componentName) {
  49054. entity.updateComponent(componentName);
  49055. });
  49056. }
  49057. }
  49058. }
  49059. })
  49060. });
  49061. },{"./a-node":98,"./a-register-element":99,"./component":100}],98:[function(_dereq_,module,exports){
  49062. /* global HTMLElement, MutationObserver */
  49063. var registerElement = _dereq_('./a-register-element').registerElement;
  49064. var utils = _dereq_('../utils/');
  49065. var bind = utils.bind;
  49066. var warn = utils.debug('core:a-node:warn');
  49067. /**
  49068. * Base class for A-Frame that manages loading of objects.
  49069. *
  49070. * Nodes can be modified using mixins.
  49071. * Nodes emit a `loaded` event when they and their children have initialized.
  49072. */
  49073. module.exports = registerElement('a-node', {
  49074. prototype: Object.create(HTMLElement.prototype, {
  49075. createdCallback: {
  49076. value: function () {
  49077. this.hasLoaded = false;
  49078. this.isNode = true;
  49079. this.mixinEls = [];
  49080. this.mixinObservers = {};
  49081. },
  49082. writable: window.debug
  49083. },
  49084. attachedCallback: {
  49085. value: function () {
  49086. var mixins;
  49087. this.sceneEl = this.closestScene();
  49088. if (!this.sceneEl) {
  49089. warn('You are attempting to attach <' + this.tagName + '> outside of an A-Frame ' +
  49090. 'scene. Append this element to `<a-scene>` instead.');
  49091. }
  49092. this.hasLoaded = false;
  49093. this.emit('nodeready', {}, false);
  49094. mixins = this.getAttribute('mixin');
  49095. if (mixins) { this.updateMixins(mixins); }
  49096. },
  49097. writable: window.debug
  49098. },
  49099. attributeChangedCallback: {
  49100. value: function (attr, oldVal, newVal) {
  49101. if (attr === 'mixin') { this.updateMixins(newVal, oldVal); }
  49102. }
  49103. },
  49104. /**
  49105. * Returns the first scene by traversing up the tree starting from and
  49106. * including receiver element.
  49107. */
  49108. closestScene: {
  49109. value: function closest () {
  49110. var element = this;
  49111. while (element) {
  49112. if (element.isScene) { break; }
  49113. element = element.parentElement;
  49114. }
  49115. return element;
  49116. }
  49117. },
  49118. /**
  49119. * Returns first element matching a selector by traversing up the tree starting
  49120. * from and including receiver element.
  49121. *
  49122. * @param {string} selector - Selector of element to find.
  49123. */
  49124. closest: {
  49125. value: function closest (selector) {
  49126. var matches = this.matches || this.mozMatchesSelector ||
  49127. this.msMatchesSelector || this.oMatchesSelector || this.webkitMatchesSelector;
  49128. var element = this;
  49129. while (element) {
  49130. if (matches.call(element, selector)) { break; }
  49131. element = element.parentElement;
  49132. }
  49133. return element;
  49134. }
  49135. },
  49136. detachedCallback: {
  49137. value: function () {
  49138. this.hasLoaded = false;
  49139. }
  49140. },
  49141. /**
  49142. * Wait for children to load, if any.
  49143. * Then emit `loaded` event and set `hasLoaded`.
  49144. */
  49145. load: {
  49146. value: function (cb, childFilter) {
  49147. var children;
  49148. var childrenLoaded;
  49149. var self = this;
  49150. if (this.hasLoaded) { return; }
  49151. // Default to waiting for all nodes.
  49152. childFilter = childFilter || function (el) { return el.isNode; };
  49153. // Wait for children to load (if any), then load.
  49154. children = this.getChildren();
  49155. childrenLoaded = children.filter(childFilter).map(function (child) {
  49156. return new Promise(function waitForLoaded (resolve) {
  49157. if (child.hasLoaded) { return resolve(); }
  49158. child.addEventListener('loaded', resolve);
  49159. });
  49160. });
  49161. Promise.all(childrenLoaded).then(function emitLoaded () {
  49162. self.hasLoaded = true;
  49163. if (cb) { cb(); }
  49164. self.emit('loaded', {}, false);
  49165. });
  49166. },
  49167. writable: true
  49168. },
  49169. getChildren: {
  49170. value: function () {
  49171. return Array.prototype.slice.call(this.children, 0);
  49172. }
  49173. },
  49174. updateMixins: {
  49175. value: function (newMixins, oldMixins) {
  49176. var newMixinsIds = newMixins ? newMixins.trim().split(/\s+/) : [];
  49177. var oldMixinsIds = oldMixins ? oldMixins.trim().split(/\s+/) : [];
  49178. // To determine what listeners will be removed
  49179. var diff = oldMixinsIds.filter(function (i) { return newMixinsIds.indexOf(i) < 0; });
  49180. this.mixinEls = [];
  49181. diff.forEach(bind(this.unregisterMixin, this));
  49182. newMixinsIds.forEach(bind(this.registerMixin, this));
  49183. }
  49184. },
  49185. registerMixin: {
  49186. value: function (mixinId) {
  49187. if (!this.sceneEl) { return; }
  49188. var mixinEl = this.sceneEl.querySelector('a-mixin#' + mixinId);
  49189. if (!mixinEl) { return; }
  49190. this.attachMixinListener(mixinEl);
  49191. this.mixinEls.push(mixinEl);
  49192. }
  49193. },
  49194. setAttribute: {
  49195. value: function (attr, newValue) {
  49196. if (attr === 'mixin') { this.updateMixins(newValue); }
  49197. HTMLElement.prototype.setAttribute.call(this, attr, newValue);
  49198. }
  49199. },
  49200. unregisterMixin: {
  49201. value: function (mixinId) {
  49202. var mixinEls = this.mixinEls;
  49203. var mixinEl;
  49204. var i;
  49205. for (i = 0; i < mixinEls.length; ++i) {
  49206. mixinEl = mixinEls[i];
  49207. if (mixinId === mixinEl.id) {
  49208. mixinEls.splice(i, 1);
  49209. break;
  49210. }
  49211. }
  49212. this.removeMixinListener(mixinId);
  49213. }
  49214. },
  49215. removeMixinListener: {
  49216. value: function (mixinId) {
  49217. var observer = this.mixinObservers[mixinId];
  49218. if (!observer) { return; }
  49219. observer.disconnect();
  49220. this.mixinObservers[mixinId] = null;
  49221. }
  49222. },
  49223. attachMixinListener: {
  49224. value: function (mixinEl) {
  49225. var self = this;
  49226. var mixinId = mixinEl.id;
  49227. var currentObserver = this.mixinObservers[mixinId];
  49228. if (!mixinEl) { return; }
  49229. if (currentObserver) { return; }
  49230. var observer = new MutationObserver(function (mutations) {
  49231. var attr = mutations[0].attributeName;
  49232. self.handleMixinUpdate(attr);
  49233. });
  49234. var config = { attributes: true };
  49235. observer.observe(mixinEl, config);
  49236. this.mixinObservers[mixinId] = observer;
  49237. }
  49238. },
  49239. handleMixinUpdate: {
  49240. value: function () { /* no-op */ }
  49241. },
  49242. /**
  49243. * Emits a DOM event.
  49244. *
  49245. * @param {String} name
  49246. * Name of event (use a space-delimited string for multiple events).
  49247. * @param {Object=} [detail={}]
  49248. * Custom data to pass as `detail` to the event.
  49249. * @param {Boolean=} [bubbles=true]
  49250. * Whether the event should bubble.
  49251. */
  49252. emit: {
  49253. value: function (name, detail, bubbles) {
  49254. var self = this;
  49255. detail = detail || {};
  49256. if (bubbles === undefined) { bubbles = true; }
  49257. var data = { bubbles: !!bubbles, detail: detail };
  49258. return name.split(' ').map(function (eventName) {
  49259. return utils.fireEvent(self, eventName, data);
  49260. });
  49261. }
  49262. },
  49263. /**
  49264. * Returns a closure that emits a DOM event.
  49265. *
  49266. * @param {String} name
  49267. * Name of event (use a space-delimited string for multiple events).
  49268. * @param {Object} detail
  49269. * Custom data (optional) to pass as `detail` if the event is to
  49270. * be a `CustomEvent`.
  49271. * @param {Boolean} bubbles
  49272. * Whether the event should be bubble.
  49273. */
  49274. emitter: {
  49275. value: function (name, detail, bubbles) {
  49276. var self = this;
  49277. return function () {
  49278. self.emit(name, detail, bubbles);
  49279. };
  49280. }
  49281. }
  49282. })
  49283. });
  49284. },{"../utils/":167,"./a-register-element":99}],99:[function(_dereq_,module,exports){
  49285. /*
  49286. ------------------------------------------------------------
  49287. ------------- WARNING WARNING WARNING WARNING --------------
  49288. ------------------------------------------------------------
  49289. This module wraps registerElement to deal with components that inherit from
  49290. `ANode` and `AEntity`. It's a pass through in any other case.
  49291. It wraps some of the prototype methods of the created element to make sure
  49292. that the corresponding functions in the base prototypes (`AEntity` and `ANode`)
  49293. are also invoked. The method in the base prototype is always called before the one
  49294. in the derived prototype.
  49295. */
  49296. // Polyfill `document.registerElement`.
  49297. _dereq_('document-register-element');
  49298. var ANode; // Must declare before AEntity. Initialized at the bottom.
  49299. var AEntity;
  49300. var knownTags = module.exports.knownTags = {};
  49301. function addTagName (tagName) {
  49302. knownTags[tagName.toLowerCase()] = true;
  49303. }
  49304. /**
  49305. * Return whether the element type is one of our known registered ones.
  49306. *
  49307. * @param {string} node - The name of the tag to register.
  49308. * @returns {boolean} Whether the tag name matches that of our registered custom elements.
  49309. */
  49310. module.exports.isNode = function (node) {
  49311. return node.tagName.toLowerCase() in knownTags || node.isNode;
  49312. };
  49313. /**
  49314. * @param {string} tagName - The name of the tag to register.
  49315. * @param {object} obj - The prototype of the new element.
  49316. * @returns {object} The prototype of the new element.
  49317. */
  49318. module.exports.registerElement = function (tagName, obj) {
  49319. var proto = Object.getPrototypeOf(obj.prototype);
  49320. var newObj = obj;
  49321. var isANode = ANode && proto === ANode.prototype;
  49322. var isAEntity = AEntity && proto === AEntity.prototype;
  49323. if (isANode || isAEntity) { addTagName(tagName); }
  49324. // Wrap if element inherits from `ANode`.
  49325. if (isANode) {
  49326. newObj = wrapANodeMethods(obj.prototype);
  49327. newObj = {prototype: Object.create(proto, newObj)};
  49328. }
  49329. // Wrap if element inherits from `AEntity`.
  49330. if (isAEntity) {
  49331. newObj = wrapAEntityMethods(obj.prototype);
  49332. newObj = {prototype: Object.create(proto, newObj)};
  49333. }
  49334. return document.registerElement(tagName, newObj);
  49335. };
  49336. /**
  49337. * Wrap some obj methods to call those on `ANode` base prototype.
  49338. *
  49339. * @param {object} obj - Object that contains the methods that will be wrapped.
  49340. * @return {object} An object with the same properties as the input parameter but
  49341. * with some of methods wrapped.
  49342. */
  49343. function wrapANodeMethods (obj) {
  49344. var newObj = {};
  49345. var ANodeMethods = [
  49346. 'attachedCallback',
  49347. 'attributeChangedCallback',
  49348. 'createdCallback'
  49349. ];
  49350. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49351. copyProperties(obj, newObj);
  49352. return newObj;
  49353. }
  49354. /**
  49355. * This wraps some of the obj methods to call those on `AEntity` base prototype.
  49356. *
  49357. * @param {object} obj - The objects that contains the methods that will be wrapped.
  49358. * @return {object} - An object with the same properties as the input parameter but
  49359. * with some of methods wrapped.
  49360. */
  49361. function wrapAEntityMethods (obj) {
  49362. var newObj = {};
  49363. var ANodeMethods = [
  49364. 'attachedCallback',
  49365. 'attributeChangedCallback',
  49366. 'createdCallback'
  49367. ];
  49368. var AEntityMethods = [
  49369. 'attachedCallback',
  49370. 'attributeChangedCallback',
  49371. 'createdCallback',
  49372. 'detachedCallback'
  49373. ];
  49374. wrapMethods(newObj, ANodeMethods, obj, ANode.prototype);
  49375. wrapMethods(newObj, AEntityMethods, obj, AEntity.prototype);
  49376. // Copies the remaining properties into the new object.
  49377. copyProperties(obj, newObj);
  49378. return newObj;
  49379. }
  49380. /**
  49381. * Wrap a list a methods to ensure that those in the base prototype are called
  49382. * before the derived one.
  49383. *
  49384. * @param {object} targetObj - Object that will contain the wrapped methods.
  49385. * @param {array} methodList - List of methods from the derivedObj that will be wrapped.
  49386. * @param {object} derivedObject - Object that inherits from the baseObj.
  49387. * @param {object} baseObj - Object that derivedObj inherits from.
  49388. */
  49389. function wrapMethods (targetObj, methodList, derivedObj, baseObj) {
  49390. methodList.forEach(function (methodName) {
  49391. wrapMethod(targetObj, methodName, derivedObj, baseObj);
  49392. });
  49393. }
  49394. module.exports.wrapMethods = wrapMethods;
  49395. /**
  49396. * Wrap one method to ensure that the one in the base prototype is called before
  49397. * the one in the derived one.
  49398. *
  49399. * @param {object} obj - Object that will contain the wrapped method.
  49400. * @param {string} methodName - The name of the method that will be wrapped.
  49401. * @param {object} derivedObject - Object that inherits from the baseObj.
  49402. * @param {object} baseObj - Object that derivedObj inherits from.
  49403. */
  49404. function wrapMethod (obj, methodName, derivedObj, baseObj) {
  49405. var derivedMethod = derivedObj[methodName];
  49406. var baseMethod = baseObj[methodName];
  49407. // Derived prototype does not define method, no need to wrap.
  49408. if (!derivedMethod || !baseMethod) { return; }
  49409. // Derived prototype doesn't override the one in the base one, no need to wrap.
  49410. if (derivedMethod === baseMethod) { return; }
  49411. // Wrap to ensure the base method is called before the one in the derived prototype.
  49412. obj[methodName] = {
  49413. value: function wrappedMethod () {
  49414. baseMethod.apply(this, arguments);
  49415. return derivedMethod.apply(this, arguments);
  49416. },
  49417. writable: window.debug
  49418. };
  49419. }
  49420. /**
  49421. * It copies the properties from source to destination object if they don't
  49422. * exist already.
  49423. *
  49424. * @param {object} source - The object where properties are copied from.
  49425. * @param {type} destination - The object where properties are copied to.
  49426. */
  49427. function copyProperties (source, destination) {
  49428. var props = Object.getOwnPropertyNames(source);
  49429. props.forEach(function (prop) {
  49430. var desc;
  49431. if (!destination[prop]) {
  49432. desc = Object.getOwnPropertyDescriptor(source, prop);
  49433. destination[prop] = {value: source[prop], writable: desc.writable};
  49434. }
  49435. });
  49436. }
  49437. ANode = _dereq_('./a-node');
  49438. AEntity = _dereq_('./a-entity');
  49439. },{"./a-entity":96,"./a-node":98,"document-register-element":16}],100:[function(_dereq_,module,exports){
  49440. /* global HTMLElement, Node */
  49441. var schema = _dereq_('./schema');
  49442. var scenes = _dereq_('./scene/scenes');
  49443. var systems = _dereq_('./system');
  49444. var utils = _dereq_('../utils/');
  49445. var components = module.exports.components = {}; // Keep track of registered components.
  49446. var parseProperties = schema.parseProperties;
  49447. var parseProperty = schema.parseProperty;
  49448. var processSchema = schema.process;
  49449. var isSingleProp = schema.isSingleProperty;
  49450. var stringifyProperties = schema.stringifyProperties;
  49451. var stringifyProperty = schema.stringifyProperty;
  49452. var styleParser = utils.styleParser;
  49453. var warn = utils.debug('core:component:warn');
  49454. var aframeScript = document.currentScript;
  49455. var upperCaseRegExp = new RegExp('[A-Z]+');
  49456. /**
  49457. * Component class definition.
  49458. *
  49459. * Components configure appearance, modify behavior, or add functionality to
  49460. * entities. The behavior and appearance of an entity can be changed at runtime
  49461. * by adding, removing, or updating components. Entities do not share instances
  49462. * of components.
  49463. *
  49464. * @member {object} el - Reference to the entity element.
  49465. * @member {string} attrValue - Value of the corresponding HTML attribute.
  49466. * @member {object} data - Component data populated by parsing the
  49467. * mapped attribute of the component plus applying defaults and mixins.
  49468. */
  49469. var Component = module.exports.Component = function (el, attrValue, id) {
  49470. this.el = el;
  49471. this.id = id;
  49472. this.attrName = this.name + (id ? '__' + id : '');
  49473. this.updateProperties(attrValue);
  49474. };
  49475. Component.prototype = {
  49476. /**
  49477. * Contains the type schema and defaults for the data values.
  49478. * Data is coerced into the types of the values of the defaults.
  49479. */
  49480. schema: {},
  49481. /**
  49482. * Init handler. Similar to attachedCallback.
  49483. * Called during component initialization and is only run once.
  49484. * Components can use this to set initial state.
  49485. */
  49486. init: function () { /* no-op */ },
  49487. /**
  49488. * Update handler. Similar to attributeChangedCallback.
  49489. * Called whenever component's data changes.
  49490. * Also called on component initialization when the component receives initial data.
  49491. *
  49492. * @param {object} prevData - Previous attributes of the component.
  49493. */
  49494. update: function (prevData) { /* no-op */ },
  49495. updateSchema: undefined,
  49496. /**
  49497. * Tick handler.
  49498. * Called on each tick of the scene render loop.
  49499. * Affected by play and pause.
  49500. *
  49501. * @param {number} time - Scene tick time.
  49502. * @param {number} timeDelta - Difference in current render time and previous render time.
  49503. */
  49504. tick: undefined,
  49505. /**
  49506. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  49507. */
  49508. play: function () { /* no-op */ },
  49509. /**
  49510. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  49511. */
  49512. pause: function () { /* no-op */ },
  49513. /**
  49514. * Remove handler. Similar to detachedCallback.
  49515. * Called whenever component is removed from the entity (i.e., removeAttribute).
  49516. * Components can use this to reset behavior on the entity.
  49517. */
  49518. remove: function () { /* no-op */ },
  49519. /**
  49520. * Parses each property based on property type.
  49521. * If component is single-property, then parses the single property value.
  49522. *
  49523. * @param {string} value - HTML attribute value.
  49524. * @param {boolean} silent - Suppress warning messages.
  49525. * @returns {object} Component data.
  49526. */
  49527. parse: function (value, silent) {
  49528. var schema = this.schema;
  49529. if (isSingleProp(schema)) { return parseProperty(value, schema); }
  49530. return parseProperties(styleParser.parse(value), schema, true, this.name, silent);
  49531. },
  49532. /**
  49533. * Stringify properties if necessary.
  49534. *
  49535. * Only called from `Entity.setAttribute` for properties whose parsers accept a non-string
  49536. * value (e.g., selector, vec3 property types).
  49537. *
  49538. * @param {object} data - Complete component data.
  49539. * @returns {string}
  49540. */
  49541. stringify: function (data) {
  49542. var schema = this.schema;
  49543. if (typeof data === 'string') { return data; }
  49544. if (isSingleProp(schema)) { return stringifyProperty(data, schema); }
  49545. data = stringifyProperties(data, schema);
  49546. return styleParser.stringify(data);
  49547. },
  49548. /**
  49549. * Returns a copy of data such that we don't expose the private this.data.
  49550. *
  49551. * @returns {object} data
  49552. */
  49553. getData: function () {
  49554. var data = this.data;
  49555. if (typeof data !== 'object') { return data; }
  49556. return utils.extend({}, data);
  49557. },
  49558. /**
  49559. * Update the cache of the pre-parsed attribute value.
  49560. *
  49561. * @param {string} value - HTML attribute value.
  49562. */
  49563. updateCachedAttrValue: function (value) {
  49564. var isSinglePropSchema = isSingleProp(this.schema);
  49565. var attrValue = this.parseAttrValueForCache(value);
  49566. this.attrValue = extendProperties({}, attrValue, isSinglePropSchema);
  49567. },
  49568. /**
  49569. * Given an HTML attribute value parses the string
  49570. * based on the component schema. To avoid double parsings of
  49571. * strings into strings we store the original instead
  49572. * of the parsed one
  49573. *
  49574. * @param {string} value - HTML attribute value
  49575. */
  49576. parseAttrValueForCache: function (value) {
  49577. var parsedValue;
  49578. if (typeof value !== 'string') { return value; }
  49579. if (isSingleProp(this.schema)) {
  49580. parsedValue = this.schema.parse(value);
  49581. // To avoid bogus double parsings. The cached values will
  49582. // be parsed when building the component data.
  49583. // For instance when parsing a src id to it's url.
  49584. // We want to cache the original string and not the parsed
  49585. // one (#monster -> models/monster.dae) so when building
  49586. // data we parse the expected value.
  49587. if (typeof parsedValue === 'string') { parsedValue = value; }
  49588. } else {
  49589. // We just parse using the style parser to avoid double parsing
  49590. // of individual properties.
  49591. parsedValue = styleParser.parse(value);
  49592. }
  49593. return parsedValue;
  49594. },
  49595. /**
  49596. * Write cached attribute data to the entity DOM element.
  49597. *
  49598. * @param {bool} isDefault - Whether component is a default component. Always flush for
  49599. * default components.
  49600. */
  49601. flushToDOM: function (isDefault) {
  49602. var attrValue = isDefault ? this.data : this.attrValue;
  49603. if (!attrValue) { return; }
  49604. HTMLElement.prototype.setAttribute.call(this.el, this.attrName,
  49605. this.stringify(attrValue));
  49606. },
  49607. /**
  49608. * Apply new component data if data has changed.
  49609. *
  49610. * @param {string} attrValue - HTML attribute value.
  49611. * If undefined, use the cached attribute value and continue updating properties.
  49612. */
  49613. updateProperties: function (attrValue) {
  49614. var el = this.el;
  49615. var isSinglePropSchema = isSingleProp(this.schema);
  49616. var oldData = extendProperties({}, this.data, isSinglePropSchema);
  49617. if (attrValue !== undefined) { this.updateCachedAttrValue(attrValue); }
  49618. if (!el.hasLoaded) { return; }
  49619. if (this.updateSchema) {
  49620. this.updateSchema(buildData(el, this.name, this.attrName, this.schema, this.attrValue,
  49621. true));
  49622. }
  49623. this.data = buildData(el, this.name, this.attrName, this.schema, this.attrValue);
  49624. if (!this.initialized) {
  49625. // Initialize component.
  49626. this.init();
  49627. this.initialized = true;
  49628. // Play the component if the entity is playing.
  49629. this.update(oldData);
  49630. if (el.isPlaying) { this.play(); }
  49631. el.emit('componentinitialized', {
  49632. id: this.id,
  49633. name: this.name,
  49634. data: this.getData()
  49635. }, false);
  49636. } else {
  49637. // Don't update if properties haven't changed
  49638. if (utils.deepEqual(oldData, this.data)) { return; }
  49639. // Update component.
  49640. this.update(oldData);
  49641. el.emit('componentchanged', {
  49642. id: this.id,
  49643. name: this.name,
  49644. newData: this.getData(),
  49645. oldData: oldData
  49646. }, false);
  49647. }
  49648. },
  49649. /**
  49650. * Reset value of a property to the property's default value.
  49651. * If single-prop component, reset value to component's default value.
  49652. *
  49653. * @param {string} propertyName - Name of property to reset.
  49654. */
  49655. resetProperty: function (propertyName) {
  49656. if (isSingleProp(this.schema)) {
  49657. this.attrValue = undefined;
  49658. } else {
  49659. if (!(propertyName in this.attrValue)) { return; }
  49660. delete this.attrValue[propertyName];
  49661. }
  49662. this.updateProperties(this.attrValue);
  49663. },
  49664. /**
  49665. * Extend schema of component given a partial schema.
  49666. *
  49667. * Some components might want to mutate their schema based on certain properties.
  49668. * e.g., Material component changes its schema based on `shader` to account for different
  49669. * uniforms
  49670. *
  49671. * @param {object} schemaAddon - Schema chunk that extend base schema.
  49672. */
  49673. extendSchema: function (schemaAddon) {
  49674. // Clone base schema.
  49675. var extendedSchema = utils.extend({}, components[this.name].schema);
  49676. // Extend base schema with new schema chunk.
  49677. utils.extend(extendedSchema, schemaAddon);
  49678. this.schema = processSchema(extendedSchema);
  49679. this.el.emit('schemachanged', {component: this.name});
  49680. }
  49681. };
  49682. // For testing.
  49683. if (window.debug) {
  49684. var registrationOrderWarnings = module.exports.registrationOrderWarnings = {};
  49685. }
  49686. /**
  49687. * Registers a component to A-Frame.
  49688. *
  49689. * @param {string} name - Component name.
  49690. * @param {object} definition - Component schema and lifecycle method handlers.
  49691. * @returns {object} Component.
  49692. */
  49693. module.exports.registerComponent = function (name, definition) {
  49694. var NewComponent;
  49695. var proto = {};
  49696. // Warning if component is statically registered after the scene.
  49697. if (document.currentScript && document.currentScript !== aframeScript) {
  49698. scenes.forEach(function checkPosition (sceneEl) {
  49699. // Okay to register component after the scene at runtime.
  49700. if (sceneEl.hasLoaded) { return; }
  49701. // Check that component is declared before the scene.
  49702. if (document.currentScript.compareDocumentPosition(sceneEl) ===
  49703. Node.DOCUMENT_POSITION_FOLLOWING) { return; }
  49704. warn('The component `' + name + '` was registered in a <script> tag after the scene. ' +
  49705. 'Component <script> tags in an HTML file should be declared *before* the scene ' +
  49706. 'such that the component is available to entities during scene initialization.');
  49707. // For testing.
  49708. if (window.debug) { registrationOrderWarnings[name] = true; }
  49709. });
  49710. }
  49711. if (upperCaseRegExp.test(name) === true) {
  49712. warn('The component name `' + name + '` contains uppercase characters, but ' +
  49713. 'HTML will ignore the capitalization of attribute names. ' +
  49714. 'Change the name to be lowercase: `' + name.toLowerCase() + '`');
  49715. }
  49716. if (name.indexOf('__') !== -1) {
  49717. throw new Error('The component name `' + name + '` is not allowed. ' +
  49718. 'The sequence __ (double underscore) is reserved to specify an id' +
  49719. ' for multiple components of the same type');
  49720. }
  49721. // Format definition object to prototype object.
  49722. Object.keys(definition).forEach(function (key) {
  49723. proto[key] = {
  49724. value: definition[key],
  49725. writable: true
  49726. };
  49727. });
  49728. if (components[name]) {
  49729. throw new Error('The component `' + name + '` has been already registered. ' +
  49730. 'Check that you are not loading two versions of the same component ' +
  49731. 'or two different components of the same name.');
  49732. }
  49733. NewComponent = function (el, attr, id) {
  49734. Component.call(this, el, attr, id);
  49735. };
  49736. NewComponent.prototype = Object.create(Component.prototype, proto);
  49737. NewComponent.prototype.name = name;
  49738. NewComponent.prototype.constructor = NewComponent;
  49739. NewComponent.prototype.system = systems && systems.systems[name];
  49740. NewComponent.prototype.play = wrapPlay(NewComponent.prototype.play);
  49741. NewComponent.prototype.pause = wrapPause(NewComponent.prototype.pause);
  49742. components[name] = {
  49743. Component: NewComponent,
  49744. dependencies: NewComponent.prototype.dependencies,
  49745. isSingleProp: isSingleProp(NewComponent.prototype.schema),
  49746. multiple: NewComponent.prototype.multiple,
  49747. parse: NewComponent.prototype.parse,
  49748. parseAttrValueForCache: NewComponent.prototype.parseAttrValueForCache,
  49749. schema: utils.extend(processSchema(NewComponent.prototype.schema)),
  49750. stringify: NewComponent.prototype.stringify,
  49751. type: NewComponent.prototype.type
  49752. };
  49753. return NewComponent;
  49754. };
  49755. /**
  49756. * Builds component data from the current state of the entity, ultimately
  49757. * updating this.data.
  49758. *
  49759. * If the component was detached completely, set data to null.
  49760. *
  49761. * Precedence:
  49762. * 1. Defaults data
  49763. * 2. Mixin data.
  49764. * 3. Attribute data.
  49765. *
  49766. * Finally coerce the data to the types of the defaults.
  49767. *
  49768. * @param {object} el - Element to build data from.
  49769. * @param {object} name - Component name.
  49770. * @param {object} attrName - Attribute name associated to the component.
  49771. * @param {object} schema - Component schema.
  49772. * @param {object} elData - Element current data.
  49773. * @param {boolean} silent - Suppress warning messages.
  49774. * @return {object} The component data
  49775. */
  49776. function buildData (el, name, attrName, schema, elData, silent) {
  49777. var componentDefined = elData !== undefined && elData !== null;
  49778. var data;
  49779. var isSinglePropSchema = isSingleProp(schema);
  49780. var mixinEls = el.mixinEls;
  49781. // 1. Default values (lowest precendence).
  49782. if (isSinglePropSchema) {
  49783. data = schema.default;
  49784. } else {
  49785. data = {};
  49786. Object.keys(schema).forEach(function applyDefault (key) {
  49787. var defaultValue = schema[key].default;
  49788. data[key] = defaultValue && defaultValue.constructor === Object
  49789. ? utils.extend({}, defaultValue)
  49790. : defaultValue;
  49791. });
  49792. }
  49793. // 2. Mixin values.
  49794. mixinEls.forEach(handleMixinUpdate);
  49795. function handleMixinUpdate (mixinEl) {
  49796. var mixinData = mixinEl.getAttribute(attrName);
  49797. if (mixinData) {
  49798. data = extendProperties(data, mixinData, isSinglePropSchema);
  49799. }
  49800. }
  49801. // 3. Attribute values (highest precendence).
  49802. if (componentDefined) {
  49803. if (isSinglePropSchema) { return parseProperty(elData, schema); }
  49804. data = extendProperties(data, elData, isSinglePropSchema);
  49805. return parseProperties(data, schema, undefined, name, silent);
  49806. } else {
  49807. // Parse and coerce using the schema.
  49808. if (isSinglePropSchema) { return parseProperty(data, schema); }
  49809. return parseProperties(data, schema, undefined, name, silent);
  49810. }
  49811. }
  49812. module.exports.buildData = buildData;
  49813. /**
  49814. * Object extending with checking for single-property schema.
  49815. *
  49816. * @param dest - Destination object or value.
  49817. * @param source - Source object or value
  49818. * @param {boolean} isSinglePropSchema - Whether or not schema is only a single property.
  49819. * @returns Overridden object or value.
  49820. */
  49821. function extendProperties (dest, source, isSinglePropSchema) {
  49822. if (isSinglePropSchema) { return source; }
  49823. return utils.extend(dest, source);
  49824. }
  49825. /**
  49826. * Wrapper for user defined pause method
  49827. * Pause component by removing tick behavior and calling user's pause method.
  49828. *
  49829. * @param pauseMethod {function} - user defined pause method
  49830. */
  49831. function wrapPause (pauseMethod) {
  49832. return function pause () {
  49833. var sceneEl = this.el.sceneEl;
  49834. if (!this.isPlaying) { return; }
  49835. pauseMethod.call(this);
  49836. this.isPlaying = false;
  49837. // Remove tick behavior.
  49838. if (!this.tick) { return; }
  49839. sceneEl.removeBehavior(this);
  49840. };
  49841. }
  49842. /**
  49843. * Wrapper for user defined play method
  49844. * Play component by adding tick behavior and calling user's play method.
  49845. *
  49846. * @param playMethod {function} - user defined play method
  49847. *
  49848. */
  49849. function wrapPlay (playMethod) {
  49850. return function play () {
  49851. var sceneEl = this.el.sceneEl;
  49852. var shouldPlay = this.el.isPlaying && !this.isPlaying;
  49853. if (!this.initialized || !shouldPlay) { return; }
  49854. playMethod.call(this);
  49855. this.isPlaying = true;
  49856. // Add tick behavior.
  49857. if (!this.tick) { return; }
  49858. sceneEl.addBehavior(this);
  49859. };
  49860. }
  49861. },{"../utils/":167,"./scene/scenes":106,"./schema":108,"./system":110}],101:[function(_dereq_,module,exports){
  49862. var schema = _dereq_('./schema');
  49863. var processSchema = schema.process;
  49864. var geometries = module.exports.geometries = {}; // Registered geometries.
  49865. var geometryNames = module.exports.geometryNames = []; // Names of registered geometries.
  49866. var THREE = _dereq_('../lib/three');
  49867. /**
  49868. * Geometry class definition.
  49869. *
  49870. * Geometries extend the geometry component API to create and register geometry types.
  49871. */
  49872. var Geometry = module.exports.Geometry = function () {};
  49873. Geometry.prototype = {
  49874. /**
  49875. * Contains the type schema and defaults for the data values.
  49876. * Data is coerced into the types of the values of the defaults.
  49877. */
  49878. schema: {},
  49879. /**
  49880. * Init handler. Similar to attachedCallback.
  49881. * Called during shader initialization and is only run once.
  49882. */
  49883. init: function (data) {
  49884. this.geometry = new THREE.Geometry();
  49885. return this.geometry;
  49886. },
  49887. /**
  49888. * Update handler. Similar to attributeChangedCallback.
  49889. * Called whenever the associated geometry data changes.
  49890. *
  49891. * @param {object} data - New geometry data.
  49892. */
  49893. update: function (data) { /* no-op */ }
  49894. };
  49895. /**
  49896. * Registers a geometry to A-Frame.
  49897. *
  49898. * @param {string} name - Geometry name.
  49899. * @param {object} definition - Geometry property and methods.
  49900. * @returns {object} Geometry.
  49901. */
  49902. module.exports.registerGeometry = function (name, definition) {
  49903. var NewGeometry;
  49904. var proto = {};
  49905. // Format definition object to prototype object.
  49906. Object.keys(definition).forEach(function expandDefinition (key) {
  49907. proto[key] = {
  49908. value: definition[key],
  49909. writable: true
  49910. };
  49911. });
  49912. if (geometries[name]) {
  49913. throw new Error('The geometry `' + name + '` has been already registered');
  49914. }
  49915. NewGeometry = function () { Geometry.call(this); };
  49916. NewGeometry.prototype = Object.create(Geometry.prototype, proto);
  49917. NewGeometry.prototype.name = name;
  49918. NewGeometry.prototype.constructor = NewGeometry;
  49919. geometries[name] = {
  49920. Geometry: NewGeometry,
  49921. schema: processSchema(NewGeometry.prototype.schema)
  49922. };
  49923. geometryNames.push(name);
  49924. return NewGeometry;
  49925. };
  49926. },{"../lib/three":146,"./schema":108}],102:[function(_dereq_,module,exports){
  49927. var coordinates = _dereq_('../utils/coordinates');
  49928. var debug = _dereq_('debug');
  49929. var error = debug('core:propertyTypes:warn');
  49930. var warn = debug('core:propertyTypes:warn');
  49931. var propertyTypes = module.exports.propertyTypes = {};
  49932. // Built-in property types.
  49933. registerPropertyType('audio', '', assetParse);
  49934. registerPropertyType('array', [], arrayParse, arrayStringify);
  49935. registerPropertyType('asset', '', assetParse);
  49936. registerPropertyType('boolean', false, boolParse);
  49937. registerPropertyType('color', '#FFF', defaultParse, defaultStringify);
  49938. registerPropertyType('int', 0, intParse);
  49939. registerPropertyType('number', 0, numberParse);
  49940. registerPropertyType('map', '', assetParse);
  49941. registerPropertyType('model', '', assetParse);
  49942. registerPropertyType('selector', '', selectorParse, selectorStringify);
  49943. registerPropertyType('selectorAll', '', selectorAllParse, selectorAllStringify);
  49944. registerPropertyType('src', '', srcParse);
  49945. registerPropertyType('string', '', defaultParse, defaultStringify);
  49946. registerPropertyType('time', 0, intParse);
  49947. registerPropertyType('vec2', {x: 0, y: 0}, vecParse, coordinates.stringify);
  49948. registerPropertyType('vec3', {x: 0, y: 0, z: 0}, vecParse, coordinates.stringify);
  49949. registerPropertyType('vec4', {x: 0, y: 0, z: 0, w: 0}, vecParse, coordinates.stringify);
  49950. /**
  49951. * Register a parser for re-use such that when someone uses `type` in the schema,
  49952. * `schema.process` will set the property `parse` and `stringify`.
  49953. *
  49954. * @param {string} type - Type name.
  49955. * @param [defaultValue=null] -
  49956. * Default value to use if component does not define default value.
  49957. * @param {function} [parse=defaultParse] - Parse string function.
  49958. * @param {function} [stringify=defaultStringify] - Stringify to DOM function.
  49959. */
  49960. function registerPropertyType (type, defaultValue, parse, stringify) {
  49961. if ('type' in propertyTypes) {
  49962. error('Property type ' + type + ' is already registered.');
  49963. return;
  49964. }
  49965. propertyTypes[type] = {
  49966. default: defaultValue,
  49967. parse: parse || defaultParse,
  49968. stringify: stringify || defaultStringify
  49969. };
  49970. }
  49971. module.exports.registerPropertyType = registerPropertyType;
  49972. function arrayParse (value) {
  49973. if (Array.isArray(value)) { return value; }
  49974. if (!value || typeof value !== 'string') { return []; }
  49975. return value.split(',').map(trim);
  49976. function trim (str) { return str.trim(); }
  49977. }
  49978. function arrayStringify (value) {
  49979. return value.join(', ');
  49980. }
  49981. /**
  49982. * For general assets.
  49983. *
  49984. * @param {string} value - Can either be `url(<value>)`, an ID selector to an asset, or
  49985. * just string.
  49986. * @returns {string} Parsed value from `url(<value>)`, src from `<someasset src>`, or
  49987. * just string.
  49988. */
  49989. function assetParse (value) {
  49990. var el;
  49991. var parsedUrl;
  49992. // If an element was provided (e.g. canvas or video), just return it.
  49993. if (typeof value !== 'string') { return value; }
  49994. // Wrapped `url()` in case of data URI.
  49995. parsedUrl = value.match(/\url\((.+)\)/);
  49996. if (parsedUrl) { return parsedUrl[1]; }
  49997. // ID.
  49998. if (value.charAt(0) === '#') {
  49999. el = selectorParse(value);
  50000. if (el) {
  50001. if (el.tagName === 'CANVAS' || el.tagName === 'VIDEO') { return el; }
  50002. return el.getAttribute('src');
  50003. }
  50004. warn('"' + value + '" asset not found.');
  50005. return;
  50006. }
  50007. // Non-wrapped url().
  50008. return value;
  50009. }
  50010. function defaultParse (value) {
  50011. return value;
  50012. }
  50013. function defaultStringify (value) {
  50014. if (value === null) { return 'null'; }
  50015. return value.toString();
  50016. }
  50017. function boolParse (value) {
  50018. return value !== 'false' && value !== false;
  50019. }
  50020. function intParse (value) {
  50021. return parseInt(value, 10);
  50022. }
  50023. function numberParse (value) {
  50024. return parseFloat(value, 10);
  50025. }
  50026. function selectorParse (value) {
  50027. if (!value) { return null; }
  50028. if (typeof value !== 'string') { return value; }
  50029. return document.querySelector(value);
  50030. }
  50031. function selectorAllParse (value) {
  50032. if (!value) { return null; }
  50033. if (typeof value !== 'string') { return value; }
  50034. return Array.prototype.slice.call(document.querySelectorAll(value), 0);
  50035. }
  50036. function selectorStringify (value) {
  50037. if (value.getAttribute) {
  50038. return '#' + value.getAttribute('id');
  50039. }
  50040. return defaultStringify(value);
  50041. }
  50042. function selectorAllStringify (value) {
  50043. if (value instanceof Array) {
  50044. return value.map(function (element) {
  50045. return '#' + element.getAttribute('id');
  50046. }).join(', ');
  50047. }
  50048. return defaultStringify(value);
  50049. }
  50050. function srcParse (value) {
  50051. warn('`src` property type is deprecated. Use `asset` instead.');
  50052. return assetParse(value);
  50053. }
  50054. function vecParse (value) {
  50055. return coordinates.parse(value, this.default);
  50056. }
  50057. },{"../utils/coordinates":162,"debug":11}],103:[function(_dereq_,module,exports){
  50058. /* global Promise, screen */
  50059. var initMetaTags = _dereq_('./metaTags').inject;
  50060. var initWakelock = _dereq_('./wakelock');
  50061. var re = _dereq_('../a-register-element');
  50062. var scenes = _dereq_('./scenes');
  50063. var systems = _dereq_('../system').systems;
  50064. var THREE = _dereq_('../../lib/three');
  50065. var TWEEN = _dereq_('tween.js');
  50066. var utils = _dereq_('../../utils/');
  50067. // Require after.
  50068. var AEntity = _dereq_('../a-entity');
  50069. var ANode = _dereq_('../a-node');
  50070. var initPostMessageAPI = _dereq_('./postMessage');
  50071. var bind = utils.bind;
  50072. var isIOS = utils.device.isIOS();
  50073. var isMobile = utils.device.isMobile();
  50074. var registerElement = re.registerElement;
  50075. var warn = utils.debug('core:a-scene:warn');
  50076. /**
  50077. * Scene element, holds all entities.
  50078. *
  50079. * @member {number} animationFrameID
  50080. * @member {array} behaviors - Component instances that have registered themselves to be
  50081. updated on every tick.
  50082. * @member {object} camera - three.js Camera object.
  50083. * @member {object} canvas
  50084. * @member {bool} isScene - Differentiates as scene entity as opposed to other entites.
  50085. * @member {bool} isMobile - Whether browser is mobile (via UA detection).
  50086. * @member {object} object3D - Root three.js Scene object.
  50087. * @member {object} renderer
  50088. * @member {bool} renderStarted
  50089. * @member (object) effect - three.js VREffect
  50090. * @member {object} systems - Registered instantiated systems.
  50091. * @member {number} time
  50092. */
  50093. module.exports = registerElement('a-scene', {
  50094. prototype: Object.create(AEntity.prototype, {
  50095. defaultComponents: {
  50096. value: {
  50097. 'canvas': '',
  50098. 'inspector': '',
  50099. 'keyboard-shortcuts': '',
  50100. 'screenshot': '',
  50101. 'vr-mode-ui': '',
  50102. 'auto-enter-vr': ''
  50103. }
  50104. },
  50105. createdCallback: {
  50106. value: function () {
  50107. this.isIOS = isIOS;
  50108. this.isMobile = isMobile;
  50109. this.isScene = true;
  50110. this.object3D = new THREE.Scene();
  50111. this.render = bind(this.render, this);
  50112. this.systems = {};
  50113. this.time = 0;
  50114. this.init();
  50115. }
  50116. },
  50117. init: {
  50118. value: function () {
  50119. this.behaviors = [];
  50120. this.hasLoaded = false;
  50121. this.isPlaying = false;
  50122. this.originalHTML = this.innerHTML;
  50123. this.addEventListener('render-target-loaded', function () {
  50124. this.setupRenderer();
  50125. this.resize();
  50126. });
  50127. this.addFullScreenStyles();
  50128. initPostMessageAPI(this);
  50129. },
  50130. writable: true
  50131. },
  50132. addFullScreenStyles: {
  50133. value: function () {
  50134. var htmlEl = document.documentElement;
  50135. htmlEl.classList.add('a-html');
  50136. document.body.classList.add('a-body');
  50137. this.classList.add('fullscreen');
  50138. }
  50139. },
  50140. removeFullScreenStyles: {
  50141. value: function () {
  50142. var htmlEl = document.documentElement;
  50143. htmlEl.classList.remove('a-html');
  50144. document.body.classList.remove('a-body');
  50145. this.classList.remove('fullscreen');
  50146. }
  50147. },
  50148. attachedCallback: {
  50149. value: function () {
  50150. var resize = bind(this.resize, this);
  50151. initMetaTags(this);
  50152. initWakelock(this);
  50153. this.initSystems();
  50154. window.addEventListener('load', resize);
  50155. window.addEventListener('resize', resize);
  50156. this.play();
  50157. // Add to scene index.
  50158. scenes.push(this);
  50159. },
  50160. writable: window.debug
  50161. },
  50162. initSystems: {
  50163. value: function () {
  50164. Object.keys(systems).forEach(bind(this.initSystem, this));
  50165. }
  50166. },
  50167. initSystem: {
  50168. value: function (name) {
  50169. var system;
  50170. if (this.systems[name]) { return; }
  50171. system = this.systems[name] = new systems[name](this);
  50172. system.init();
  50173. }
  50174. },
  50175. /**
  50176. * Shuts down scene on detach.
  50177. */
  50178. detachedCallback: {
  50179. value: function () {
  50180. var sceneIndex;
  50181. window.cancelAnimationFrame(this.animationFrameID);
  50182. this.animationFrameID = null;
  50183. // Remove from scene index.
  50184. sceneIndex = scenes.indexOf(this);
  50185. scenes.splice(sceneIndex, 1);
  50186. }
  50187. },
  50188. /**
  50189. * @param {object} behavior - Generally a component. Must implement a .update() method to
  50190. * be called on every tick.
  50191. */
  50192. addBehavior: {
  50193. value: function (behavior) {
  50194. var behaviors = this.behaviors;
  50195. if (behaviors.indexOf(behavior) !== -1) { return; }
  50196. behaviors.push(behavior);
  50197. }
  50198. },
  50199. /**
  50200. * For tests.
  50201. */
  50202. checkHeadsetConnected: {
  50203. value: utils.device.checkHeadsetConnected,
  50204. writable: window.debug
  50205. },
  50206. /**
  50207. * Call `requestPresent` if WebVR or WebVR polyfill.
  50208. * Call `requestFullscreen` on desktop.
  50209. * Handle events, states, fullscreen styles.
  50210. *
  50211. * @returns {Promise}
  50212. */
  50213. enterVR: {
  50214. value: function (event) {
  50215. var self = this;
  50216. // Don't enter VR if already in VR.
  50217. if (this.is('vr-mode')) { return Promise.resolve('Already in VR.'); }
  50218. if (this.checkHeadsetConnected() || this.isMobile) {
  50219. return this.effect.requestPresent().then(enterVRSuccess, enterVRFailure);
  50220. }
  50221. enterVRSuccess();
  50222. return Promise.resolve();
  50223. function enterVRSuccess () {
  50224. self.addState('vr-mode');
  50225. self.emit('enter-vr', event);
  50226. // Lock to landscape orientation on mobile.
  50227. if (self.isMobile && screen.orientation && screen.orientation.lock) {
  50228. screen.orientation.lock('landscape');
  50229. }
  50230. self.addFullScreenStyles();
  50231. // On mobile, the polyfill handles fullscreen.
  50232. // TODO: 07/16 Chromium builds break when `requestFullscreen`ing on a canvas
  50233. // that we are also `requestPresent`ing. Until then, don't fullscreen if headset
  50234. // connected.
  50235. if (!self.isMobile && !self.checkHeadsetConnected()) {
  50236. requestFullscreen(self.canvas);
  50237. }
  50238. self.resize();
  50239. }
  50240. function enterVRFailure (err) {
  50241. if (err && err.message) {
  50242. throw new Error('Failed to enter VR mode (`requestPresent`): ' + err.message);
  50243. } else {
  50244. throw new Error('Failed to enter VR mode (`requestPresent`).');
  50245. }
  50246. }
  50247. }
  50248. },
  50249. /**
  50250. * Call `exitPresent` if WebVR or WebVR polyfill.
  50251. * Handle events, states, fullscreen styles.
  50252. *
  50253. * @returns {Promise}
  50254. */
  50255. exitVR: {
  50256. value: function () {
  50257. var self = this;
  50258. // Don't exit VR if not in VR.
  50259. if (!this.is('vr-mode')) { return Promise.resolve('Not in VR.'); }
  50260. exitFullscreen();
  50261. if (this.checkHeadsetConnected() || this.isMobile) {
  50262. return this.effect.exitPresent().then(exitVRSuccess, exitVRFailure);
  50263. }
  50264. exitVRSuccess();
  50265. return Promise.resolve();
  50266. function exitVRSuccess () {
  50267. self.removeState('vr-mode');
  50268. // Lock to landscape orientation on mobile.
  50269. if (self.isMobile && screen.orientation && screen.orientation.unlock) {
  50270. screen.orientation.unlock();
  50271. }
  50272. // Exiting VR in embedded mode, no longer need fullscreen styles.
  50273. if (self.hasAttribute('embedded')) { self.removeFullScreenStyles(); }
  50274. self.resize();
  50275. if (self.isIOS) { utils.forceCanvasResizeSafariMobile(this.canvas); }
  50276. self.emit('exit-vr', {target: self});
  50277. }
  50278. function exitVRFailure (err) {
  50279. if (err && err.message) {
  50280. throw new Error('Failed to exit VR mode (`exitPresent`): ' + err.message);
  50281. } else {
  50282. throw new Error('Failed to exit VR mode (`exitPresent`).');
  50283. }
  50284. }
  50285. }
  50286. },
  50287. /**
  50288. * Wraps Entity.getAttribute to take into account for systems.
  50289. * If system exists, then return system data rather than possible component data.
  50290. */
  50291. getAttribute: {
  50292. value: function (attr) {
  50293. var system = this.systems[attr];
  50294. if (system) { return system.data; }
  50295. return AEntity.prototype.getAttribute.call(this, attr);
  50296. }
  50297. },
  50298. /**
  50299. * `getAttribute` used to be `getDOMAttribute` and `getComputedAttribute` used to be
  50300. * what `getAttribute` is now. Now legacy code.
  50301. */
  50302. getComputedAttribute: {
  50303. value: function (attr) {
  50304. warn('`getComputedAttribute` is deprecated. Use `getAttribute` instead.');
  50305. this.getAttribute(attr);
  50306. }
  50307. },
  50308. /**
  50309. * Wraps Entity.getDOMAttribute to take into account for systems.
  50310. * If system exists, then return system data rather than possible component data.
  50311. */
  50312. getDOMAttribute: {
  50313. value: function (attr) {
  50314. var system = this.systems[attr];
  50315. if (system) { return system.data; }
  50316. return AEntity.prototype.getDOMAttribute.call(this, attr);
  50317. }
  50318. },
  50319. /**
  50320. * Wraps Entity.setAttribute to take into account for systems.
  50321. * If system exists, then skip component initialization checks and do a normal
  50322. * setAttribute.
  50323. */
  50324. setAttribute: {
  50325. value: function (attr, value, componentPropValue) {
  50326. var system = this.systems[attr];
  50327. if (system) {
  50328. ANode.prototype.setAttribute.call(this, attr, value);
  50329. return;
  50330. }
  50331. AEntity.prototype.setAttribute.call(this, attr, value, componentPropValue);
  50332. }
  50333. },
  50334. /**
  50335. * @param {object} behavior - Generally a component. Has registered itself to behaviors.
  50336. */
  50337. removeBehavior: {
  50338. value: function (behavior) {
  50339. var behaviors = this.behaviors;
  50340. var index = behaviors.indexOf(behavior);
  50341. if (index === -1) { return; }
  50342. behaviors.splice(index, 1);
  50343. }
  50344. },
  50345. resize: {
  50346. value: function () {
  50347. var camera = this.camera;
  50348. var canvas = this.canvas;
  50349. var embedded = this.getAttribute('embedded') && !this.is('vr-mode');
  50350. var size;
  50351. // Possible camera or canvas not injected yet.
  50352. // ON MOBILE the webvr-polyfill relies on the fullscreen API to enter
  50353. // VR mode. The canvas is resized by VREffect following the values returned
  50354. // by getEyeParameters. We don't want to overwrite the size with the
  50355. // windows width and height.
  50356. if (!camera || !canvas || this.is('vr-mode') && isMobile) { return; }
  50357. // Update camera.
  50358. size = getCanvasSize(canvas, embedded);
  50359. camera.aspect = size.width / size.height;
  50360. camera.updateProjectionMatrix();
  50361. // Notify renderer of size change.
  50362. this.renderer.setSize(size.width, size.height);
  50363. },
  50364. writable: window.debug
  50365. },
  50366. setupRenderer: {
  50367. value: function () {
  50368. var canvas = this.canvas;
  50369. // Set at startup. To enable/disable antialias
  50370. // at runttime we would have to recreate the whole context
  50371. var antialias = this.getAttribute('antialias') === 'true';
  50372. var renderer = this.renderer = new THREE.WebGLRenderer({
  50373. canvas: canvas,
  50374. antialias: antialias || window.hasNativeWebVRImplementation,
  50375. alpha: true
  50376. });
  50377. renderer.setPixelRatio(window.devicePixelRatio);
  50378. renderer.sortObjects = false;
  50379. this.effect = new THREE.VREffect(renderer);
  50380. },
  50381. writable: window.debug
  50382. },
  50383. /**
  50384. * Handler attached to elements to help scene know when to kick off.
  50385. * Scene waits for all entities to load.
  50386. */
  50387. play: {
  50388. value: function () {
  50389. var self = this;
  50390. if (this.renderStarted) {
  50391. AEntity.prototype.play.call(this);
  50392. return;
  50393. }
  50394. this.addEventListener('loaded', function () {
  50395. AEntity.prototype.play.call(this); // .play() *before* render.
  50396. // Wait for camera if necessary before rendering.
  50397. if (this.camera) {
  50398. startRender(this);
  50399. return;
  50400. }
  50401. this.addEventListener('camera-set-active', function () { startRender(this); });
  50402. function startRender (sceneEl) {
  50403. if (sceneEl.renderStarted) { return; }
  50404. sceneEl.resize();
  50405. // Kick off render loop.
  50406. if (sceneEl.renderer) {
  50407. if (window.performance) {
  50408. window.performance.mark('render-started');
  50409. }
  50410. sceneEl.render(0);
  50411. sceneEl.renderStarted = true;
  50412. sceneEl.emit('renderstart');
  50413. }
  50414. }
  50415. });
  50416. // setTimeout to wait for all nodes to attach and run their callbacks.
  50417. setTimeout(function () {
  50418. AEntity.prototype.load.call(self);
  50419. });
  50420. }
  50421. },
  50422. /**
  50423. * Reload the scene to the original DOM content.
  50424. *
  50425. * @param {bool} doPause - Whether to reload the scene with all dynamic behavior paused.
  50426. */
  50427. reload: {
  50428. value: function (doPause) {
  50429. var self = this;
  50430. if (doPause) { this.pause(); }
  50431. this.innerHTML = this.originalHTML;
  50432. this.init();
  50433. ANode.prototype.load.call(this, play);
  50434. function play () {
  50435. if (!self.isPlaying) { return; }
  50436. AEntity.prototype.play.call(self);
  50437. }
  50438. }
  50439. },
  50440. /**
  50441. * Wrap `updateComponent` to not initialize the component if the component has a system
  50442. * (aframevr/aframe#2365).
  50443. */
  50444. updateComponent: {
  50445. value: function (componentName) {
  50446. if (componentName in systems) { return; }
  50447. AEntity.prototype.updateComponent.apply(this, arguments);
  50448. }
  50449. },
  50450. /**
  50451. * Behavior-updater meant to be called from scene render.
  50452. * Abstracted to a different function to facilitate unit testing (`scene.tick()`) without
  50453. * needing to render.
  50454. */
  50455. tick: {
  50456. value: function (time, timeDelta) {
  50457. var systems = this.systems;
  50458. // Animations.
  50459. TWEEN.update(time);
  50460. // Components.
  50461. this.behaviors.forEach(function (component) {
  50462. if (!component.el.isPlaying) { return; }
  50463. component.tick(time, timeDelta);
  50464. });
  50465. // Systems.
  50466. Object.keys(systems).forEach(function (key) {
  50467. if (!systems[key].tick) { return; }
  50468. systems[key].tick(time, timeDelta);
  50469. });
  50470. }
  50471. },
  50472. /**
  50473. * The render loop.
  50474. *
  50475. * Updates animations.
  50476. * Updates behaviors.
  50477. * Renders with request animation frame.
  50478. */
  50479. render: {
  50480. value: function (time) {
  50481. var effect = this.effect;
  50482. var timeDelta = time - this.time;
  50483. if (this.isPlaying) { this.tick(time, timeDelta); }
  50484. this.animationFrameID = effect.requestAnimationFrame(this.render);
  50485. effect.render(this.object3D, this.camera);
  50486. this.time = time;
  50487. },
  50488. writable: true
  50489. }
  50490. })
  50491. });
  50492. /**
  50493. * Return the canvas size where the scene will be rendered
  50494. * It will be always the window size except when the scene
  50495. * is embedded. The parent size will be returned in that case
  50496. *
  50497. * @param {object} canvasEl - the canvas element
  50498. * @param {boolean} embedded - Is the scene embedded?
  50499. */
  50500. function getCanvasSize (canvasEl, embedded) {
  50501. if (embedded) {
  50502. return {
  50503. height: canvasEl.parentElement.offsetHeight,
  50504. width: canvasEl.parentElement.offsetWidth
  50505. };
  50506. }
  50507. return {
  50508. height: window.innerHeight,
  50509. width: window.innerWidth
  50510. };
  50511. }
  50512. function requestFullscreen (canvas) {
  50513. var requestFullscreen =
  50514. canvas.requestFullscreen ||
  50515. canvas.webkitRequestFullscreen ||
  50516. canvas.mozRequestFullScreen || // The capitalized `S` is not a typo.
  50517. canvas.msRequestFullscreen;
  50518. requestFullscreen.apply(canvas);
  50519. }
  50520. function exitFullscreen () {
  50521. if (document.exitFullscreen) {
  50522. document.exitFullscreen();
  50523. } else if (document.mozCancelFullScreen) {
  50524. document.mozCancelFullScreen();
  50525. } else if (document.webkitExitFullscreen) {
  50526. document.webkitExitFullscreen();
  50527. }
  50528. }
  50529. },{"../../lib/three":146,"../../utils/":167,"../a-entity":96,"../a-node":98,"../a-register-element":99,"../system":110,"./metaTags":104,"./postMessage":105,"./scenes":106,"./wakelock":107,"tween.js":49}],104:[function(_dereq_,module,exports){
  50530. var constants = _dereq_('../../constants/');
  50531. var extend = _dereq_('../../utils').extend;
  50532. var MOBILE_HEAD_TAGS = module.exports.MOBILE_HEAD_TAGS = [
  50533. Meta({name: 'viewport', content: 'width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no,user-scalable=no,minimal-ui'}),
  50534. // W3C-standardised meta tags.
  50535. Meta({name: 'mobile-web-app-capable', content: 'yes'}),
  50536. Meta({name: 'theme-color', content: 'black'})
  50537. ];
  50538. var MOBILE_IOS_HEAD_TAGS = [
  50539. // iOS-specific meta tags for fullscreen when pinning to homescreen.
  50540. Meta({name: 'apple-mobile-web-app-capable', content: 'yes'}),
  50541. Meta({name: 'apple-mobile-web-app-status-bar-style', content: 'black'}),
  50542. Link({rel: 'apple-touch-icon', href: 'https://aframe.io/images/aframe-logo-152.png'})
  50543. ];
  50544. function Meta (attrs) {
  50545. return {
  50546. tagName: 'meta',
  50547. attributes: attrs,
  50548. exists: function () { return document.querySelector('meta[name="' + attrs.name + '"]'); }
  50549. };
  50550. }
  50551. function Link (attrs) {
  50552. return {
  50553. tagName: 'link',
  50554. attributes: attrs,
  50555. exists: function () { return document.querySelector('link[rel="' + attrs.rel + '"]'); }
  50556. };
  50557. }
  50558. /**
  50559. * Injects the necessary metatags in the document for mobile support:
  50560. * 1. Prevent the user to zoom in the document.
  50561. * 2. Ensure that window.innerWidth and window.innerHeight have the correct
  50562. * values and the canvas is properly scaled.
  50563. * 3. To allow fullscreen mode when pinning a web app on the home screen on
  50564. * iOS.
  50565. * Adapted from https://www.reddit.com/r/web_design/comments/3la04p/
  50566. *
  50567. * @param {object} scene - Scene element
  50568. * @returns {Array}
  50569. */
  50570. module.exports.inject = function injectHeadTags (scene) {
  50571. var headEl = document.head;
  50572. var headScriptEl = headEl.querySelector('script');
  50573. var tag;
  50574. var headTags = [];
  50575. MOBILE_HEAD_TAGS.forEach(createAndInjectTag);
  50576. if (scene.isIOS) {
  50577. MOBILE_IOS_HEAD_TAGS.forEach(createAndInjectTag);
  50578. }
  50579. return headTags;
  50580. function createAndInjectTag (tagObj) {
  50581. if (!tagObj || tagObj.exists()) { return; }
  50582. tag = createTag(tagObj);
  50583. if (!tag) { return; }
  50584. if (headScriptEl) {
  50585. headScriptEl.parentNode.insertBefore(tag, headScriptEl);
  50586. } else {
  50587. headEl.appendChild(tag);
  50588. }
  50589. headTags.push(tag);
  50590. }
  50591. };
  50592. function createTag (tagObj) {
  50593. if (!tagObj || !tagObj.tagName) { return; }
  50594. var meta = document.createElement(tagObj.tagName);
  50595. meta.setAttribute(constants.AFRAME_INJECTED, '');
  50596. return extend(meta, tagObj.attributes);
  50597. }
  50598. },{"../../constants/":91,"../../utils":167}],105:[function(_dereq_,module,exports){
  50599. var bind = _dereq_('../../utils/bind');
  50600. var isIframed = _dereq_('../../utils/').isIframed;
  50601. /**
  50602. * Provides a post message API for scenes contained
  50603. * in an iframe.
  50604. */
  50605. module.exports = function initPostMessageAPI (scene) {
  50606. // Handles fullscreen behavior when inside an iframe.
  50607. if (!isIframed()) { return; }
  50608. // postMessage API handler
  50609. window.addEventListener('message', bind(postMessageAPIHandler, scene));
  50610. };
  50611. function postMessageAPIHandler (event) {
  50612. var scene = this;
  50613. if (!event.data) { return; }
  50614. switch (event.data.type) {
  50615. case 'vr': {
  50616. switch (event.data.data) {
  50617. case 'enter':
  50618. scene.enterVR();
  50619. break;
  50620. case 'exit':
  50621. scene.exitVR();
  50622. break;
  50623. }
  50624. }
  50625. }
  50626. }
  50627. },{"../../utils/":167,"../../utils/bind":161}],106:[function(_dereq_,module,exports){
  50628. /*
  50629. Scene index for keeping track of created scenes.
  50630. */
  50631. module.exports = [];
  50632. },{}],107:[function(_dereq_,module,exports){
  50633. var Wakelock = _dereq_('../../../vendor/wakelock/wakelock');
  50634. module.exports = function initWakelock (scene) {
  50635. if (!scene.isMobile) { return; }
  50636. var wakelock = scene.wakelock = new Wakelock();
  50637. scene.addEventListener('enter-vr', function () { wakelock.request(); });
  50638. scene.addEventListener('exit-vr', function () { wakelock.release(); });
  50639. };
  50640. },{"../../../vendor/wakelock/wakelock":177}],108:[function(_dereq_,module,exports){
  50641. var debug = _dereq_('../utils/debug');
  50642. var propertyTypes = _dereq_('./propertyTypes').propertyTypes;
  50643. var warn = debug('core:schema:warn');
  50644. /**
  50645. * A schema is classified as a schema for a single property if:
  50646. * - `type` is defined on the schema as a string.
  50647. * - OR `default` is defined on the schema, as a reserved keyword.
  50648. * - OR schema is empty.
  50649. */
  50650. function isSingleProperty (schema) {
  50651. if ('type' in schema) {
  50652. return typeof schema.type === 'string';
  50653. }
  50654. return 'default' in schema;
  50655. }
  50656. module.exports.isSingleProperty = isSingleProperty;
  50657. /**
  50658. * Build step to schema to use `type` to inject default value, parser, and stringifier.
  50659. *
  50660. * @param {object} schema
  50661. * @returns {object} Schema.
  50662. */
  50663. module.exports.process = function (schema) {
  50664. // For single property schema, run processPropDefinition over the whole schema.
  50665. if (isSingleProperty(schema)) {
  50666. return processPropertyDefinition(schema);
  50667. }
  50668. // For multi-property schema, run processPropDefinition over each property definition.
  50669. Object.keys(schema).forEach(function (propName) {
  50670. schema[propName] = processPropertyDefinition(schema[propName]);
  50671. });
  50672. return schema;
  50673. };
  50674. /**
  50675. * Inject default value, parser, stringifier for single property.
  50676. */
  50677. function processPropertyDefinition (propDefinition) {
  50678. var defaultVal = propDefinition.default;
  50679. var propType;
  50680. var typeName = propDefinition.type;
  50681. // Type inference.
  50682. if (!propDefinition.type) {
  50683. if (defaultVal !== undefined && ['boolean', 'number'].indexOf(typeof defaultVal) !== -1) {
  50684. // Type inference.
  50685. typeName = typeof defaultVal;
  50686. } else if (Array.isArray(defaultVal)) {
  50687. typeName = 'array';
  50688. } else {
  50689. // Fall back to string.
  50690. typeName = 'string';
  50691. }
  50692. } else if (propDefinition.type === 'bool') {
  50693. typeName = 'boolean';
  50694. } else if (propDefinition.type === 'float') {
  50695. typeName = 'number';
  50696. }
  50697. propType = propertyTypes[typeName];
  50698. if (!propType) {
  50699. warn('Unknown property type: ' + typeName);
  50700. }
  50701. // Fill in parse and stringify using property types.
  50702. propDefinition.parse = propDefinition.parse || propType.parse;
  50703. propDefinition.stringify = propDefinition.stringify || propType.stringify;
  50704. // Fill in type name.
  50705. propDefinition.type = typeName;
  50706. // Fill in default value.
  50707. if (!('default' in propDefinition)) {
  50708. propDefinition.default = propType.default;
  50709. }
  50710. return propDefinition;
  50711. }
  50712. module.exports.processPropertyDefinition = processPropertyDefinition;
  50713. /**
  50714. * Parse propData using schema. Use default values if not existing in propData.
  50715. *
  50716. * @param {object} propData - Unparsed properties.
  50717. * @param {object} schema - Property types definition.
  50718. * @param {boolean} getPartialData - Whether to return full component data or just the data
  50719. * with keys in `propData`.
  50720. * @param {string } componentName - Name of the component, used for the property warning.
  50721. * @param {boolean} silent - Suppress warning messages.
  50722. */
  50723. module.exports.parseProperties = function (propData, schema, getPartialData, componentName,
  50724. silent) {
  50725. var propNames = Object.keys(getPartialData ? propData : schema);
  50726. if (propData === null || typeof propData !== 'object') { return propData; }
  50727. // Validation errors.
  50728. Object.keys(propData).forEach(function (propName) {
  50729. if (!schema[propName] && !silent) {
  50730. warn('Unknown property `' + propName +
  50731. '` for component/system `' + componentName + '`.');
  50732. }
  50733. });
  50734. propNames.forEach(function parse (propName) {
  50735. var propDefinition = schema[propName];
  50736. var propValue = propData[propName];
  50737. if (!(schema[propName])) { return; }
  50738. propData[propName] = parseProperty(propValue, propDefinition);
  50739. });
  50740. return propData;
  50741. };
  50742. /**
  50743. * Deserialize a single property.
  50744. */
  50745. function parseProperty (value, propDefinition) {
  50746. // Use default value if value is falsy.
  50747. if (value === undefined || value === null || value === '') {
  50748. value = propDefinition.default;
  50749. }
  50750. // Invoke property type parser.
  50751. return propDefinition.parse(value, propDefinition.default);
  50752. }
  50753. module.exports.parseProperty = parseProperty;
  50754. /**
  50755. * Serialize a group of properties.
  50756. */
  50757. module.exports.stringifyProperties = function (propData, schema) {
  50758. var stringifiedData = {};
  50759. Object.keys(propData).forEach(function (propName) {
  50760. var propDefinition = schema[propName];
  50761. var propValue = propData[propName];
  50762. var value = propValue;
  50763. if (typeof value === 'object') {
  50764. value = stringifyProperty(propValue, propDefinition);
  50765. if (!propDefinition) { warn('Unknown component property: ' + propName); }
  50766. }
  50767. stringifiedData[propName] = value;
  50768. });
  50769. return stringifiedData;
  50770. };
  50771. /**
  50772. * Serialize a single property.
  50773. */
  50774. function stringifyProperty (value, propDefinition) {
  50775. // This function stringifies but it's used in a context where
  50776. // there's always second stringification pass. By returning the original
  50777. // value when it's not an object we save one unnecessary call
  50778. // to JSON.stringify.
  50779. if (typeof value !== 'object') { return value; }
  50780. // if there's no schema for the property we use standar JSON stringify
  50781. if (!propDefinition || value === null) { return JSON.stringify(value); }
  50782. return propDefinition.stringify(value);
  50783. }
  50784. module.exports.stringifyProperty = stringifyProperty;
  50785. },{"../utils/debug":163,"./propertyTypes":102}],109:[function(_dereq_,module,exports){
  50786. var schema = _dereq_('./schema');
  50787. var processSchema = schema.process;
  50788. var shaders = module.exports.shaders = {}; // Keep track of registered shaders.
  50789. var shaderNames = module.exports.shaderNames = []; // Keep track of the names of registered shaders.
  50790. var THREE = _dereq_('../lib/three');
  50791. var utils = _dereq_('../utils');
  50792. // A-Frame properties to three.js uniform types.
  50793. var propertyToThreeMapping = {
  50794. array: 'v3',
  50795. color: 'v3',
  50796. int: 'i',
  50797. number: 'f',
  50798. map: 't',
  50799. time: 'f',
  50800. vec2: 'v2',
  50801. vec3: 'v3',
  50802. vec4: 'v4'
  50803. };
  50804. /**
  50805. * Shader class definition.
  50806. *
  50807. * Shaders extend the material component API so you can create your own library
  50808. * of customized materials
  50809. *
  50810. */
  50811. var Shader = module.exports.Shader = function () {};
  50812. Shader.prototype = {
  50813. /**
  50814. * Contains the type schema and defaults for the data values.
  50815. * Data is coerced into the types of the values of the defaults.
  50816. */
  50817. schema: {},
  50818. vertexShader:
  50819. 'void main() {' +
  50820. 'gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);' +
  50821. '}',
  50822. fragmentShader:
  50823. 'void main() {' +
  50824. 'gl_FragColor = vec4(1.0, 0.0, 1.0, 1.0);' +
  50825. '}',
  50826. /**
  50827. * Init handler. Similar to attachedCallback.
  50828. * Called during shader initialization and is only run once.
  50829. */
  50830. init: function (data) {
  50831. this.attributes = this.initVariables(data, 'attribute');
  50832. this.uniforms = this.initVariables(data, 'uniform');
  50833. this.material = new (this.raw ? THREE.RawShaderMaterial : THREE.ShaderMaterial)({
  50834. // attributes: this.attributes,
  50835. uniforms: this.uniforms,
  50836. vertexShader: this.vertexShader,
  50837. fragmentShader: this.fragmentShader
  50838. });
  50839. return this.material;
  50840. },
  50841. initVariables: function (data, type) {
  50842. var variables = {};
  50843. var schema = this.schema;
  50844. Object.keys(schema).forEach(function processSchema (key) {
  50845. if (schema[key].is !== type) { return; }
  50846. var varType = propertyToThreeMapping[schema[key].type];
  50847. variables[key] = {
  50848. type: varType,
  50849. value: undefined // Let updateVariables handle setting these.
  50850. };
  50851. });
  50852. return variables;
  50853. },
  50854. /**
  50855. * Update handler. Similar to attributeChangedCallback.
  50856. * Called whenever the associated material data changes.
  50857. *
  50858. * @param {object} data - New material data.
  50859. */
  50860. update: function (data) {
  50861. this.updateVariables(data, 'attribute');
  50862. this.updateVariables(data, 'uniform');
  50863. },
  50864. updateVariables: function (data, type) {
  50865. var self = this;
  50866. var variables = type === 'uniform' ? this.uniforms : this.attributes;
  50867. var schema = this.schema;
  50868. Object.keys(data).forEach(function processData (key) {
  50869. var materialKey;
  50870. if (!schema[key] || schema[key].is !== type) { return; }
  50871. if (schema[key].type === 'map') {
  50872. // If data unchanged, get out early.
  50873. if (!variables[key] || variables[key].value === data[key]) { return; }
  50874. // Special handling is needed for textures.
  50875. materialKey = '_texture_' + key;
  50876. // We can't actually set the variable correctly until we've loaded the texture.
  50877. self.el.addEventListener('materialtextureloaded', function () {
  50878. variables[key].value = self.material[materialKey];
  50879. variables[key].needsUpdate = true;
  50880. });
  50881. // Kick off the texture update now that handler is added.
  50882. utils.material.updateMapMaterialFromData(materialKey, key, self, data);
  50883. return;
  50884. }
  50885. variables[key].value = self.parseValue(schema[key].type, data[key]);
  50886. variables[key].needsUpdate = true;
  50887. });
  50888. },
  50889. parseValue: function (type, value) {
  50890. var color;
  50891. switch (type) {
  50892. case 'vec2': {
  50893. return new THREE.Vector2(value.x, value.y);
  50894. }
  50895. case 'vec3': {
  50896. return new THREE.Vector3(value.x, value.y, value.z);
  50897. }
  50898. case 'vec4': {
  50899. return new THREE.Vector4(value.x, value.y, value.z, value.w);
  50900. }
  50901. case 'color': {
  50902. color = new THREE.Color(value);
  50903. return new THREE.Vector3(color.r, color.g, color.b);
  50904. }
  50905. default: {
  50906. return value;
  50907. }
  50908. }
  50909. }
  50910. };
  50911. /**
  50912. * Registers a shader to A-Frame.
  50913. *
  50914. * @param {string} name - shader name.
  50915. * @param {object} definition - shader property and methods.
  50916. * @returns {object} Shader.
  50917. */
  50918. module.exports.registerShader = function (name, definition) {
  50919. var NewShader;
  50920. var proto = {};
  50921. // Format definition object to prototype object.
  50922. Object.keys(definition).forEach(function (key) {
  50923. proto[key] = {
  50924. value: definition[key],
  50925. writable: true
  50926. };
  50927. });
  50928. if (shaders[name]) {
  50929. throw new Error('The shader ' + name + ' has been already registered');
  50930. }
  50931. NewShader = function () { Shader.call(this); };
  50932. NewShader.prototype = Object.create(Shader.prototype, proto);
  50933. NewShader.prototype.name = name;
  50934. NewShader.prototype.constructor = NewShader;
  50935. shaders[name] = {
  50936. Shader: NewShader,
  50937. schema: processSchema(NewShader.prototype.schema)
  50938. };
  50939. shaderNames.push(name);
  50940. return NewShader;
  50941. };
  50942. },{"../lib/three":146,"../utils":167,"./schema":108}],110:[function(_dereq_,module,exports){
  50943. /* global HTMLElement */
  50944. var components = _dereq_('./component');
  50945. var schema = _dereq_('./schema');
  50946. var utils = _dereq_('../utils/');
  50947. var parseProperties = schema.parseProperties;
  50948. var parseProperty = schema.parseProperty;
  50949. var processSchema = schema.process;
  50950. var isSingleProp = schema.isSingleProperty;
  50951. var styleParser = utils.styleParser;
  50952. var systems = module.exports.systems = {}; // Keep track of registered systems.
  50953. /**
  50954. * System class definition.
  50955. *
  50956. * Systems provide global scope and services to a group of instantiated components of the
  50957. * same class. They can also help abstract logic away from components such that components
  50958. * only have to worry about data.
  50959. * For example, a physics component that creates a physics world that oversees
  50960. * all entities with a physics or rigid body component.
  50961. *
  50962. * @member {string} name - Name that system is registered under.
  50963. * @member {Element} sceneEl - Handle to the scene element where system applies to.
  50964. */
  50965. var System = module.exports.System = function (sceneEl) {
  50966. var component = components && components.components[this.name];
  50967. var schema = this.schema;
  50968. var rawData;
  50969. // Set reference to scene.
  50970. this.sceneEl = sceneEl;
  50971. // Set reference to matching component (if exists).
  50972. if (component) { component.Component.prototype.system = this; }
  50973. // Process system configuration.
  50974. if (!Object.keys(schema).length) { return; }
  50975. rawData = HTMLElement.prototype.getAttribute.call(sceneEl, this.name);
  50976. if (isSingleProp(schema)) {
  50977. this.data = parseProperty(rawData, schema);
  50978. return;
  50979. }
  50980. this.data = parseProperties(styleParser.parse(rawData) || {}, schema, false, this.name);
  50981. };
  50982. System.prototype = {
  50983. /**
  50984. * Schema to configure system.
  50985. */
  50986. schema: {},
  50987. /**
  50988. * Init handler. Called during scene initialization and is only run once.
  50989. * Systems can use this to set initial state.
  50990. */
  50991. init: function () { /* no-op */ },
  50992. /**
  50993. * Tick handler.
  50994. * Called on each tick of the scene render loop.
  50995. * Affected by play and pause.
  50996. *
  50997. * @param {number} time - Scene tick time.
  50998. * @param {number} timeDelta - Difference in current render time and previous render time.
  50999. */
  51000. tick: undefined,
  51001. /**
  51002. * Called to start any dynamic behavior (e.g., animation, AI, events, physics).
  51003. */
  51004. play: function () { /* no-op */ },
  51005. /**
  51006. * Called to stop any dynamic behavior (e.g., animation, AI, events, physics).
  51007. */
  51008. pause: function () { /* no-op */ }
  51009. };
  51010. /**
  51011. * Registers a system to A-Frame.
  51012. *
  51013. * @param {string} name - Component name.
  51014. * @param {object} definition - Component property and methods.
  51015. * @returns {object} Component.
  51016. */
  51017. module.exports.registerSystem = function (name, definition) {
  51018. var i;
  51019. var NewSystem;
  51020. var proto = {};
  51021. var scenes = utils.findAllScenes(document);
  51022. // Format definition object to prototype object.
  51023. Object.keys(definition).forEach(function (key) {
  51024. proto[key] = {
  51025. value: definition[key],
  51026. writable: true
  51027. };
  51028. });
  51029. if (systems[name]) {
  51030. throw new Error('The system `' + name + '` has been already registered. ' +
  51031. 'Check that you are not loading two versions of the same system ' +
  51032. 'or two different systems of the same name.');
  51033. }
  51034. NewSystem = function (sceneEl) { System.call(this, sceneEl); };
  51035. NewSystem.prototype = Object.create(System.prototype, proto);
  51036. NewSystem.prototype.name = name;
  51037. NewSystem.prototype.constructor = NewSystem;
  51038. NewSystem.prototype.schema = utils.extend(processSchema(NewSystem.prototype.schema));
  51039. systems[name] = NewSystem;
  51040. // Initialize systems for existing scenes
  51041. for (i = 0; i < scenes.length; i++) { scenes[i].initSystem(name); }
  51042. };
  51043. },{"../utils/":167,"./component":100,"./schema":108}],111:[function(_dereq_,module,exports){
  51044. _dereq_('./pivot');
  51045. },{"./pivot":112}],112:[function(_dereq_,module,exports){
  51046. var registerComponent = _dereq_('../../core/component').registerComponent;
  51047. var THREE = _dereq_('../../lib/three');
  51048. var originalPosition = new THREE.Vector3();
  51049. var originalRotation = new THREE.Vector3();
  51050. /**
  51051. * Wrap el.object3D within an outer group. Apply pivot to el.object3D as position.
  51052. */
  51053. registerComponent('pivot', {
  51054. dependencies: ['position'],
  51055. schema: {type: 'vec3'},
  51056. init: function () {
  51057. var data = this.data;
  51058. var el = this.el;
  51059. var originalParent = el.object3D.parent;
  51060. var originalGroup = el.object3D;
  51061. var outerGroup = new THREE.Group();
  51062. originalPosition.copy(originalGroup.position);
  51063. originalRotation.copy(originalGroup.rotation);
  51064. // Detach current group from parent.
  51065. originalParent.remove(originalGroup);
  51066. outerGroup.add(originalGroup);
  51067. // Set new group as the outer group.
  51068. originalParent.add(outerGroup);
  51069. // Set outer group as new object3D.
  51070. el.object3D = outerGroup;
  51071. // Apply pivot to original group.
  51072. originalGroup.position.set(-1 * data.x, -1 * data.y, -1 * data.z);
  51073. // Offset the pivot so that world position not affected.
  51074. // And restore position onto outer group.
  51075. outerGroup.position.set(data.x + originalPosition.x, data.y + originalPosition.y,
  51076. data.z + originalPosition.z);
  51077. // Transfer rotation to outer group.
  51078. outerGroup.rotation.copy(originalGroup.rotation);
  51079. originalGroup.rotation.set(0, 0, 0);
  51080. }
  51081. });
  51082. },{"../../core/component":100,"../../lib/three":146}],113:[function(_dereq_,module,exports){
  51083. /**
  51084. * Common mesh defaults, mappings, and transforms.
  51085. */
  51086. var components = _dereq_('../../core/component').components;
  51087. var shaders = _dereq_('../../core/shader').shaders;
  51088. var utils = _dereq_('../../utils/');
  51089. var materialMappings = {};
  51090. Object.keys(components.material.schema).forEach(addMapping);
  51091. Object.keys(shaders.standard.schema).forEach(addMapping);
  51092. function addMapping (prop) {
  51093. // To hyphenated.
  51094. var htmlAttrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51095. if (prop === 'fog') { htmlAttrName = 'material-fog'; }
  51096. if (prop === 'visible') { htmlAttrName = 'material-visible'; }
  51097. materialMappings[htmlAttrName] = 'material.' + prop;
  51098. }
  51099. module.exports = function getMeshMixin () {
  51100. return {
  51101. defaultComponents: {material: {}},
  51102. mappings: utils.extend({}, materialMappings)
  51103. };
  51104. };
  51105. },{"../../core/component":100,"../../core/shader":109,"../../utils/":167}],114:[function(_dereq_,module,exports){
  51106. _dereq_('./primitives/a-camera');
  51107. _dereq_('./primitives/a-collada-model');
  51108. _dereq_('./primitives/a-cursor');
  51109. _dereq_('./primitives/a-curvedimage');
  51110. _dereq_('./primitives/a-gltf-model');
  51111. _dereq_('./primitives/a-image');
  51112. _dereq_('./primitives/a-light');
  51113. _dereq_('./primitives/a-obj-model');
  51114. _dereq_('./primitives/a-sky');
  51115. _dereq_('./primitives/a-sound');
  51116. _dereq_('./primitives/a-text');
  51117. _dereq_('./primitives/a-video');
  51118. _dereq_('./primitives/a-videosphere');
  51119. _dereq_('./primitives/meshPrimitives');
  51120. },{"./primitives/a-camera":116,"./primitives/a-collada-model":117,"./primitives/a-cursor":118,"./primitives/a-curvedimage":119,"./primitives/a-gltf-model":120,"./primitives/a-image":121,"./primitives/a-light":122,"./primitives/a-obj-model":123,"./primitives/a-sky":124,"./primitives/a-sound":125,"./primitives/a-text":126,"./primitives/a-video":127,"./primitives/a-videosphere":128,"./primitives/meshPrimitives":129}],115:[function(_dereq_,module,exports){
  51121. var AEntity = _dereq_('../../core/a-entity');
  51122. var components = _dereq_('../../core/component').components;
  51123. var registerElement = _dereq_('../../core/a-register-element').registerElement;
  51124. var utils = _dereq_('../../utils/');
  51125. var debug = utils.debug;
  51126. var setComponentProperty = utils.entity.setComponentProperty;
  51127. var log = debug('extras:primitives:debug');
  51128. var warn = debug('extras:primitives:warn');
  51129. var primitives = module.exports.primitives = {};
  51130. module.exports.registerPrimitive = function registerPrimitive (name, definition) {
  51131. name = name.toLowerCase();
  51132. log('Registering <%s>', name);
  51133. // Deprecation warning for defaultAttributes usage.
  51134. if (definition.defaultAttributes) {
  51135. warn("The 'defaultAttributes' object is deprecated. Use 'defaultComponents' instead.");
  51136. }
  51137. var primitive = registerElement(name, {
  51138. prototype: Object.create(AEntity.prototype, {
  51139. defaultComponentsFromPrimitive: {
  51140. value: definition.defaultComponents || definition.defaultAttributes || {}
  51141. },
  51142. deprecated: {value: definition.deprecated || null},
  51143. deprecatedMappings: {value: definition.deprecatedMappings || {}},
  51144. mappings: {value: definition.mappings || {}},
  51145. createdCallback: {
  51146. value: function () {
  51147. if (definition.deprecated) { console.warn(definition.deprecated); }
  51148. this.resolveMappingCollisions();
  51149. }
  51150. },
  51151. /**
  51152. * If a mapping collides with a registered component name
  51153. * it renames the mapping to componentname-property
  51154. */
  51155. resolveMappingCollisions: {
  51156. value: function () {
  51157. var mappings = this.mappings;
  51158. var self = this;
  51159. Object.keys(mappings).forEach(function resolveCollision (key) {
  51160. var newAttribute;
  51161. if (components[key]) {
  51162. newAttribute = mappings[key].replace('.', '-');
  51163. mappings[newAttribute] = mappings[key];
  51164. delete mappings[key];
  51165. console.warn('The primitive ' + self.tagName.toLowerCase() + ' has a mapping collision. ' +
  51166. 'The attribute ' + key + ' has the same name as a registered component and' +
  51167. ' has been renamed to ' + newAttribute);
  51168. }
  51169. });
  51170. }
  51171. },
  51172. getExtraComponents: {
  51173. value: function () {
  51174. var attr;
  51175. var data;
  51176. var i;
  51177. var mapping;
  51178. var mixins;
  51179. var path;
  51180. var self = this;
  51181. // Gather component data from default components.
  51182. data = utils.clone(this.defaultComponentsFromPrimitive);
  51183. // Factor in mixins to overwrite default components.
  51184. mixins = this.getAttribute('mixin');
  51185. if (mixins) {
  51186. mixins = mixins.trim().split(' ');
  51187. mixins.forEach(function applyMixin (mixinId) {
  51188. var mixinComponents = self.sceneEl.querySelector('#' + mixinId).componentCache;
  51189. Object.keys(mixinComponents).forEach(function setComponent (name) {
  51190. data[name] = utils.extendDeep(data[name] || {}, mixinComponents[name]);
  51191. });
  51192. });
  51193. }
  51194. // Gather component data from mappings.
  51195. for (i = 0; i < this.attributes.length; i++) {
  51196. attr = this.attributes[i];
  51197. mapping = this.mappings[attr.name];
  51198. if (mapping) {
  51199. path = utils.entity.getComponentPropertyPath(mapping);
  51200. if (path.constructor === Array) {
  51201. data[path[0]][path[1]] = attr.value;
  51202. } else {
  51203. data[path] = attr.value;
  51204. }
  51205. continue;
  51206. }
  51207. }
  51208. return data;
  51209. }
  51210. },
  51211. /**
  51212. * Sync to attribute to component property whenever mapped attribute changes.
  51213. * If attribute is mapped to a component property, set the component property using
  51214. * the attribute value.
  51215. */
  51216. attributeChangedCallback: {
  51217. value: function (attr, oldVal, value) {
  51218. var componentName = this.mappings[attr];
  51219. if (attr in this.deprecatedMappings) {
  51220. console.warn(this.deprecatedMappings[attr]);
  51221. }
  51222. if (!attr || !componentName) { return; }
  51223. // Set value.
  51224. setComponentProperty(this, componentName, value);
  51225. }
  51226. }
  51227. })
  51228. });
  51229. // Store.
  51230. primitives[name] = primitive;
  51231. return primitive;
  51232. };
  51233. /**
  51234. * Add component mappings using schema.
  51235. */
  51236. function addComponentMapping (componentName, mappings) {
  51237. var schema = components[componentName].schema;
  51238. Object.keys(schema).map(function (prop) {
  51239. // Hyphenate where there is camelCase.
  51240. var attrName = prop.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51241. // If there is a mapping collision, prefix with component name and hyphen.
  51242. if (mappings[attrName] !== undefined) { attrName = componentName + '-' + prop; }
  51243. mappings[attrName] = componentName + '.' + prop;
  51244. });
  51245. }
  51246. /**
  51247. * Helper to define a primitive, building mappings using a component schema.
  51248. */
  51249. function definePrimitive (tagName, defaultComponents, mappings) {
  51250. // If no initial mappings provided, start from empty map.
  51251. mappings = mappings || {};
  51252. // From the default components, add mapping automagically.
  51253. Object.keys(defaultComponents).map(function buildMappings (componentName) {
  51254. addComponentMapping(componentName, mappings);
  51255. });
  51256. // Register the primitive.
  51257. module.exports.registerPrimitive(tagName, utils.extendDeep({}, null, {
  51258. defaultComponents: defaultComponents,
  51259. mappings: mappings
  51260. }));
  51261. }
  51262. module.exports.definePrimitive = definePrimitive;
  51263. },{"../../core/a-entity":96,"../../core/a-register-element":99,"../../core/component":100,"../../utils/":167}],116:[function(_dereq_,module,exports){
  51264. var DEFAULT_CAMERA_HEIGHT = _dereq_('../../../constants/').DEFAULT_CAMERA_HEIGHT;
  51265. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51266. registerPrimitive('a-camera', {
  51267. defaultComponents: {
  51268. camera: {
  51269. userHeight: DEFAULT_CAMERA_HEIGHT
  51270. },
  51271. 'look-controls': {},
  51272. 'wasd-controls': {}
  51273. },
  51274. mappings: {
  51275. active: 'camera.active',
  51276. far: 'camera.far',
  51277. fov: 'camera.fov',
  51278. 'look-controls-enabled': 'look-controls.enabled',
  51279. near: 'camera.near',
  51280. 'wasd-controls-enabled': 'wasd-controls.enabled',
  51281. 'reverse-mouse-drag': 'look-controls.reverseMouseDrag',
  51282. 'user-height': 'camera.userHeight',
  51283. zoom: 'camera.zoom'
  51284. },
  51285. deprecatedMappings: {
  51286. 'cursor-color': 'a-camera[cursor-color] has been removed. Use a-cursor[color] instead.',
  51287. 'cursor-maxdistance': 'a-camera[cursor-maxdistance] has been removed. Use a-cursor[max-distance] instead.',
  51288. 'cursor-offset': 'a-camera[cursor-offset] has been removed. Use a-cursor[position] instead.',
  51289. 'cursor-opacity': 'a-camera[cursor-offset] has been removed. Use a-cursor[opacity] instead.',
  51290. 'cursor-scale': 'a-camera[cursor-scale] has been removed. Use a-cursor[scale] instead.',
  51291. 'cursor-visible': 'a-camera[cursor-visible] has been removed. Use a-cursor[visible] instead.'
  51292. }
  51293. });
  51294. },{"../../../constants/":91,"../primitives":115}],117:[function(_dereq_,module,exports){
  51295. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51296. registerPrimitive('a-collada-model', {
  51297. mappings: {
  51298. src: 'collada-model'
  51299. }
  51300. });
  51301. },{"../primitives":115}],118:[function(_dereq_,module,exports){
  51302. var getMeshMixin = _dereq_('../getMeshMixin');
  51303. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51304. var utils = _dereq_('../../../utils/');
  51305. registerPrimitive('a-cursor', utils.extendDeep({}, getMeshMixin(), {
  51306. defaultComponents: {
  51307. cursor: {},
  51308. geometry: {
  51309. primitive: 'ring',
  51310. radiusOuter: 0.016,
  51311. radiusInner: 0.01,
  51312. segmentsTheta: 64
  51313. },
  51314. material: {
  51315. color: '#000',
  51316. shader: 'flat',
  51317. opacity: 0.8
  51318. },
  51319. position: {
  51320. x: 0,
  51321. y: 0,
  51322. z: -1
  51323. },
  51324. raycaster: {
  51325. far: 1000
  51326. }
  51327. },
  51328. mappings: {
  51329. far: 'raycaster.far',
  51330. fuse: 'cursor.fuse',
  51331. interval: 'raycaster.interval',
  51332. objects: 'raycaster.objects',
  51333. 'fuse-timeout': 'cursor.fuseTimeout'
  51334. }
  51335. }));
  51336. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],119:[function(_dereq_,module,exports){
  51337. var getMeshMixin = _dereq_('../getMeshMixin');
  51338. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51339. var utils = _dereq_('../../../utils/');
  51340. registerPrimitive('a-curvedimage', utils.extendDeep({}, getMeshMixin(), {
  51341. defaultComponents: {
  51342. geometry: {
  51343. height: 1,
  51344. primitive: 'cylinder',
  51345. radius: 2,
  51346. segmentsRadial: 48,
  51347. thetaLength: 270,
  51348. openEnded: true,
  51349. thetaStart: 0
  51350. },
  51351. material: {
  51352. color: '#FFF',
  51353. shader: 'flat',
  51354. side: 'double',
  51355. transparent: true,
  51356. repeat: '-1 1'
  51357. }
  51358. },
  51359. mappings: {
  51360. height: 'geometry.height',
  51361. 'open-ended': 'geometry.openEnded',
  51362. radius: 'geometry.radius',
  51363. segments: 'geometry.segmentsRadial',
  51364. start: 'geometry.thetaStart',
  51365. 'theta-length': 'geometry.thetaLength',
  51366. 'theta-start': 'geometry.thetaStart',
  51367. 'width': 'geometry.thetaLength'
  51368. }
  51369. }));
  51370. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],120:[function(_dereq_,module,exports){
  51371. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51372. registerPrimitive('a-gltf-model', {
  51373. mappings: {
  51374. src: 'gltf-model'
  51375. }
  51376. });
  51377. },{"../primitives":115}],121:[function(_dereq_,module,exports){
  51378. var getMeshMixin = _dereq_('../getMeshMixin');
  51379. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51380. var utils = _dereq_('../../../utils/');
  51381. registerPrimitive('a-image', utils.extendDeep({}, getMeshMixin(), {
  51382. defaultComponents: {
  51383. geometry: {
  51384. primitive: 'plane'
  51385. },
  51386. material: {
  51387. color: '#FFF',
  51388. shader: 'flat',
  51389. side: 'double',
  51390. transparent: true
  51391. }
  51392. },
  51393. mappings: {
  51394. height: 'geometry.height',
  51395. width: 'geometry.width'
  51396. }
  51397. }));
  51398. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],122:[function(_dereq_,module,exports){
  51399. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51400. registerPrimitive('a-light', {
  51401. defaultComponents: {
  51402. light: {}
  51403. },
  51404. mappings: {
  51405. angle: 'light.angle',
  51406. color: 'light.color',
  51407. 'ground-color': 'light.groundColor',
  51408. decay: 'light.decay',
  51409. distance: 'light.distance',
  51410. intensity: 'light.intensity',
  51411. penumbra: 'light.penumbra',
  51412. type: 'light.type',
  51413. target: 'light.target'
  51414. }
  51415. });
  51416. },{"../primitives":115}],123:[function(_dereq_,module,exports){
  51417. var meshMixin = _dereq_('../getMeshMixin')();
  51418. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51419. var utils = _dereq_('../../../utils/');
  51420. registerPrimitive('a-obj-model', utils.extendDeep({}, meshMixin, {
  51421. defaultComponents: {
  51422. 'obj-model': {}
  51423. },
  51424. mappings: {
  51425. src: 'obj-model.obj',
  51426. mtl: 'obj-model.mtl'
  51427. }
  51428. }));
  51429. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],124:[function(_dereq_,module,exports){
  51430. var getMeshMixin = _dereq_('../getMeshMixin');
  51431. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51432. var utils = _dereq_('../../../utils/');
  51433. var meshPrimitives = _dereq_('./meshPrimitives');
  51434. registerPrimitive('a-sky', utils.extendDeep({}, getMeshMixin(), {
  51435. defaultComponents: {
  51436. geometry: {
  51437. primitive: 'sphere',
  51438. radius: 5000,
  51439. segmentsWidth: 64,
  51440. segmentsHeight: 20
  51441. },
  51442. material: {
  51443. color: '#FFF',
  51444. shader: 'flat'
  51445. },
  51446. scale: '-1 1 1'
  51447. },
  51448. mappings: utils.extendDeep({}, meshPrimitives['a-sphere'].prototype.mappings)
  51449. }));
  51450. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115,"./meshPrimitives":129}],125:[function(_dereq_,module,exports){
  51451. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51452. registerPrimitive('a-sound', {
  51453. defaultComponents: {
  51454. sound: {}
  51455. },
  51456. mappings: {
  51457. src: 'sound.src',
  51458. on: 'sound.on',
  51459. autoplay: 'sound.autoplay',
  51460. loop: 'sound.loop',
  51461. volume: 'sound.volume'
  51462. }
  51463. });
  51464. },{"../primitives":115}],126:[function(_dereq_,module,exports){
  51465. // <a-text> using `definePrimitive` helper.
  51466. var definePrimitive = _dereq_('../primitives').definePrimitive;
  51467. definePrimitive('a-text', {text: {anchor: 'align', width: 5}});
  51468. },{"../primitives":115}],127:[function(_dereq_,module,exports){
  51469. var getMeshMixin = _dereq_('../getMeshMixin');
  51470. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51471. var utils = _dereq_('../../../utils/');
  51472. registerPrimitive('a-video', utils.extendDeep({}, getMeshMixin(), {
  51473. defaultComponents: {
  51474. geometry: {
  51475. primitive: 'plane'
  51476. },
  51477. material: {
  51478. color: '#FFF',
  51479. shader: 'flat',
  51480. side: 'double',
  51481. transparent: true
  51482. }
  51483. },
  51484. mappings: {
  51485. height: 'geometry.height',
  51486. width: 'geometry.width'
  51487. }
  51488. }));
  51489. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],128:[function(_dereq_,module,exports){
  51490. var getMeshMixin = _dereq_('../getMeshMixin');
  51491. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51492. var utils = _dereq_('../../../utils/');
  51493. registerPrimitive('a-videosphere', utils.extendDeep({}, getMeshMixin(), {
  51494. defaultComponents: {
  51495. geometry: {
  51496. primitive: 'sphere',
  51497. radius: 5000,
  51498. segmentsWidth: 64,
  51499. segmentsHeight: 20
  51500. },
  51501. material: {
  51502. color: '#FFF',
  51503. shader: 'flat'
  51504. },
  51505. scale: '-1 1 1'
  51506. },
  51507. mappings: {
  51508. radius: 'geometry.radius',
  51509. 'segments-height': 'geometry.segmentsHeight',
  51510. 'segments-width': 'geometry.segmentsWidth'
  51511. }
  51512. }));
  51513. },{"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],129:[function(_dereq_,module,exports){
  51514. /**
  51515. * Automated mesh primitive registration.
  51516. */
  51517. var getMeshMixin = _dereq_('../getMeshMixin');
  51518. var geometries = _dereq_('../../../core/geometry').geometries;
  51519. var geometryNames = _dereq_('../../../core/geometry').geometryNames;
  51520. var registerPrimitive = _dereq_('../primitives').registerPrimitive;
  51521. var utils = _dereq_('../../../utils/');
  51522. // For testing.
  51523. var meshPrimitives = module.exports = {};
  51524. // Generate primitive for each geometry type.
  51525. geometryNames.forEach(function registerMeshPrimitive (geometryName) {
  51526. var geometry = geometries[geometryName];
  51527. var geometryHyphened = unCamelCase(geometryName);
  51528. // Generate mappings.
  51529. var mappings = {};
  51530. Object.keys(geometry.schema).forEach(function createMapping (property) {
  51531. mappings[unCamelCase(property)] = 'geometry.' + property;
  51532. });
  51533. // Register.
  51534. var tagName = 'a-' + geometryHyphened;
  51535. var primitive = registerPrimitive(tagName, utils.extendDeep({}, getMeshMixin(), {
  51536. defaultComponents: {geometry: {primitive: geometryName}},
  51537. mappings: mappings
  51538. }));
  51539. meshPrimitives[tagName] = primitive;
  51540. });
  51541. /**
  51542. * camelCase to hyphened-string.
  51543. */
  51544. function unCamelCase (str) {
  51545. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  51546. }
  51547. },{"../../../core/geometry":101,"../../../utils/":167,"../getMeshMixin":113,"../primitives":115}],130:[function(_dereq_,module,exports){
  51548. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51549. var THREE = _dereq_('../lib/three');
  51550. registerGeometry('box', {
  51551. schema: {
  51552. depth: {default: 1, min: 0},
  51553. height: {default: 1, min: 0},
  51554. width: {default: 1, min: 0},
  51555. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  51556. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'},
  51557. segmentsDepth: {default: 1, min: 1, max: 20, type: 'int'}
  51558. },
  51559. init: function (data) {
  51560. this.geometry = new THREE.BoxGeometry(data.width, data.height, data.depth);
  51561. }
  51562. });
  51563. },{"../core/geometry":101,"../lib/three":146}],131:[function(_dereq_,module,exports){
  51564. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51565. var THREE = _dereq_('../lib/three');
  51566. var degToRad = THREE.Math.degToRad;
  51567. registerGeometry('circle', {
  51568. schema: {
  51569. radius: {default: 1, min: 0},
  51570. segments: {default: 32, min: 3, type: 'int'},
  51571. thetaLength: {default: 360, min: 0},
  51572. thetaStart: {default: 0}
  51573. },
  51574. init: function (data) {
  51575. this.geometry = new THREE.CircleGeometry(
  51576. data.radius, data.segments, degToRad(data.thetaStart), degToRad(data.thetaLength));
  51577. }
  51578. });
  51579. },{"../core/geometry":101,"../lib/three":146}],132:[function(_dereq_,module,exports){
  51580. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51581. var THREE = _dereq_('../lib/three');
  51582. var degToRad = THREE.Math.degToRad;
  51583. registerGeometry('cone', {
  51584. schema: {
  51585. height: {default: 1, min: 0},
  51586. openEnded: {default: false},
  51587. radiusBottom: {default: 1, min: 0},
  51588. radiusTop: {default: 0.8, min: 0},
  51589. segmentsHeight: {default: 18, min: 1, type: 'int'},
  51590. segmentsRadial: {default: 36, min: 3, type: 'int'},
  51591. thetaLength: {default: 360, min: 0},
  51592. thetaStart: {default: 0}
  51593. },
  51594. init: function (data) {
  51595. this.geometry = new THREE.CylinderGeometry(
  51596. data.radiusTop, data.radiusBottom, data.height, data.segmentsRadial,
  51597. data.segmentsHeight, data.openEnded, degToRad(data.thetaStart),
  51598. degToRad(data.thetaLength));
  51599. }
  51600. });
  51601. },{"../core/geometry":101,"../lib/three":146}],133:[function(_dereq_,module,exports){
  51602. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51603. var THREE = _dereq_('../lib/three');
  51604. var degToRad = THREE.Math.degToRad;
  51605. registerGeometry('cylinder', {
  51606. schema: {
  51607. height: {default: 1, min: 0},
  51608. openEnded: {default: false},
  51609. radius: {default: 1, min: 0},
  51610. segmentsHeight: {default: 18, min: 1, type: 'int'},
  51611. segmentsRadial: {default: 36, min: 3, type: 'int'},
  51612. thetaLength: {default: 360, min: 0},
  51613. thetaStart: {default: 0}
  51614. },
  51615. init: function (data) {
  51616. this.geometry = new THREE.CylinderGeometry(
  51617. data.radius, data.radius, data.height, data.segmentsRadial, data.segmentsHeight,
  51618. data.openEnded, degToRad(data.thetaStart), degToRad(data.thetaLength));
  51619. }
  51620. });
  51621. },{"../core/geometry":101,"../lib/three":146}],134:[function(_dereq_,module,exports){
  51622. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51623. var THREE = _dereq_('../lib/three');
  51624. registerGeometry('dodecahedron', {
  51625. schema: {
  51626. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51627. radius: {default: 1, min: 0}
  51628. },
  51629. init: function (data) {
  51630. this.geometry = new THREE.DodecahedronGeometry(data.radius, data.detail);
  51631. }
  51632. });
  51633. },{"../core/geometry":101,"../lib/three":146}],135:[function(_dereq_,module,exports){
  51634. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51635. var THREE = _dereq_('../lib/three');
  51636. registerGeometry('icosahedron', {
  51637. schema: {
  51638. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51639. radius: {default: 1, min: 0}
  51640. },
  51641. init: function (data) {
  51642. this.geometry = new THREE.IcosahedronGeometry(data.radius, data.detail);
  51643. }
  51644. });
  51645. },{"../core/geometry":101,"../lib/three":146}],136:[function(_dereq_,module,exports){
  51646. _dereq_('./box.js');
  51647. _dereq_('./circle.js');
  51648. _dereq_('./cone.js');
  51649. _dereq_('./cylinder.js');
  51650. _dereq_('./dodecahedron.js');
  51651. _dereq_('./icosahedron.js');
  51652. _dereq_('./octahedron.js');
  51653. _dereq_('./plane.js');
  51654. _dereq_('./ring.js');
  51655. _dereq_('./sphere.js');
  51656. _dereq_('./tetrahedron.js');
  51657. _dereq_('./torus.js');
  51658. _dereq_('./torusKnot.js');
  51659. },{"./box.js":130,"./circle.js":131,"./cone.js":132,"./cylinder.js":133,"./dodecahedron.js":134,"./icosahedron.js":135,"./octahedron.js":137,"./plane.js":138,"./ring.js":139,"./sphere.js":140,"./tetrahedron.js":141,"./torus.js":142,"./torusKnot.js":143}],137:[function(_dereq_,module,exports){
  51660. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51661. var THREE = _dereq_('../lib/three');
  51662. registerGeometry('octahedron', {
  51663. schema: {
  51664. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51665. radius: {default: 1, min: 0}
  51666. },
  51667. init: function (data) {
  51668. this.geometry = new THREE.OctahedronGeometry(data.radius, data.detail);
  51669. }
  51670. });
  51671. },{"../core/geometry":101,"../lib/three":146}],138:[function(_dereq_,module,exports){
  51672. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51673. var THREE = _dereq_('../lib/three');
  51674. registerGeometry('plane', {
  51675. schema: {
  51676. height: {default: 1, min: 0},
  51677. width: {default: 1, min: 0},
  51678. segmentsHeight: {default: 1, min: 1, max: 20, type: 'int'},
  51679. segmentsWidth: {default: 1, min: 1, max: 20, type: 'int'}
  51680. },
  51681. init: function (data) {
  51682. this.geometry = new THREE.PlaneGeometry(data.width, data.height);
  51683. }
  51684. });
  51685. },{"../core/geometry":101,"../lib/three":146}],139:[function(_dereq_,module,exports){
  51686. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51687. var THREE = _dereq_('../lib/three');
  51688. var degToRad = THREE.Math.degToRad;
  51689. registerGeometry('ring', {
  51690. schema: {
  51691. radiusInner: {default: 0.8, min: 0},
  51692. radiusOuter: {default: 1.2, min: 0},
  51693. segmentsPhi: {default: 10, min: 1, type: 'int'},
  51694. segmentsTheta: {default: 32, min: 3, type: 'int'},
  51695. thetaLength: {default: 360, min: 0},
  51696. thetaStart: {default: 0}
  51697. },
  51698. init: function (data) {
  51699. this.geometry = new THREE.RingGeometry(
  51700. data.radiusInner, data.radiusOuter, data.segmentsTheta, data.segmentsPhi,
  51701. degToRad(data.thetaStart), degToRad(data.thetaLength));
  51702. }
  51703. });
  51704. },{"../core/geometry":101,"../lib/three":146}],140:[function(_dereq_,module,exports){
  51705. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51706. var THREE = _dereq_('../lib/three');
  51707. var degToRad = THREE.Math.degToRad;
  51708. registerGeometry('sphere', {
  51709. schema: {
  51710. radius: {default: 1, min: 0},
  51711. phiLength: {default: 360},
  51712. phiStart: {default: 0, min: 0},
  51713. thetaLength: {default: 180, min: 0},
  51714. thetaStart: {default: 0},
  51715. segmentsHeight: {default: 18, min: 2, type: 'int'},
  51716. segmentsWidth: {default: 36, min: 3, type: 'int'}
  51717. },
  51718. init: function (data) {
  51719. this.geometry = new THREE.SphereGeometry(
  51720. data.radius, data.segmentsWidth, data.segmentsHeight, degToRad(data.phiStart),
  51721. degToRad(data.phiLength), degToRad(data.thetaStart), degToRad(data.thetaLength));
  51722. }
  51723. });
  51724. },{"../core/geometry":101,"../lib/three":146}],141:[function(_dereq_,module,exports){
  51725. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51726. var THREE = _dereq_('../lib/three');
  51727. registerGeometry('tetrahedron', {
  51728. schema: {
  51729. detail: {default: 0, min: 0, max: 5, type: 'int'},
  51730. radius: {default: 1, min: 0}
  51731. },
  51732. init: function (data) {
  51733. this.geometry = new THREE.TetrahedronGeometry(data.radius, data.detail);
  51734. }
  51735. });
  51736. },{"../core/geometry":101,"../lib/three":146}],142:[function(_dereq_,module,exports){
  51737. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51738. var THREE = _dereq_('../lib/three');
  51739. var degToRad = THREE.Math.degToRad;
  51740. registerGeometry('torus', {
  51741. schema: {
  51742. arc: {default: 360},
  51743. radius: {default: 1, min: 0},
  51744. radiusTubular: {default: 0.2, min: 0},
  51745. segmentsRadial: {default: 36, min: 2, type: 'int'},
  51746. segmentsTubular: {default: 32, min: 3, type: 'int'}
  51747. },
  51748. init: function (data) {
  51749. this.geometry = new THREE.TorusGeometry(
  51750. data.radius, data.radiusTubular * 2, data.segmentsRadial, data.segmentsTubular,
  51751. degToRad(data.arc));
  51752. }
  51753. });
  51754. },{"../core/geometry":101,"../lib/three":146}],143:[function(_dereq_,module,exports){
  51755. var registerGeometry = _dereq_('../core/geometry').registerGeometry;
  51756. var THREE = _dereq_('../lib/three');
  51757. registerGeometry('torusKnot', {
  51758. schema: {
  51759. p: {default: 2, min: 1},
  51760. q: {default: 3, min: 1},
  51761. radius: {default: 1, min: 0},
  51762. radiusTubular: {default: 0.2, min: 0},
  51763. segmentsRadial: {default: 8, min: 3, type: 'int'},
  51764. segmentsTubular: {default: 100, min: 3, type: 'int'}
  51765. },
  51766. init: function (data) {
  51767. this.geometry = new THREE.TorusKnotGeometry(
  51768. data.radius, data.radiusTubular * 2, data.segmentsTubular, data.segmentsRadial,
  51769. data.p, data.q);
  51770. }
  51771. });
  51772. },{"../core/geometry":101,"../lib/three":146}],144:[function(_dereq_,module,exports){
  51773. var utils = _dereq_('./utils/');
  51774. var debug = utils.debug;
  51775. var warn = debug('A-Frame:warn');
  51776. if (document.currentScript && document.currentScript.parentNode !== document.head &&
  51777. !window.debug) {
  51778. warn('Put the A-Frame <script> tag in the <head> of the HTML *before* the scene to ' +
  51779. 'ensure everything for A-Frame is properly registered before they are used from ' +
  51780. 'HTML.');
  51781. }
  51782. // Polyfill `Promise`.
  51783. window.Promise = window.Promise || _dereq_('promise-polyfill');
  51784. // Check before the polyfill runs
  51785. window.hasNativeWebVRImplementation = !!navigator.getVRDisplays || !!navigator.getVRDevices;
  51786. window.WebVRConfig = window.WebVRConfig || {
  51787. BUFFER_SCALE: 1,
  51788. CARDBOARD_UI_DISABLED: true,
  51789. ROTATE_INSTRUCTIONS_DISABLED: true,
  51790. TOUCH_PANNER_DISABLED: true,
  51791. MOUSE_KEYBOARD_CONTROLS_DISABLED: true
  51792. };
  51793. // Workaround for iOS Safari canvas sizing issues in stereo (webvr-polyfill/issues/102).
  51794. // Only for iOS on versions older than 10.
  51795. if (utils.device.isIOSOlderThan10(navigator.userAgent)) {
  51796. window.WebVRConfig.BUFFER_SCALE = 1 / window.devicePixelRatio;
  51797. }
  51798. // WebVR polyfill
  51799. _dereq_('webvr-polyfill');
  51800. _dereq_('present'); // Polyfill `performance.now()`.
  51801. // CSS.
  51802. _dereq_('./style/aframe.css');
  51803. _dereq_('./style/rStats.css');
  51804. // Required before `AEntity` so that all components are registered.
  51805. var AScene = _dereq_('./core/scene/a-scene');
  51806. var components = _dereq_('./core/component').components;
  51807. var registerComponent = _dereq_('./core/component').registerComponent;
  51808. var registerGeometry = _dereq_('./core/geometry').registerGeometry;
  51809. var registerPrimitive = _dereq_('./extras/primitives/primitives').registerPrimitive;
  51810. var registerShader = _dereq_('./core/shader').registerShader;
  51811. var registerSystem = _dereq_('./core/system').registerSystem;
  51812. var shaders = _dereq_('./core/shader').shaders;
  51813. var systems = _dereq_('./core/system').systems;
  51814. // Exports THREE to window so three.js can be used without alteration.
  51815. var THREE = window.THREE = _dereq_('./lib/three');
  51816. var TWEEN = window.TWEEN = _dereq_('tween.js');
  51817. var pkg = _dereq_('../package');
  51818. _dereq_('./components/index'); // Register standard components.
  51819. _dereq_('./geometries/index'); // Register standard geometries.
  51820. _dereq_('./shaders/index'); // Register standard shaders.
  51821. _dereq_('./systems/index'); // Register standard systems.
  51822. var ANode = _dereq_('./core/a-node');
  51823. var AEntity = _dereq_('./core/a-entity'); // Depends on ANode and core components.
  51824. _dereq_('./core/a-animation');
  51825. _dereq_('./core/a-assets');
  51826. _dereq_('./core/a-cubemap');
  51827. _dereq_('./core/a-mixin');
  51828. // Extras.
  51829. _dereq_('./extras/components/');
  51830. _dereq_('./extras/primitives/');
  51831. console.log('A-Frame Version: 0.5.0 (Date 10-02-2017, Commit #bf8b8f9)');
  51832. console.log('three Version:', pkg.dependencies['three']);
  51833. console.log('WebVR Polyfill Version:', pkg.dependencies['webvr-polyfill']);
  51834. module.exports = window.AFRAME = {
  51835. AComponent: _dereq_('./core/component').Component,
  51836. AEntity: AEntity,
  51837. ANode: ANode,
  51838. AScene: AScene,
  51839. components: components,
  51840. geometries: _dereq_('./core/geometry').geometries,
  51841. registerComponent: registerComponent,
  51842. registerElement: _dereq_('./core/a-register-element').registerElement,
  51843. registerGeometry: registerGeometry,
  51844. registerPrimitive: registerPrimitive,
  51845. registerShader: registerShader,
  51846. registerSystem: registerSystem,
  51847. primitives: {
  51848. getMeshMixin: _dereq_('./extras/primitives/getMeshMixin'),
  51849. primitives: _dereq_('./extras/primitives/primitives').primitives
  51850. },
  51851. scenes: _dereq_('./core/scene/scenes'),
  51852. schema: _dereq_('./core/schema'),
  51853. shaders: shaders,
  51854. systems: systems,
  51855. THREE: THREE,
  51856. TWEEN: TWEEN,
  51857. utils: utils,
  51858. version: pkg.version
  51859. };
  51860. },{"../package":55,"./components/index":63,"./core/a-animation":93,"./core/a-assets":94,"./core/a-cubemap":95,"./core/a-entity":96,"./core/a-mixin":97,"./core/a-node":98,"./core/a-register-element":99,"./core/component":100,"./core/geometry":101,"./core/scene/a-scene":103,"./core/scene/scenes":106,"./core/schema":108,"./core/shader":109,"./core/system":110,"./extras/components/":111,"./extras/primitives/":114,"./extras/primitives/getMeshMixin":113,"./extras/primitives/primitives":115,"./geometries/index":136,"./lib/three":146,"./shaders/index":148,"./style/aframe.css":152,"./style/rStats.css":153,"./systems/index":157,"./utils/":167,"present":34,"promise-polyfill":35,"tween.js":49,"webvr-polyfill":50}],145:[function(_dereq_,module,exports){
  51861. window.aframeStats = function (scene) {
  51862. var _rS = null;
  51863. var _scene = scene;
  51864. var _values = {
  51865. te: {
  51866. caption: 'Entities'
  51867. },
  51868. lt: {
  51869. caption: 'Load Time'
  51870. }
  51871. };
  51872. var _groups = [ {
  51873. caption: 'A-Frame',
  51874. values: [ 'te', 'lt' ]
  51875. } ];
  51876. function _update () {
  51877. _rS('te').set(getEntityCount());
  51878. if (window.performance.getEntriesByName) {
  51879. _rS('lt').set(window.performance.getEntriesByName('render-started')[0].startTime.toFixed(0));
  51880. }
  51881. }
  51882. function getEntityCount () {
  51883. var elements = _scene.querySelectorAll('*');
  51884. Array.prototype.slice.call(elements).filter(function (el) {
  51885. return el.isEntity;
  51886. });
  51887. return elements.length;
  51888. }
  51889. function _start () {}
  51890. function _end () {}
  51891. function _attach (r) {
  51892. _rS = r;
  51893. }
  51894. return {
  51895. update: _update,
  51896. start: _start,
  51897. end: _end,
  51898. attach: _attach,
  51899. values: _values,
  51900. groups: _groups,
  51901. fractions: []
  51902. };
  51903. };
  51904. if (typeof module === 'object') {
  51905. module.exports = {
  51906. aframeStats: window.aframeStats
  51907. };
  51908. }
  51909. },{}],146:[function(_dereq_,module,exports){
  51910. (function (global){
  51911. var THREE = global.THREE = _dereq_('three');
  51912. // Allow cross-origin images to be loaded.
  51913. // This should not be on `THREE.Loader` nor `THREE.ImageUtils`.
  51914. // Must be on `THREE.TextureLoader`.
  51915. if (THREE.TextureLoader) {
  51916. THREE.TextureLoader.prototype.crossOrigin = 'anonymous';
  51917. }
  51918. // This is for images loaded from the model loaders.
  51919. if (THREE.ImageLoader) {
  51920. THREE.ImageLoader.prototype.crossOrigin = 'anonymous';
  51921. }
  51922. // In-memory caching for XHRs (for images, audio files, textures, etc.).
  51923. if (THREE.Cache) {
  51924. THREE.Cache.enabled = true;
  51925. }
  51926. // TODO: Eventually include these only if they are needed by a component.
  51927. _dereq_('three/examples/js/loaders/GLTFLoader'); // THREE.GLTFLoader
  51928. _dereq_('three/examples/js/loaders/OBJLoader'); // THREE.OBJLoader
  51929. _dereq_('three/examples/js/loaders/MTLLoader'); // THREE.MTLLoader
  51930. _dereq_('three/examples/js/BlendCharacter'); // THREE.BlendCharacter
  51931. _dereq_('three/examples/js/loaders/ColladaLoader'); // THREE.ColladaLoader
  51932. _dereq_('../../vendor/VRControls'); // THREE.VRControls
  51933. _dereq_('../../vendor/VREffect'); // THREE.VREffect
  51934. THREE.ColladaLoader.prototype.crossOrigin = 'anonymous';
  51935. THREE.GLTFLoader.prototype.crossOrigin = 'anonymous';
  51936. THREE.MTLLoader.prototype.crossOrigin = 'anonymous';
  51937. THREE.OBJLoader.prototype.crossOrigin = 'anonymous';
  51938. module.exports = THREE;
  51939. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  51940. },{"../../vendor/VRControls":172,"../../vendor/VREffect":173,"three":42,"three/examples/js/BlendCharacter":43,"three/examples/js/loaders/ColladaLoader":44,"three/examples/js/loaders/GLTFLoader":45,"three/examples/js/loaders/MTLLoader":46,"three/examples/js/loaders/OBJLoader":47}],147:[function(_dereq_,module,exports){
  51941. var registerShader = _dereq_('../core/shader').registerShader;
  51942. var THREE = _dereq_('../lib/three');
  51943. var utils = _dereq_('../utils/');
  51944. /**
  51945. * Flat shader using THREE.MeshBasicMaterial.
  51946. */
  51947. module.exports.Shader = registerShader('flat', {
  51948. schema: {
  51949. color: {type: 'color'},
  51950. fog: {default: true},
  51951. height: {default: 256},
  51952. offset: {type: 'vec2', default: {x: 0, y: 0}},
  51953. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  51954. src: {type: 'map'},
  51955. width: {default: 512},
  51956. wireframe: {default: false},
  51957. wireframeLinewidth: {default: 2}
  51958. },
  51959. /**
  51960. * Initializes the shader.
  51961. * Adds a reference from the scene to this entity as the camera.
  51962. */
  51963. init: function (data) {
  51964. this.textureSrc = null;
  51965. this.material = new THREE.MeshBasicMaterial(getMaterialData(data));
  51966. utils.material.updateMap(this, data);
  51967. },
  51968. update: function (data) {
  51969. this.updateMaterial(data);
  51970. utils.material.updateMap(this, data);
  51971. },
  51972. /**
  51973. * Updating existing material.
  51974. *
  51975. * @param {object} data - Material component data.
  51976. */
  51977. updateMaterial: function (data) {
  51978. var material = this.material;
  51979. data = getMaterialData(data);
  51980. Object.keys(data).forEach(function (key) {
  51981. material[key] = data[key];
  51982. });
  51983. }
  51984. });
  51985. /**
  51986. * Builds and normalize material data, normalizing stuff along the way.
  51987. *
  51988. * @param {object} data - Material data.
  51989. * @returns {object} data - Processed material data.
  51990. */
  51991. function getMaterialData (data) {
  51992. return {
  51993. fog: data.fog,
  51994. color: new THREE.Color(data.color),
  51995. wireframe: data.wireframe,
  51996. wireframeLinewidth: data.wireframeLinewidth
  51997. };
  51998. }
  51999. },{"../core/shader":109,"../lib/three":146,"../utils/":167}],148:[function(_dereq_,module,exports){
  52000. _dereq_('./flat');
  52001. _dereq_('./standard');
  52002. _dereq_('./sdf');
  52003. _dereq_('./msdf');
  52004. },{"./flat":147,"./msdf":149,"./sdf":150,"./standard":151}],149:[function(_dereq_,module,exports){
  52005. var registerShader = _dereq_('../core/shader').registerShader;
  52006. /**
  52007. * Multi-channel signed distance field.
  52008. * Used by text component.
  52009. */
  52010. module.exports.Shader = registerShader('msdf', {
  52011. schema: {
  52012. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52013. color: {type: 'color', is: 'uniform', default: 'white'},
  52014. map: {type: 'map', is: 'uniform'},
  52015. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52016. },
  52017. raw: true,
  52018. vertexShader: [
  52019. 'attribute vec2 uv;',
  52020. 'attribute vec3 position;',
  52021. 'uniform mat4 projectionMatrix;',
  52022. 'uniform mat4 modelViewMatrix;',
  52023. 'varying vec2 vUV;',
  52024. 'void main(void) {',
  52025. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52026. ' vUV = uv;',
  52027. '}'
  52028. ].join('\n'),
  52029. fragmentShader: [
  52030. '#ifdef GL_OES_standard_derivatives',
  52031. '#extension GL_OES_standard_derivatives: enable',
  52032. '#endif',
  52033. 'precision highp float;',
  52034. // FIXME: Experimentally determined constants.
  52035. '#define BIG_ENOUGH 0.001',
  52036. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52037. '#define ALL_SMOOTH 0.4',
  52038. '#define ALL_ROUGH 0.02',
  52039. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52040. 'uniform sampler2D map;',
  52041. 'uniform vec3 color;',
  52042. 'uniform float opacity;',
  52043. 'uniform float alphaTest;',
  52044. 'varying vec2 vUV;',
  52045. 'float median(float r, float g, float b) {',
  52046. ' return max(min(r, g), min(max(r, g), b));',
  52047. '}',
  52048. 'void main() {',
  52049. ' vec3 sample = 1.0 - texture2D(map, vUV).rgb;',
  52050. ' float sigDist = median(sample.r, sample.g, sample.b) - 0.5;',
  52051. ' float alpha = clamp(sigDist/fwidth(sigDist) + 0.5, 0.0, 1.0);',
  52052. ' float dscale = 0.353505;',
  52053. ' vec2 duv = dscale * (dFdx(vUV) + dFdy(vUV));',
  52054. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52055. // When texel is too small, blend raw alpha value rather than supersampling.
  52056. // FIXME: Experimentally determined constant.
  52057. ' if (isBigEnough > BIG_ENOUGH) {',
  52058. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52059. ' alpha = ratio * alpha + (1.0 - ratio) * (sigDist + 0.5);',
  52060. ' }',
  52061. ' gl_FragColor = vec4(color.xyz, alpha * opacity);',
  52062. // When texel is big enough, do standard alpha test.
  52063. // FIXME: Experimentally determined constant.
  52064. // Looks much better if we *don't* do this, but do we get Z fighting?
  52065. ' if (isBigEnough <= BIG_ENOUGH && gl_FragColor.a < alphaTest) { discard; return; }',
  52066. // Else, do modified alpha test.
  52067. // FIXME: Experimentally determined constant.
  52068. ' if (gl_FragColor.a < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52069. '}'
  52070. ].join('\n')
  52071. });
  52072. },{"../core/shader":109}],150:[function(_dereq_,module,exports){
  52073. var registerShader = _dereq_('../core/shader').registerShader;
  52074. /**
  52075. * Signed distance field.
  52076. * Used by text component.
  52077. */
  52078. module.exports.Shader = registerShader('sdf', {
  52079. schema: {
  52080. alphaTest: {type: 'number', is: 'uniform', default: 0.5},
  52081. color: {type: 'color', is: 'uniform', default: 'white'},
  52082. map: {type: 'map', is: 'uniform'},
  52083. opacity: {type: 'number', is: 'uniform', default: 1.0}
  52084. },
  52085. raw: true,
  52086. vertexShader: [
  52087. 'attribute vec2 uv;',
  52088. 'attribute vec3 position;',
  52089. 'uniform mat4 projectionMatrix;',
  52090. 'uniform mat4 modelViewMatrix;',
  52091. 'varying vec2 vUV;',
  52092. 'void main(void) {',
  52093. ' gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);',
  52094. ' vUV = uv;',
  52095. '}'
  52096. ].join('\n'),
  52097. fragmentShader: [
  52098. '#ifdef GL_OES_standard_derivatives',
  52099. '#extension GL_OES_standard_derivatives: enable',
  52100. '#endif',
  52101. 'precision highp float;',
  52102. // FIXME: experimentally determined constants
  52103. '#define BIG_ENOUGH 0.001',
  52104. '#define MODIFIED_ALPHATEST (0.02 * isBigEnough / BIG_ENOUGH)',
  52105. '#define ALL_SMOOTH 0.4',
  52106. '#define ALL_ROUGH 0.02',
  52107. '#define DISCARD_ALPHA (alphaTest / (2.2 - 1.2 * ratio))',
  52108. 'uniform sampler2D map;',
  52109. 'uniform vec3 color;',
  52110. 'uniform float opacity;',
  52111. 'uniform float alphaTest;',
  52112. 'varying vec2 vUV;',
  52113. '#ifdef GL_OES_standard_derivatives',
  52114. 'float contour(float width, float value) {',
  52115. ' return smoothstep(0.5 - value, 0.5 + value, width);',
  52116. '}',
  52117. '#else',
  52118. 'float aastep(float value, float afwidth) {',
  52119. ' return smoothstep(0.5 - afwidth, 0.5 + afwidth, value);',
  52120. '}',
  52121. '#endif',
  52122. 'void main() {',
  52123. '#ifdef GL_OES_standard_derivatives',
  52124. // when we have derivatives and can get texel size etc., that allows supersampling etc.
  52125. ' vec2 uv = vUV;',
  52126. ' vec4 texColor = texture2D(map, uv);',
  52127. ' float dist = texColor.a;',
  52128. ' float width = fwidth(dist);',
  52129. ' float alpha = contour(dist, width);',
  52130. ' float dscale = 0.353505;',
  52131. ' vec2 duv = dscale * (dFdx(uv) + dFdy(uv));',
  52132. ' float isBigEnough = max(abs(duv.x), abs(duv.y));',
  52133. // when texel is too small, blend raw alpha value rather than supersampling etc.
  52134. // FIXME: experimentally determined constant
  52135. ' if (isBigEnough > BIG_ENOUGH) {',
  52136. ' float ratio = BIG_ENOUGH / isBigEnough;',
  52137. ' alpha = ratio * alpha + (1.0 - ratio) * dist;',
  52138. ' }',
  52139. // otherwise do weighted supersampling
  52140. // FIXME: why this weighting?
  52141. ' else if (isBigEnough <= BIG_ENOUGH) {',
  52142. ' vec4 box = vec4 (uv - duv, uv + duv);',
  52143. ' alpha = (alpha + 0.5 * (',
  52144. ' contour(texture2D(map, box.xy).a, width)',
  52145. ' + contour(texture2D(map, box.zw).a, width)',
  52146. ' + contour(texture2D(map, box.xw).a, width)',
  52147. ' + contour(texture2D(map, box.zy).a, width)',
  52148. ' )) / 3.0;',
  52149. ' }',
  52150. // when texel is big enough, do standard alpha test
  52151. // FIXME: experimentally determined constant
  52152. // looks much better if we DON'T do this, but do we get Z fighting etc.?
  52153. ' if (isBigEnough <= BIG_ENOUGH && alpha < alphaTest) { discard; return; }',
  52154. // else do modified alpha test
  52155. // FIXME: experimentally determined constant
  52156. ' if (alpha < alphaTest * MODIFIED_ALPHATEST) { discard; return; }',
  52157. '#else',
  52158. ' vec4 texColor = texture2D(map, vUV);',
  52159. ' float value = texColor.a;',
  52160. // when we don't have derivatives, use approximations
  52161. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52162. ' float afwidth = (1.0 / 32.0) * (1.4142135623730951 / (2.0 * gl_FragCoord.w));',
  52163. ' float alpha = aastep(value, afwidth);',
  52164. // use gl_FragCoord.w to guess when we should blend
  52165. // FIXME: if we understood font pixel dimensions, this could probably be improved
  52166. ' 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);',
  52167. ' if (alpha < alphaTest) { if (ratio >= 1.0) { discard; return; } alpha = 0.0; }',
  52168. ' alpha = alpha * ratio + (1.0 - ratio) * value;',
  52169. ' if (ratio < 1.0)',
  52170. ' if (alpha <= DISCARD_ALPHA) { discard; return; }',
  52171. '#endif',
  52172. ' gl_FragColor = vec4(color, opacity * alpha);',
  52173. '}'
  52174. ].join('\n')
  52175. });
  52176. },{"../core/shader":109}],151:[function(_dereq_,module,exports){
  52177. var registerShader = _dereq_('../core/shader').registerShader;
  52178. var THREE = _dereq_('../lib/three');
  52179. var utils = _dereq_('../utils/');
  52180. var CubeLoader = new THREE.CubeTextureLoader();
  52181. var texturePromises = {};
  52182. /**
  52183. * Standard (physically-based) shader using THREE.MeshStandardMaterial.
  52184. */
  52185. module.exports.Shader = registerShader('standard', {
  52186. schema: {
  52187. ambientOcclusionMap: {type: 'map'},
  52188. ambientOcclusionMapIntensity: {default: 1},
  52189. ambientOcclusionTextureOffset: {type: 'vec2'},
  52190. ambientOcclusionTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52191. color: {type: 'color'},
  52192. displacementMap: {type: 'map'},
  52193. displacementScale: {default: 1},
  52194. displacementBias: {default: 0.5},
  52195. displacementTextureOffset: {type: 'vec2'},
  52196. displacementTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52197. envMap: {default: ''},
  52198. fog: {default: true},
  52199. height: {default: 256},
  52200. metalness: {default: 0.0, min: 0.0, max: 1.0},
  52201. normalMap: {type: 'map'},
  52202. normalScale: {type: 'vec2', default: '1 1'},
  52203. normalTextureOffset: {type: 'vec2'},
  52204. normalTextureRepeat: {type: 'vec2', default: {x: 1, y: 1}},
  52205. offset: {type: 'vec2', default: {x: 0, y: 0}},
  52206. repeat: {type: 'vec2', default: {x: 1, y: 1}},
  52207. roughness: {default: 0.5, min: 0.0, max: 1.0},
  52208. sphericalEnvMap: {type: 'map'},
  52209. src: {type: 'map'},
  52210. width: {default: 512},
  52211. wireframe: {default: false},
  52212. wireframeLinewidth: {default: 2}
  52213. },
  52214. /**
  52215. * Initializes the shader.
  52216. * Adds a reference from the scene to this entity as the camera.
  52217. */
  52218. init: function (data) {
  52219. this.material = new THREE.MeshStandardMaterial(getMaterialData(data));
  52220. utils.material.updateMap(this, data);
  52221. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52222. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52223. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52224. this.updateEnvMap(data);
  52225. },
  52226. update: function (data) {
  52227. this.updateMaterial(data);
  52228. utils.material.updateMap(this, data);
  52229. if (data.normalMap) { utils.material.updateDistortionMap('normal', this, data); }
  52230. if (data.displacementMap) { utils.material.updateDistortionMap('displacement', this, data); }
  52231. if (data.ambientOcclusionMap) { utils.material.updateDistortionMap('ambientOcclusion', this, data); }
  52232. this.updateEnvMap(data);
  52233. },
  52234. /**
  52235. * Updating existing material.
  52236. *
  52237. * @param {object} data - Material component data.
  52238. * @returns {object} Material.
  52239. */
  52240. updateMaterial: function (data) {
  52241. var material = this.material;
  52242. data = getMaterialData(data);
  52243. Object.keys(data).forEach(function (key) {
  52244. material[key] = data[key];
  52245. });
  52246. },
  52247. /**
  52248. * Handle environment cubemap. Textures are cached in texturePromises.
  52249. */
  52250. updateEnvMap: function (data) {
  52251. var self = this;
  52252. var material = this.material;
  52253. var envMap = data.envMap;
  52254. var sphericalEnvMap = data.sphericalEnvMap;
  52255. // No envMap defined or already loading.
  52256. if ((!envMap && !sphericalEnvMap) || this.isLoadingEnvMap) {
  52257. material.envMap = null;
  52258. material.needsUpdate = true;
  52259. return;
  52260. }
  52261. this.isLoadingEnvMap = true;
  52262. // if a spherical env map is defined then use it.
  52263. if (sphericalEnvMap) {
  52264. this.el.sceneEl.systems.material.loadTexture(sphericalEnvMap, {src: sphericalEnvMap}, function textureLoaded (texture) {
  52265. self.isLoadingEnvMap = false;
  52266. texture.mapping = THREE.SphericalReflectionMapping;
  52267. material.envMap = texture;
  52268. utils.material.handleTextureEvents(self.el, texture);
  52269. material.needsUpdate = true;
  52270. });
  52271. return;
  52272. }
  52273. // Another material is already loading this texture. Wait on promise.
  52274. if (texturePromises[envMap]) {
  52275. texturePromises[envMap].then(function (cube) {
  52276. self.isLoadingEnvMap = false;
  52277. material.envMap = cube;
  52278. utils.material.handleTextureEvents(self.el, cube);
  52279. material.needsUpdate = true;
  52280. });
  52281. return;
  52282. }
  52283. // Material is first to load this texture. Load and resolve texture.
  52284. texturePromises[envMap] = new Promise(function (resolve) {
  52285. utils.srcLoader.validateCubemapSrc(envMap, function loadEnvMap (urls) {
  52286. CubeLoader.load(urls, function (cube) {
  52287. // Texture loaded.
  52288. self.isLoadingEnvMap = false;
  52289. material.envMap = cube;
  52290. utils.material.handleTextureEvents(self.el, cube);
  52291. resolve(cube);
  52292. });
  52293. });
  52294. });
  52295. }
  52296. });
  52297. /**
  52298. * Builds and normalize material data, normalizing stuff along the way.
  52299. *
  52300. * @param {object} data - Material data.
  52301. * @returns {object} data - Processed material data.
  52302. */
  52303. function getMaterialData (data) {
  52304. var newData = {
  52305. color: new THREE.Color(data.color),
  52306. fog: data.fog,
  52307. metalness: data.metalness,
  52308. roughness: data.roughness,
  52309. wireframe: data.wireframe,
  52310. wireframeLinewidth: data.wireframeLinewidth
  52311. };
  52312. if (data.normalMap) { newData.normalScale = data.normalScale; }
  52313. if (data.ambientOcclusionMap) { newData.aoMapIntensity = data.ambientOcclusionMapIntensity; }
  52314. if (data.displacementMap) {
  52315. newData.displacementScale = data.displacementScale;
  52316. newData.displacementBias = data.displacementBias;
  52317. }
  52318. return newData;
  52319. }
  52320. },{"../core/shader":109,"../lib/three":146,"../utils/":167}],152:[function(_dereq_,module,exports){
  52321. var css = ".a-html{bottom:0;left:0;position:fixed;right:0;top:0}.a-body{height:100%;margin:0;overflow:hidden;padding:0;width:100%}:-webkit-full-screen{background-color:transparent}.a-hidden{display:none!important}.a-canvas{height:100%;left:0;position:absolute;top:0;width:100%}.a-canvas.a-grab-cursor:hover{cursor:grab;cursor:-moz-grabbing;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:174px}@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;height:10%;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;
  52322. },{"browserify-css":3}],153:[function(_dereq_,module,exports){
  52323. 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;
  52324. },{"browserify-css":3}],154:[function(_dereq_,module,exports){
  52325. var bind = _dereq_('../utils/bind');
  52326. var constants = _dereq_('../constants/');
  52327. var registerSystem = _dereq_('../core/system').registerSystem;
  52328. var DEFAULT_CAMERA_ATTR = 'data-aframe-default-camera';
  52329. /**
  52330. * Camera system. Manages which camera is active among multiple cameras in scene.
  52331. *
  52332. * @member {object} activeCameraEl - Active camera entity.
  52333. */
  52334. module.exports.System = registerSystem('camera', {
  52335. init: function () {
  52336. this.activeCameraEl = null;
  52337. // Wait for all entities to fully load before checking for existence of camera.
  52338. // Since entities wait for <a-assets> to load, any cameras attaching to the scene
  52339. // will do so asynchronously.
  52340. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultCamera, this));
  52341. },
  52342. /**
  52343. * Create a default camera if user has not added one during the initial scene traversal.
  52344. *
  52345. * Default camera offset height is at average eye level (~1.6m).
  52346. */
  52347. setupDefaultCamera: function () {
  52348. var sceneEl = this.sceneEl;
  52349. var defaultCameraEl;
  52350. // Camera already defined.
  52351. if (sceneEl.camera) {
  52352. sceneEl.emit('camera-ready', {cameraEl: sceneEl.camera.el});
  52353. return;
  52354. }
  52355. // Set up default camera.
  52356. defaultCameraEl = document.createElement('a-entity');
  52357. defaultCameraEl.setAttribute('position', '0 0 0');
  52358. defaultCameraEl.setAttribute(DEFAULT_CAMERA_ATTR, '');
  52359. defaultCameraEl.setAttribute('camera', {active: true, userHeight: constants.DEFAULT_CAMERA_HEIGHT});
  52360. defaultCameraEl.setAttribute('wasd-controls', '');
  52361. defaultCameraEl.setAttribute('look-controls', '');
  52362. defaultCameraEl.setAttribute(constants.AFRAME_INJECTED, '');
  52363. sceneEl.appendChild(defaultCameraEl);
  52364. sceneEl.addEventListener('enter-vr', this.removeDefaultOffset);
  52365. sceneEl.addEventListener('exit-vr', this.addDefaultOffset);
  52366. sceneEl.emit('camera-ready', {cameraEl: defaultCameraEl});
  52367. },
  52368. /**
  52369. * Set a different active camera.
  52370. * When we choose a (sort of) random scene camera as the replacement, set its `active` to
  52371. * true. The camera component will call `setActiveCamera` and handle passing the torch to
  52372. * the new camera.
  52373. */
  52374. disableActiveCamera: function () {
  52375. var cameraEls = this.sceneEl.querySelectorAll('[camera]');
  52376. var newActiveCameraEl = cameraEls[cameraEls.length - 1];
  52377. newActiveCameraEl.setAttribute('camera', 'active', true);
  52378. },
  52379. /**
  52380. * Set active camera to be used by renderer.
  52381. * Removes the default camera (if present).
  52382. * Disables all other cameras in the scene.
  52383. *
  52384. * @param {Element} newCameraEl - Entity with camera component.
  52385. */
  52386. setActiveCamera: function (newCameraEl) {
  52387. var cameraEl;
  52388. var cameraEls;
  52389. var i;
  52390. var newCamera;
  52391. var previousCamera = this.activeCameraEl;
  52392. var sceneEl = this.sceneEl;
  52393. // Same camera.
  52394. newCamera = newCameraEl.getObject3D('camera');
  52395. if (!newCamera || newCameraEl === this.activeCameraEl) { return; }
  52396. // Grab the default camera.
  52397. var defaultCameraWrapper = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  52398. var defaultCameraEl = defaultCameraWrapper &&
  52399. defaultCameraWrapper.querySelector('[camera]');
  52400. // Remove default camera if new camera is not the default camera.
  52401. if (newCameraEl !== defaultCameraEl) { removeDefaultCamera(sceneEl); }
  52402. // Make new camera active.
  52403. this.activeCameraEl = newCameraEl;
  52404. this.activeCameraEl.play();
  52405. sceneEl.camera = newCamera;
  52406. // Disable current camera
  52407. if (previousCamera) {
  52408. previousCamera.setAttribute('camera', 'active', false);
  52409. }
  52410. // Disable other cameras in the scene
  52411. cameraEls = sceneEl.querySelectorAll('[camera]');
  52412. for (i = 0; i < cameraEls.length; i++) {
  52413. cameraEl = cameraEls[i];
  52414. if (newCameraEl === cameraEl) { continue; }
  52415. cameraEl.setAttribute('camera', 'active', false);
  52416. cameraEl.pause();
  52417. }
  52418. sceneEl.emit('camera-set-active', {cameraEl: newCameraEl});
  52419. }
  52420. });
  52421. /**
  52422. * Remove injected default camera from scene, if present.
  52423. *
  52424. * @param {Element} sceneEl
  52425. */
  52426. function removeDefaultCamera (sceneEl) {
  52427. var defaultCamera;
  52428. var camera = sceneEl.camera;
  52429. if (!camera) { return; }
  52430. // Remove default camera if present.
  52431. defaultCamera = sceneEl.querySelector('[' + DEFAULT_CAMERA_ATTR + ']');
  52432. if (!defaultCamera) { return; }
  52433. sceneEl.removeChild(defaultCamera);
  52434. }
  52435. },{"../constants/":91,"../core/system":110,"../utils/bind":161}],155:[function(_dereq_,module,exports){
  52436. var geometries = _dereq_('../core/geometry').geometries;
  52437. var registerSystem = _dereq_('../core/system').registerSystem;
  52438. var THREE = _dereq_('../lib/three');
  52439. /**
  52440. * System for geometry component.
  52441. * Handle geometry caching.
  52442. *
  52443. * @member {object} cache - Mapping of stringified component data to THREE.Geometry objects.
  52444. * @member {object} cacheCount - Keep track of number of entities using a geometry to
  52445. * know whether to dispose on removal.
  52446. */
  52447. module.exports.System = registerSystem('geometry', {
  52448. init: function () {
  52449. this.cache = {};
  52450. this.cacheCount = {};
  52451. },
  52452. /**
  52453. * Reset cache. Mainly for testing.
  52454. */
  52455. clearCache: function () {
  52456. this.cache = {};
  52457. this.cacheCount = {};
  52458. },
  52459. /**
  52460. * Attempt to retrieve from cache.
  52461. *
  52462. * @returns {Object|null} A geometry if it exists, else null.
  52463. */
  52464. getOrCreateGeometry: function (data) {
  52465. var cache = this.cache;
  52466. var cachedGeometry;
  52467. var hash;
  52468. // Skip all caching logic.
  52469. if (data.skipCache || data.mergeTo) { return createGeometry(data); }
  52470. // Try to retrieve from cache first.
  52471. hash = this.hash(data);
  52472. cachedGeometry = cache[hash];
  52473. incrementCacheCount(this.cacheCount, hash);
  52474. if (cachedGeometry) { return cachedGeometry; }
  52475. // Create geometry.
  52476. cachedGeometry = createGeometry(data);
  52477. // Cache and return geometry.
  52478. cache[hash] = cachedGeometry;
  52479. return cachedGeometry;
  52480. },
  52481. /**
  52482. * Let system know that an entity is no longer using a geometry.
  52483. */
  52484. unuseGeometry: function (data) {
  52485. var cache = this.cache;
  52486. var cacheCount = this.cacheCount;
  52487. var geometry;
  52488. var hash;
  52489. if (data.skipCache || data.mergeTo) { return; }
  52490. hash = this.hash(data);
  52491. if (!cache[hash]) { return; }
  52492. decrementCacheCount(cacheCount, hash);
  52493. // Another entity is still using this geometry. No need to do anything.
  52494. if (cacheCount[hash] > 0) { return; }
  52495. // No more entities are using this geometry. Dispose.
  52496. geometry = cache[hash];
  52497. geometry.dispose();
  52498. delete cache[hash];
  52499. delete cacheCount[hash];
  52500. },
  52501. /**
  52502. * Use JSON.stringify to turn component data into hash.
  52503. * Should be deterministic within a single browser engine.
  52504. * If not, then look into json-stable-stringify.
  52505. */
  52506. hash: function (data) {
  52507. return JSON.stringify(data);
  52508. }
  52509. });
  52510. /**
  52511. * Create geometry using component data.
  52512. *
  52513. * @param {object} data - Component data.
  52514. * @returns {object} Geometry.
  52515. */
  52516. function createGeometry (data) {
  52517. var geometryType = data.primitive;
  52518. var GeometryClass = geometries[geometryType] && geometries[geometryType].Geometry;
  52519. var geometryInstance = new GeometryClass();
  52520. if (!GeometryClass) { throw new Error('Unknown geometry `' + geometryType + '`'); }
  52521. geometryInstance.init(data);
  52522. return toBufferGeometry(geometryInstance.geometry, data.buffer);
  52523. }
  52524. /**
  52525. * Decreate count of entity using a geometry.
  52526. */
  52527. function decrementCacheCount (cacheCount, hash) {
  52528. cacheCount[hash]--;
  52529. }
  52530. /**
  52531. * Increase count of entity using a geometry.
  52532. */
  52533. function incrementCacheCount (cacheCount, hash) {
  52534. cacheCount[hash] = cacheCount[hash] === undefined ? 1 : cacheCount[hash] + 1;
  52535. }
  52536. /**
  52537. * Transform geometry to BufferGeometry if `doBuffer`.
  52538. *
  52539. * @param {object} geometry
  52540. * @param {boolean} doBuffer
  52541. * @returns {object} Geometry.
  52542. */
  52543. function toBufferGeometry (geometry, doBuffer) {
  52544. var bufferGeometry;
  52545. if (!doBuffer) { return geometry; }
  52546. bufferGeometry = new THREE.BufferGeometry().fromGeometry(geometry);
  52547. bufferGeometry.metadata = {type: geometry.type, parameters: geometry.parameters || {}};
  52548. geometry.dispose(); // Dispose no longer needed non-buffer geometry.
  52549. return bufferGeometry;
  52550. }
  52551. },{"../core/geometry":101,"../core/system":110,"../lib/three":146}],156:[function(_dereq_,module,exports){
  52552. var registerSystem = _dereq_('../core/system').registerSystem;
  52553. var THREE = _dereq_('../lib/three');
  52554. /**
  52555. * glTF model system.
  52556. */
  52557. module.exports.System = registerSystem('gltf-model', {
  52558. init: function () {
  52559. this.models = [];
  52560. },
  52561. /**
  52562. * Updates shaders for all glTF models in the system.
  52563. */
  52564. tick: function () {
  52565. var sceneEl = this.sceneEl;
  52566. if (sceneEl.hasLoaded && this.models.length) {
  52567. THREE.GLTFLoader.Shaders.update(sceneEl.object3D, sceneEl.camera);
  52568. }
  52569. },
  52570. /**
  52571. * Registers a glTF asset.
  52572. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  52573. */
  52574. registerModel: function (gltf) {
  52575. this.models.push(gltf);
  52576. },
  52577. /**
  52578. * Unregisters a glTF asset.
  52579. * @param {object} gltf Asset containing a scene and (optional) animations and cameras.
  52580. */
  52581. unregisterModel: function (gltf) {
  52582. var models = this.models;
  52583. var index = models.indexOf(gltf);
  52584. if (index >= 0) {
  52585. models.splice(index, 1);
  52586. }
  52587. }
  52588. });
  52589. },{"../core/system":110,"../lib/three":146}],157:[function(_dereq_,module,exports){
  52590. _dereq_('./camera');
  52591. _dereq_('./geometry');
  52592. _dereq_('./gltf-model');
  52593. _dereq_('./light');
  52594. _dereq_('./material');
  52595. _dereq_('./tracked-controls');
  52596. },{"./camera":154,"./geometry":155,"./gltf-model":156,"./light":158,"./material":159,"./tracked-controls":160}],158:[function(_dereq_,module,exports){
  52597. var registerSystem = _dereq_('../core/system').registerSystem;
  52598. var bind = _dereq_('../utils/bind');
  52599. var constants = _dereq_('../constants/');
  52600. var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';
  52601. /**
  52602. * Light system.
  52603. *
  52604. * Prescribes default lighting if not specified (one ambient, one directional).
  52605. * Removes default lighting from the scene when a new light is added.
  52606. *
  52607. * @param {bool} defaultLights - Whether default lighting are defined.
  52608. * @param {bool} userDefinedLights - Whether user lighting is defined.
  52609. */
  52610. module.exports.System = registerSystem('light', {
  52611. init: function () {
  52612. this.defaultLights = false;
  52613. this.userDefinedLights = false;
  52614. // Wait for all entities to fully load before checking for existence of lights.
  52615. // Since entities wait for <a-assets> to load, any lights attaching to the scene
  52616. // will do so asynchronously.
  52617. this.sceneEl.addEventListener('loaded', bind(this.setupDefaultLights, this));
  52618. },
  52619. /**
  52620. * Notify scene that light has been added and to remove the default.
  52621. *
  52622. * @param {object} el - element holding the light component.
  52623. */
  52624. registerLight: function (el) {
  52625. if (!el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
  52626. // User added a light, remove default lights through DOM.
  52627. this.removeDefaultLights();
  52628. this.userDefinedLights = true;
  52629. }
  52630. },
  52631. removeDefaultLights: function () {
  52632. var defaultLights;
  52633. var sceneEl = this.sceneEl;
  52634. if (!this.defaultLights) { return; }
  52635. defaultLights = document.querySelectorAll('[' + DEFAULT_LIGHT_ATTR + ']');
  52636. for (var i = 0; i < defaultLights.length; i++) {
  52637. sceneEl.removeChild(defaultLights[i]);
  52638. }
  52639. this.defaultLights = false;
  52640. },
  52641. /**
  52642. * Prescibe default lights to the scene.
  52643. * Does so by injecting markup such that this state is not invisible.
  52644. * These lights are removed if the user adds any lights.
  52645. */
  52646. setupDefaultLights: function () {
  52647. var sceneEl = this.sceneEl;
  52648. var ambientLight;
  52649. var directionalLight;
  52650. if (this.userDefinedLights || this.defaultLights) { return; }
  52651. ambientLight = document.createElement('a-entity');
  52652. directionalLight = document.createElement('a-entity');
  52653. ambientLight.setAttribute('light', {color: '#BBB', type: 'ambient'});
  52654. ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  52655. ambientLight.setAttribute(constants.AFRAME_INJECTED, '');
  52656. sceneEl.appendChild(ambientLight);
  52657. directionalLight.setAttribute('light', {color: '#FFF', intensity: 0.6});
  52658. directionalLight.setAttribute('position', {x: -0.5, y: 1, z: 1});
  52659. directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
  52660. directionalLight.setAttribute(constants.AFRAME_INJECTED, '');
  52661. sceneEl.appendChild(directionalLight);
  52662. this.defaultLights = true;
  52663. }
  52664. });
  52665. },{"../constants/":91,"../core/system":110,"../utils/bind":161}],159:[function(_dereq_,module,exports){
  52666. var registerSystem = _dereq_('../core/system').registerSystem;
  52667. var THREE = _dereq_('../lib/three');
  52668. var utils = _dereq_('../utils/');
  52669. var debug = utils.debug;
  52670. var error = debug('components:texture:error');
  52671. var TextureLoader = new THREE.TextureLoader();
  52672. var warn = debug('components:texture:warn');
  52673. /**
  52674. * System for material component.
  52675. * Handle material registration, updates (for fog), and texture caching.
  52676. *
  52677. * @member materials {object} - Registered materials.
  52678. * @member textureCache {object} - Texture cache for:
  52679. * - Images: textureCache has mapping of src -> repeat -> cached three.js texture.
  52680. * - Videos: textureCache has mapping of videoElement -> cached three.js texture.
  52681. */
  52682. module.exports.System = registerSystem('material', {
  52683. init: function () {
  52684. this.materials = {};
  52685. this.textureCache = {};
  52686. },
  52687. clearTextureCache: function () {
  52688. this.textureCache = {};
  52689. },
  52690. /**
  52691. * Determine whether `src` is a image or video. Then try to load the asset, then call back.
  52692. *
  52693. * @param {string, or element} src - Texture URL or element.
  52694. * @param {string} data - Relevant texture data used for caching.
  52695. * @param {function} cb - Callback to pass texture to.
  52696. */
  52697. loadTexture: function (src, data, cb) {
  52698. var self = this;
  52699. // Canvas.
  52700. if (src.tagName === 'CANVAS') {
  52701. this.loadCanvas(src, data, cb);
  52702. return;
  52703. }
  52704. // Video element.
  52705. if (src.tagName === 'VIDEO') {
  52706. if (!src.hasAttribute('src') && !src.hasAttribute('srcObject')) {
  52707. warn('Video element was defined without `src` nor `srcObject` attributes.');
  52708. }
  52709. this.loadVideo(src, data, cb);
  52710. return;
  52711. }
  52712. utils.srcLoader.validateSrc(src, loadImageCb, loadVideoCb);
  52713. function loadImageCb (src) { self.loadImage(src, data, cb); }
  52714. function loadVideoCb (src) { self.loadVideo(src, data, cb); }
  52715. },
  52716. /**
  52717. * High-level function for loading image textures (THREE.Texture).
  52718. *
  52719. * @param {Element|string} src - Texture source.
  52720. * @param {object} data - Texture data.
  52721. * @param {function} cb - Callback to pass texture to.
  52722. */
  52723. loadImage: function (src, data, cb) {
  52724. var hash = this.hash(data);
  52725. var handleImageTextureLoaded = cb;
  52726. var textureCache = this.textureCache;
  52727. // Texture already being loaded or already loaded. Wait on promise.
  52728. if (textureCache[hash]) {
  52729. textureCache[hash].then(handleImageTextureLoaded);
  52730. return;
  52731. }
  52732. // Texture not yet being loaded. Start loading it.
  52733. textureCache[hash] = loadImageTexture(src, data);
  52734. textureCache[hash].then(handleImageTextureLoaded);
  52735. },
  52736. /**
  52737. * High-level function for loading canvas textures (THREE.Texture).
  52738. *
  52739. * @param {Element|string} src - Texture source.
  52740. * @param {object} data - Texture data.
  52741. * @param {function} cb - Callback to pass texture to.
  52742. */
  52743. loadCanvas: function (src, data, cb) {
  52744. // Hack readyState and HAVE_CURRENT_DATA on canvas to work with THREE.VideoTexture
  52745. src.readyState = 2;
  52746. src.HAVE_CURRENT_DATA = 2;
  52747. this.loadVideo(src, data, cb);
  52748. },
  52749. /**
  52750. * Load video texture (THREE.VideoTexture).
  52751. * Which is just an image texture that RAFs + needsUpdate.
  52752. * Note that creating a video texture is synchronous unlike loading an image texture.
  52753. * Made asynchronous to be consistent with image textures.
  52754. *
  52755. * @param {Element|string} src - Texture source.
  52756. * @param {object} data - Texture data.
  52757. * @param {function} cb - Callback to pass texture to.
  52758. */
  52759. loadVideo: function (src, data, cb) {
  52760. var hash;
  52761. var texture;
  52762. var textureCache = this.textureCache;
  52763. var videoEl;
  52764. var videoTextureResult;
  52765. function handleVideoTextureLoaded (result) {
  52766. result.texture.needsUpdate = true;
  52767. cb(result.texture, result.videoEl);
  52768. }
  52769. // Video element provided.
  52770. if (typeof src !== 'string') {
  52771. // Check cache before creating texture.
  52772. videoEl = src;
  52773. hash = this.hashVideo(data, videoEl);
  52774. if (textureCache[hash]) {
  52775. textureCache[hash].then(handleVideoTextureLoaded);
  52776. return;
  52777. }
  52778. // If not in cache, fix up the attributes then start to create the texture.
  52779. fixVideoAttributes(videoEl);
  52780. }
  52781. // Only URL provided. Use video element to create texture.
  52782. videoEl = videoEl || createVideoEl(src, data.width, data.height);
  52783. // Generated video element already cached. Use that.
  52784. hash = this.hashVideo(data, videoEl);
  52785. if (textureCache[hash]) {
  52786. textureCache[hash].then(handleVideoTextureLoaded);
  52787. return;
  52788. }
  52789. // Create new video texture.
  52790. texture = new THREE.VideoTexture(videoEl);
  52791. texture.minFilter = THREE.LinearFilter;
  52792. setTextureProperties(texture, data);
  52793. // Cache as promise to be consistent with image texture caching.
  52794. videoTextureResult = {texture: texture, videoEl: videoEl};
  52795. textureCache[hash] = Promise.resolve(videoTextureResult);
  52796. handleVideoTextureLoaded(videoTextureResult);
  52797. },
  52798. hash: function (data) {
  52799. return JSON.stringify(data);
  52800. },
  52801. hashVideo: function (data, videoEl) {
  52802. return calculateVideoCacheHash(data, videoEl);
  52803. },
  52804. /**
  52805. * Keep track of material in case an update trigger is needed (e.g., fog).
  52806. *
  52807. * @param {object} material
  52808. */
  52809. registerMaterial: function (material) {
  52810. this.materials[material.uuid] = material;
  52811. },
  52812. /**
  52813. * Stop tracking material.
  52814. *
  52815. * @param {object} material
  52816. */
  52817. unregisterMaterial: function (material) {
  52818. delete this.materials[material.uuid];
  52819. },
  52820. /**
  52821. * Trigger update to all registered materials.
  52822. */
  52823. updateMaterials: function (material) {
  52824. var materials = this.materials;
  52825. Object.keys(materials).forEach(function (uuid) {
  52826. materials[uuid].needsUpdate = true;
  52827. });
  52828. }
  52829. });
  52830. /**
  52831. * Calculates consistent hash from a video element using its attributes.
  52832. * If the video element has an ID, use that.
  52833. * Else build a hash that looks like `src:myvideo.mp4;height:200;width:400;`.
  52834. *
  52835. * @param data {object} - Texture data such as repeat.
  52836. * @param videoEl {Element} - Video element.
  52837. * @returns {string}
  52838. */
  52839. function calculateVideoCacheHash (data, videoEl) {
  52840. var i;
  52841. var id = videoEl.getAttribute('id');
  52842. var hash;
  52843. var videoAttributes;
  52844. if (id) { return id; }
  52845. // Calculate hash using sorted video attributes.
  52846. hash = '';
  52847. videoAttributes = data || {};
  52848. for (i = 0; i < videoEl.attributes.length; i++) {
  52849. videoAttributes[videoEl.attributes[i].name] = videoEl.attributes[i].value;
  52850. }
  52851. Object.keys(videoAttributes).sort().forEach(function (name) {
  52852. hash += name + ':' + videoAttributes[name] + ';';
  52853. });
  52854. return hash;
  52855. }
  52856. /**
  52857. * Load image texture.
  52858. *
  52859. * @private
  52860. * @param {string|object} src - An <img> element or url to an image file.
  52861. * @param {object} data - Data to set texture properties like `repeat`.
  52862. * @returns {Promise} Resolves once texture is loaded.
  52863. */
  52864. function loadImageTexture (src, data) {
  52865. return new Promise(doLoadImageTexture);
  52866. function doLoadImageTexture (resolve, reject) {
  52867. var isEl = typeof src !== 'string';
  52868. function resolveTexture (texture) {
  52869. setTextureProperties(texture, data);
  52870. texture.needsUpdate = true;
  52871. resolve(texture);
  52872. }
  52873. // Create texture from an element.
  52874. if (isEl) {
  52875. resolveTexture(new THREE.Texture(src));
  52876. return;
  52877. }
  52878. // Load texture from src string. THREE will create underlying element.
  52879. // Use THREE.TextureLoader (src, onLoad, onProgress, onError) to load texture.
  52880. TextureLoader.load(
  52881. src,
  52882. resolveTexture,
  52883. function () { /* no-op */ },
  52884. function (xhr) {
  52885. error('`$s` could not be fetched (Error code: %s; Response: %s)', xhr.status,
  52886. xhr.statusText);
  52887. }
  52888. );
  52889. }
  52890. }
  52891. /**
  52892. * Set texture properties such as repeat and offset.
  52893. *
  52894. * @param {object} data - With keys like `repeat`.
  52895. */
  52896. function setTextureProperties (texture, data) {
  52897. var offset = data.offset || {x: 0, y: 0};
  52898. var repeat = data.repeat || {x: 1, y: 1};
  52899. var npot = data.npot || false;
  52900. // To support NPOT textures, wrap must be ClampToEdge (not Repeat),
  52901. // and filters must not use mipmaps (i.e. Nearest or Linear).
  52902. if (npot) {
  52903. texture.wrapS = THREE.ClampToEdgeWrapping;
  52904. texture.wrapT = THREE.ClampToEdgeWrapping;
  52905. texture.magFilter = THREE.LinearFilter;
  52906. texture.minFilter = THREE.LinearFilter;
  52907. }
  52908. // Don't bother setting repeat if it is 1/1. Power-of-two is required to repeat.
  52909. if (repeat.x !== 1 || repeat.y !== 1) {
  52910. texture.wrapS = THREE.RepeatWrapping;
  52911. texture.wrapT = THREE.RepeatWrapping;
  52912. texture.repeat.set(repeat.x, repeat.y);
  52913. }
  52914. // Don't bother setting offset if it is 0/0.
  52915. if (offset.x !== 0 || offset.y !== 0) {
  52916. texture.offset.set(offset.x, offset.y);
  52917. }
  52918. }
  52919. /**
  52920. * Create video element to be used as a texture.
  52921. *
  52922. * @param {string} src - Url to a video file.
  52923. * @param {number} width - Width of the video.
  52924. * @param {number} height - Height of the video.
  52925. * @returns {Element} Video element.
  52926. */
  52927. function createVideoEl (src, width, height) {
  52928. var videoEl = document.createElement('video');
  52929. videoEl.width = width;
  52930. videoEl.height = height;
  52931. videoEl.setAttribute('webkit-playsinline', ''); // Support inline videos for iOS webviews.
  52932. videoEl.autoplay = true;
  52933. videoEl.loop = true;
  52934. videoEl.crossOrigin = 'anonymous';
  52935. videoEl.addEventListener('error', function () {
  52936. warn('`$s` is not a valid video', src);
  52937. }, true);
  52938. videoEl.src = src;
  52939. return videoEl;
  52940. }
  52941. /**
  52942. * Fixes a video element's attributes to prevent developers from accidentally passing the
  52943. * wrong attribute values to commonly misused video attributes.
  52944. *
  52945. * <video> does not treat `autoplay`, `controls`, `crossorigin`, `loop`, and `preload` as
  52946. * as booleans. Existence of those attributes will mean truthy.
  52947. *
  52948. * For example, translates <video loop="false"> to <video>.
  52949. *
  52950. * @see https://developer.mozilla.org/docs/Web/HTML/Element/video#Attributes
  52951. * @param {Element} videoEl - Video element.
  52952. * @returns {Element} Video element with the correct properties updated.
  52953. */
  52954. function fixVideoAttributes (videoEl) {
  52955. videoEl.autoplay = videoEl.getAttribute('autoplay') !== 'false';
  52956. videoEl.controls = videoEl.getAttribute('controls') !== 'false';
  52957. if (videoEl.getAttribute('loop') === 'false') {
  52958. videoEl.removeAttribute('loop');
  52959. }
  52960. if (videoEl.getAttribute('preload') === 'false') {
  52961. videoEl.preload = 'none';
  52962. }
  52963. videoEl.crossOrigin = videoEl.crossOrigin || 'anonymous';
  52964. // To support inline videos in iOS webviews.
  52965. videoEl.setAttribute('webkit-playsinline', '');
  52966. return videoEl;
  52967. }
  52968. },{"../core/system":110,"../lib/three":146,"../utils/":167}],160:[function(_dereq_,module,exports){
  52969. var registerSystem = _dereq_('../core/system').registerSystem;
  52970. var trackedControlsUtils = _dereq_('../utils/tracked-controls');
  52971. var utils = _dereq_('../utils');
  52972. /**
  52973. * Tracked controls system.
  52974. * It maintains a list with the available tracked controllers
  52975. */
  52976. module.exports.System = registerSystem('tracked-controls', {
  52977. init: function () {
  52978. var self = this;
  52979. this.controllers = [];
  52980. this.lastControllersUpdate = 0;
  52981. // Throttle the (renamed) tick handler to minimum 10ms interval.
  52982. this.tick = utils.throttle(this.throttledTick, 10, this);
  52983. if (!navigator.getVRDisplays) { return; }
  52984. navigator.getVRDisplays().then(function (displays) {
  52985. if (displays.length > 0) {
  52986. self.vrDisplay = displays[0];
  52987. }
  52988. });
  52989. },
  52990. updateControllerList: function () {
  52991. var controllers = this.controllers = [];
  52992. var gamepads = trackedControlsUtils.getGamepadsByPrefix('');
  52993. for (var i = 0; i < gamepads.length; i++) {
  52994. var gamepad = gamepads[i];
  52995. if (gamepad && gamepad.pose) { controllers.push(gamepad); }
  52996. }
  52997. },
  52998. /**
  52999. * Update controller list every 10 millseconds.
  53000. */
  53001. throttledTick: function () {
  53002. this.updateControllerList();
  53003. this.sceneEl.emit('controllersupdated', { controllers: this.controllers });
  53004. }
  53005. });
  53006. },{"../core/system":110,"../utils":167,"../utils/tracked-controls":171}],161:[function(_dereq_,module,exports){
  53007. /**
  53008. * Faster version of Function.prototype.bind
  53009. * @param {Function} fn - Function to wrap.
  53010. * @param {Object} ctx - What to bind as context.
  53011. * @param {...*} arguments - Arguments to pass through.
  53012. */
  53013. module.exports = function bind (fn, ctx/* , arg1, arg2 */) {
  53014. return (function (prependedArgs) {
  53015. return function bound () {
  53016. // Concat the bound function arguments with those passed to original bind
  53017. var args = prependedArgs.concat(Array.prototype.slice.call(arguments, 0));
  53018. return fn.apply(ctx, args);
  53019. };
  53020. })(Array.prototype.slice.call(arguments, 2));
  53021. };
  53022. },{}],162:[function(_dereq_,module,exports){
  53023. /* global THREE */
  53024. var extend = _dereq_('object-assign');
  53025. // Coordinate string regex. Handles negative, positive, and decimals.
  53026. var regex = /^\s*((-?\d*\.{0,1}\d+)\s+){2,3}(-?\d*\.{0,1}\d+)\s*$/;
  53027. module.exports.regex = regex;
  53028. /**
  53029. * Parses coordinates from an "x y z" string.
  53030. * Example: "3 10 -5" to {x: 3, y: 10, z: -5}.
  53031. *
  53032. * @param {string} val - An "x y z" string.
  53033. * @param {string} defaults - fallback value.
  53034. * @returns {object} An object with keys [x, y, z].
  53035. */
  53036. function parse (value, defaultVec) {
  53037. var coordinate;
  53038. var vec = {};
  53039. if (value && typeof value === 'object') {
  53040. return vecParseFloat({
  53041. x: value.x !== undefined ? value.x : (defaultVec && defaultVec.x),
  53042. y: value.y !== undefined ? value.y : (defaultVec && defaultVec.y),
  53043. z: value.z !== undefined ? value.z : (defaultVec && defaultVec.z),
  53044. w: value.w !== undefined ? value.w : (defaultVec && defaultVec.w)
  53045. });
  53046. }
  53047. if (typeof value !== 'string' || value === null) {
  53048. return typeof defaultVec === 'object' ? extend({}, defaultVec) : defaultVec;
  53049. }
  53050. coordinate = value.trim().replace(/\s+/g, ' ').split(' ');
  53051. vec.x = coordinate[0] || defaultVec && defaultVec.x;
  53052. vec.y = coordinate[1] || defaultVec && defaultVec.y;
  53053. vec.z = coordinate[2] || defaultVec && defaultVec.z;
  53054. vec.w = coordinate[3] || defaultVec && defaultVec.w;
  53055. return vecParseFloat(vec);
  53056. }
  53057. module.exports.parse = parse;
  53058. /**
  53059. * Stringifies coordinates from an object with keys [x y z].
  53060. * Example: {x: 3, y: 10, z: -5} to "3 10 -5".
  53061. *
  53062. * @param {object|string} data - An object with keys [x y z].
  53063. * @returns {string} An "x y z" string.
  53064. */
  53065. function stringify (data) {
  53066. if (typeof data !== 'object') { return data; }
  53067. return [data.x, data.y, data.z, data.w].join(' ').trim();
  53068. }
  53069. module.exports.stringify = stringify;
  53070. /**
  53071. * @returns {bool}
  53072. */
  53073. module.exports.isCoordinate = function (value) {
  53074. return regex.test(value);
  53075. };
  53076. function vecParseFloat (vec) {
  53077. Object.keys(vec).forEach(function (key) {
  53078. if (vec[key] === undefined) {
  53079. delete vec[key];
  53080. return;
  53081. }
  53082. vec[key] = parseFloat(vec[key], 10);
  53083. });
  53084. return vec;
  53085. }
  53086. /**
  53087. * Converts {x, y, z} object to three.js Vector3.
  53088. */
  53089. module.exports.toVector3 = function (vec3) {
  53090. return new THREE.Vector3(vec3.x, vec3.y, vec3.z);
  53091. };
  53092. },{"object-assign":28}],163:[function(_dereq_,module,exports){
  53093. (function (process){
  53094. var debugLib = _dereq_('debug');
  53095. var extend = _dereq_('object-assign');
  53096. var settings = {
  53097. colors: {
  53098. debug: 'gray',
  53099. error: 'red',
  53100. info: 'gray',
  53101. warn: 'orange'
  53102. }
  53103. };
  53104. /**
  53105. * Monkeypatches `debug` so we can colorize error/warning messages.
  53106. *
  53107. * (See issue: https://github.com/visionmedia/debug/issues/137)
  53108. */
  53109. var debug = function (namespace) {
  53110. var d = debugLib(namespace);
  53111. d.color = getDebugNamespaceColor(namespace);
  53112. return d;
  53113. };
  53114. extend(debug, debugLib);
  53115. /**
  53116. * Returns the type of the namespace (e.g., `error`, `warn`).
  53117. *
  53118. * @param {String} namespace
  53119. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53120. * @returns {String} The type of the namespace (e.g., `warn`).
  53121. * @api private
  53122. */
  53123. function getDebugNamespaceType (namespace) {
  53124. var chunks = namespace.split(':');
  53125. return chunks[chunks.length - 1]; // Return the last one
  53126. }
  53127. /**
  53128. * Returns the color of the namespace (e.g., `orange`).
  53129. *
  53130. * @param {String} namespace
  53131. * The debug logger's namespace (e.g., `components:geometry:warn`).
  53132. * @returns {String} The color of the namespace (e.g., `orange`).
  53133. * @api private
  53134. */
  53135. function getDebugNamespaceColor (namespace) {
  53136. var type = getDebugNamespaceType(namespace);
  53137. var color = settings.colors && settings.colors[type];
  53138. return color || null;
  53139. }
  53140. /**
  53141. * Returns `localStorage` if possible.
  53142. *
  53143. * This is necessary because Safari throws when a user disables
  53144. * cookies or `localStorage` and you attempt to access it.
  53145. *
  53146. * @returns {localStorage}
  53147. * @api private
  53148. */
  53149. function storage () {
  53150. try {
  53151. return window.localStorage;
  53152. } catch (e) {
  53153. }
  53154. }
  53155. /**
  53156. * To enable console logging, type this in the Console of your Dev Tools:
  53157. *
  53158. * localStorage.logs = 1
  53159. *
  53160. * To disable console logging:
  53161. *
  53162. * localStorage.logs = 0
  53163. *
  53164. */
  53165. var ls = storage();
  53166. if (ls && (parseInt(ls.logs, 10) || ls.logs === 'true')) {
  53167. debug.enable('*');
  53168. } else {
  53169. debug.enable('*:error,*:info,*:warn');
  53170. }
  53171. if (process.browser) { window.logs = debug; }
  53172. module.exports = debug;
  53173. }).call(this,_dereq_('_process'))
  53174. },{"_process":9,"debug":11,"object-assign":28}],164:[function(_dereq_,module,exports){
  53175. var THREE = _dereq_('../lib/three');
  53176. var dolly = new THREE.Object3D();
  53177. var controls = new THREE.VRControls(dolly);
  53178. /**
  53179. * Determine if a headset is connected by checking if the
  53180. * orientation is available
  53181. */
  53182. function checkHeadsetConnected () {
  53183. var orientation;
  53184. controls.update();
  53185. orientation = dolly.quaternion;
  53186. if (orientation._x !== 0 || orientation._y !== 0 || orientation._z !== 0) {
  53187. return true;
  53188. }
  53189. return false;
  53190. }
  53191. module.exports.checkHeadsetConnected = checkHeadsetConnected;
  53192. /**
  53193. * Check for positional tracking.
  53194. */
  53195. function checkHasPositionalTracking () {
  53196. var position = new THREE.Vector3();
  53197. return (function () {
  53198. if (isMobile() || isGearVR()) { return false; }
  53199. controls.update();
  53200. dolly.updateMatrix();
  53201. position.setFromMatrixPosition(dolly.matrix);
  53202. if (position.x !== 0 || position.y !== 0 || position.z !== 0) {
  53203. return true;
  53204. }
  53205. return false;
  53206. })();
  53207. }
  53208. module.exports.checkHasPositionalTracking = checkHasPositionalTracking;
  53209. /**
  53210. * Checks if browser is mobile.
  53211. * @return {Boolean} True if mobile browser detected.
  53212. */
  53213. var isMobile = (function () {
  53214. var _isMobile = false;
  53215. (function (a) {
  53216. // eslint-disable-next-line no-useless-escape
  53217. 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))) {
  53218. _isMobile = true;
  53219. }
  53220. if (isIOS()) {
  53221. _isMobile = true;
  53222. }
  53223. if (isGearVR()) {
  53224. _isMobile = false;
  53225. }
  53226. })(navigator.userAgent || navigator.vendor || window.opera);
  53227. return function () { return _isMobile; };
  53228. })();
  53229. module.exports.isMobile = isMobile;
  53230. function isIOS () {
  53231. return /iPad|iPhone|iPod/.test(navigator.platform);
  53232. }
  53233. module.exports.isIOS = isIOS;
  53234. function isGearVR () {
  53235. return /SamsungBrowser.+Mobile VR/i.test(navigator.userAgent);
  53236. }
  53237. module.exports.isGearVR = isGearVR;
  53238. /**
  53239. * Checks mobile device orientation.
  53240. * @return {Boolean} True if landscape orientation.
  53241. */
  53242. module.exports.isLandscape = function () {
  53243. return window.orientation === 90 || window.orientation === -90;
  53244. };
  53245. /**
  53246. * Check if device is iOS and older than version 10.
  53247. */
  53248. module.exports.isIOSOlderThan10 = function (userAgent) {
  53249. return /(iphone|ipod|ipad).*os.(7|8|9)/i.test(userAgent);
  53250. };
  53251. },{"../lib/three":146}],165:[function(_dereq_,module,exports){
  53252. /**
  53253. * Split a delimited component property string (e.g., `material.color`) to an object
  53254. * containing `component` name and `property` name. If there is no delimiter, just return the
  53255. * string back.
  53256. */
  53257. module.exports.getComponentPropertyPath = function (str, delimiter) {
  53258. delimiter = delimiter || '.';
  53259. if (str.indexOf(delimiter) === -1) { return str; }
  53260. return str.split(delimiter);
  53261. };
  53262. /**
  53263. * Get component property using encoded component name + component property name with a
  53264. * delimiter.
  53265. */
  53266. module.exports.getComponentProperty = function (el, name, delimiter) {
  53267. var splitName;
  53268. delimiter = delimiter || '.';
  53269. if (name.indexOf(delimiter) !== -1) {
  53270. splitName = name.split(delimiter);
  53271. return el.getAttribute(splitName[0])[splitName[1]];
  53272. }
  53273. return el.getAttribute(name);
  53274. };
  53275. /**
  53276. * Set component property using encoded component name + component property name with a
  53277. * delimiter.
  53278. */
  53279. module.exports.setComponentProperty = function (el, name, value, delimiter) {
  53280. var splitName;
  53281. delimiter = delimiter || '.';
  53282. if (name.indexOf(delimiter) !== -1) {
  53283. splitName = name.split(delimiter);
  53284. el.setAttribute(splitName[0], splitName[1], value);
  53285. return;
  53286. }
  53287. el.setAttribute(name, value);
  53288. };
  53289. },{}],166:[function(_dereq_,module,exports){
  53290. module.exports = function forceCanvasResizeSafariMobile (canvasEl) {
  53291. var width = canvasEl.style.width;
  53292. var height = canvasEl.style.height;
  53293. // Taken from webvr-polyfill (https://github.com/borismus/webvr-polyfill/blob/85f657cd502ec9417bf26b87c3cb2afa6a70e079/src/util.js#L200)
  53294. // iOS only workaround for https://bugs.webkit.org/show_bug.cgi?id=152556
  53295. // By changing the size 1 pixel and restoring the previous value
  53296. // we trigger a size recalculation cycle.
  53297. canvasEl.style.width = (parseInt(width, 10) + 1) + 'px';
  53298. canvasEl.style.height = (parseInt(height, 10) + 1) + 'px';
  53299. setTimeout(function () {
  53300. canvasEl.style.width = width;
  53301. canvasEl.style.height = height;
  53302. }, 200);
  53303. };
  53304. },{}],167:[function(_dereq_,module,exports){
  53305. /* global CustomEvent, location */
  53306. /* Centralized place to reference utilities since utils is exposed to the user. */
  53307. var debug = _dereq_('./debug');
  53308. var deepAssign = _dereq_('deep-assign');
  53309. var device = _dereq_('./device');
  53310. var objectAssign = _dereq_('object-assign');
  53311. var warn = debug('utils:warn');
  53312. module.exports.bind = _dereq_('./bind');
  53313. module.exports.coordinates = _dereq_('./coordinates');
  53314. module.exports.debug = debug;
  53315. module.exports.device = device;
  53316. module.exports.entity = _dereq_('./entity');
  53317. module.exports.forceCanvasResizeSafariMobile = _dereq_('./forceCanvasResizeSafariMobile');
  53318. module.exports.material = _dereq_('./material');
  53319. module.exports.styleParser = _dereq_('./styleParser');
  53320. module.exports.trackedControls = _dereq_('./tracked-controls');
  53321. module.exports.checkHeadsetConnected = function () {
  53322. warn('`utils.checkHeadsetConnected` has moved to `utils.device.checkHeadsetConnected`');
  53323. return device.checkHeadsetConnected(arguments);
  53324. };
  53325. module.exports.isGearVR = function () {
  53326. warn('`utils.isGearVR` has moved to `utils.device.isGearVR`');
  53327. return device.isGearVR(arguments);
  53328. };
  53329. module.exports.isIOS = function () {
  53330. warn('`utils.isIOS` has moved to `utils.device.isIOS`');
  53331. return device.isIOS(arguments);
  53332. };
  53333. module.exports.isMobile = function () {
  53334. warn('`utils.isMobile has moved to `utils.device.isMobile`');
  53335. return device.isMobile(arguments);
  53336. };
  53337. /**
  53338. * Returns throttle function that gets called at most once every interval.
  53339. *
  53340. * @param {function} functionToThrottle
  53341. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  53342. * @param {object} optionalContext - If given, bind function to throttle to this context.
  53343. * @returns {function} Throttled function.
  53344. */
  53345. module.exports.throttle = function (functionToThrottle, minimumInterval, optionalContext) {
  53346. var lastTime;
  53347. if (optionalContext) {
  53348. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  53349. }
  53350. return function () {
  53351. var time = Date.now();
  53352. var sinceLastTime = typeof lastTime === 'undefined' ? minimumInterval : time - lastTime;
  53353. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  53354. lastTime = time;
  53355. functionToThrottle.apply(null, arguments);
  53356. }
  53357. };
  53358. };
  53359. /**
  53360. * Returns throttle function that gets called at most once every interval.
  53361. * Uses the time/timeDelta timestamps provided by the global render loop for better perf.
  53362. *
  53363. * @param {function} functionToThrottle
  53364. * @param {number} minimumInterval - Minimal interval between calls (milliseconds).
  53365. * @param {object} optionalContext - If given, bind function to throttle to this context.
  53366. * @returns {function} Throttled function.
  53367. */
  53368. module.exports.throttleTick = function (functionToThrottle, minimumInterval, optionalContext) {
  53369. var lastTime;
  53370. if (optionalContext) {
  53371. functionToThrottle = module.exports.bind(functionToThrottle, optionalContext);
  53372. }
  53373. return function (time, delta) {
  53374. var sinceLastTime = typeof lastTime === 'undefined' ? delta : time - lastTime;
  53375. if (typeof lastTime === 'undefined' || (sinceLastTime >= minimumInterval)) {
  53376. lastTime = time;
  53377. functionToThrottle(time, sinceLastTime);
  53378. }
  53379. };
  53380. };
  53381. /**
  53382. * Fires a custom DOM event.
  53383. *
  53384. * @param {Element} el Element on which to fire the event.
  53385. * @param {String} name Name of the event.
  53386. * @param {Object=} [data={bubbles: true, {detail: <el>}}]
  53387. * Data to pass as `customEventInit` to the event.
  53388. */
  53389. module.exports.fireEvent = function (el, name, data) {
  53390. data = data || {};
  53391. data.detail = data.detail || {};
  53392. data.detail.target = data.detail.target || el;
  53393. var evt = new CustomEvent(name, data);
  53394. el.dispatchEvent(evt);
  53395. };
  53396. /**
  53397. * Mix the properties of source object(s) into a destination object.
  53398. *
  53399. * @param {object} dest - The object to which properties will be copied.
  53400. * @param {...object} source - The object(s) from which properties will be copied.
  53401. */
  53402. module.exports.extend = objectAssign;
  53403. module.exports.extendDeep = deepAssign;
  53404. module.exports.clone = function (obj) {
  53405. return JSON.parse(JSON.stringify(obj));
  53406. };
  53407. /**
  53408. * Checks if two values are equal.
  53409. * Includes objects and arrays and nested objects and arrays.
  53410. * Try to keep this function performant as it will be called often to see if a component
  53411. * should be updated.
  53412. *
  53413. * @param {object} a - First object.
  53414. * @param {object} b - Second object.
  53415. * @returns {boolean} Whether two objects are deeply equal.
  53416. */
  53417. function deepEqual (a, b) {
  53418. var i;
  53419. var keysA;
  53420. var keysB;
  53421. var valA;
  53422. var valB;
  53423. // If not objects, compare as values.
  53424. if (typeof a !== 'object' || typeof b !== 'object' ||
  53425. a === null || b === null) { return a === b; }
  53426. // Different number of keys, not equal.
  53427. keysA = Object.keys(a);
  53428. keysB = Object.keys(b);
  53429. if (keysA.length !== keysB.length) { return false; }
  53430. // Return `false` at the first sign of inequality.
  53431. for (i = 0; i < keysA.length; ++i) {
  53432. valA = a[keysA[i]];
  53433. valB = b[keysA[i]];
  53434. // Check nested array and object.
  53435. if ((typeof valA === 'object' || typeof valB === 'object') ||
  53436. (Array.isArray(valA) && Array.isArray(valB))) {
  53437. if (!deepEqual(valA, valB)) { return false; }
  53438. } else if (valA !== valB) {
  53439. return false;
  53440. }
  53441. }
  53442. return true;
  53443. }
  53444. module.exports.deepEqual = deepEqual;
  53445. /**
  53446. * Computes the difference between two objects.
  53447. *
  53448. * @param {object} a - First object to compare (e.g., oldData).
  53449. * @param {object} b - Second object to compare (e.g., newData).
  53450. * @returns {object}
  53451. * Difference object where set of keys note which values were not equal, and values are
  53452. * `b`'s values.
  53453. */
  53454. module.exports.diff = function (a, b) {
  53455. var diff = {};
  53456. var keys = Object.keys(a);
  53457. Object.keys(b).forEach(function collectKeys (bKey) {
  53458. if (keys.indexOf(bKey) === -1) {
  53459. keys.push(bKey);
  53460. }
  53461. });
  53462. keys.forEach(function doDiff (key) {
  53463. var aVal = a[key];
  53464. var bVal = b[key];
  53465. var isComparingObjects = aVal && bVal &&
  53466. aVal.constructor === Object && bVal.constructor === Object;
  53467. if ((isComparingObjects && !deepEqual(aVal, bVal)) ||
  53468. (!isComparingObjects && aVal !== bVal)) {
  53469. diff[key] = bVal;
  53470. }
  53471. });
  53472. return diff;
  53473. };
  53474. /**
  53475. * Returns whether we should capture this keyboard event for keyboard shortcuts.
  53476. * @param {Event} event Event object.
  53477. * @returns {Boolean} Whether the key event should be captured.
  53478. */
  53479. module.exports.shouldCaptureKeyEvent = function (event) {
  53480. if (event.metaKey) { return false; }
  53481. return document.activeElement === document.body;
  53482. };
  53483. /**
  53484. * Splits a string into an array based on a delimiter.
  53485. *
  53486. * @param {string=} [str=''] Source string
  53487. * @param {string=} [delimiter=' '] Delimiter to use
  53488. * @returns {array} Array of delimited strings
  53489. */
  53490. module.exports.splitString = function (str, delimiter) {
  53491. if (typeof delimiter === 'undefined') { delimiter = ' '; }
  53492. // First collapse the whitespace (or whatever the delimiter is).
  53493. var regex = new RegExp(delimiter, 'g');
  53494. str = (str || '').replace(regex, delimiter);
  53495. // Then split.
  53496. return str.split(delimiter);
  53497. };
  53498. /**
  53499. * Extracts data from the element given an object that contains expected keys.
  53500. *
  53501. * @param {Element} Source element.
  53502. * @param {Object} [defaults={}] Object of default key-value pairs.
  53503. * @returns {Object}
  53504. */
  53505. module.exports.getElData = function (el, defaults) {
  53506. defaults = defaults || {};
  53507. var data = {};
  53508. Object.keys(defaults).forEach(copyAttribute);
  53509. function copyAttribute (key) {
  53510. if (el.hasAttribute(key)) {
  53511. data[key] = el.getAttribute(key);
  53512. }
  53513. }
  53514. return data;
  53515. };
  53516. /**
  53517. * Retrieves querystring value.
  53518. * @param {String} name Name of querystring key.
  53519. * @return {String} Value
  53520. */
  53521. module.exports.getUrlParameter = function (name) {
  53522. // eslint-disable-next-line no-useless-escape
  53523. name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  53524. var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  53525. var results = regex.exec(location.search);
  53526. return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
  53527. };
  53528. /**
  53529. * Detects whether context is within iframe.
  53530. */
  53531. module.exports.isIframed = function () {
  53532. return window.top !== window.self;
  53533. };
  53534. /**
  53535. * Finds all elements under the element that have the isScene
  53536. * property set to true
  53537. */
  53538. module.exports.findAllScenes = function (el) {
  53539. var matchingElements = [];
  53540. var allElements = el.getElementsByTagName('*');
  53541. for (var i = 0, n = allElements.length; i < n; i++) {
  53542. if (allElements[i].isScene) {
  53543. // Element exists with isScene set.
  53544. matchingElements.push(allElements[i]);
  53545. }
  53546. }
  53547. return matchingElements;
  53548. };
  53549. // Must be at bottom to avoid circular dependency.
  53550. module.exports.srcLoader = _dereq_('./src-loader');
  53551. },{"./bind":161,"./coordinates":162,"./debug":163,"./device":164,"./entity":165,"./forceCanvasResizeSafariMobile":166,"./material":168,"./src-loader":169,"./styleParser":170,"./tracked-controls":171,"deep-assign":14,"object-assign":28}],168:[function(_dereq_,module,exports){
  53552. var THREE = _dereq_('../lib/three');
  53553. /**
  53554. * Update `material.map` given `data.src`. For standard and flat shaders.
  53555. *
  53556. * @param {object} shader - A-Frame shader instance.
  53557. * @param {object} data
  53558. */
  53559. module.exports.updateMapMaterialFromData = function (materialName, dataName, shader, data) {
  53560. var el = shader.el;
  53561. var material = shader.material;
  53562. var src = data[dataName];
  53563. var shadowSrcName = '_texture_' + dataName;
  53564. if (src) {
  53565. if (src === shader[shadowSrcName]) { return; }
  53566. // Texture added or changed.
  53567. shader[shadowSrcName] = src;
  53568. if (src instanceof THREE.Texture) { setMap(src); return; }
  53569. el.sceneEl.systems.material.loadTexture(src, {src: src, repeat: data.repeat, offset: data.offset, npot: data.npot}, setMap);
  53570. return;
  53571. }
  53572. // Texture removed.
  53573. if (!material[materialName]) { return; }
  53574. shader[shadowSrcName] = null;
  53575. setMap(null);
  53576. function setMap (texture) {
  53577. if (shader[shadowSrcName] !== src) { return; }
  53578. material[materialName] = texture;
  53579. material.needsUpdate = true;
  53580. handleTextureEvents(el, texture);
  53581. }
  53582. };
  53583. /**
  53584. * Update `material.map` given `data.src`. For standard and flat shaders.
  53585. *
  53586. * @param {object} shader - A-Frame shader instance.
  53587. * @param {object} data
  53588. */
  53589. module.exports.updateMap = function (shader, data) {
  53590. return module.exports.updateMapMaterialFromData('map', 'src', shader, data);
  53591. };
  53592. /**
  53593. * Updates the material's maps which give the illusion of extra geometry.
  53594. *
  53595. * @param {string} longType - The friendly name of the map from the component e.g. ambientOcclusionMap becomes aoMap in THREE.js
  53596. * @param {object} shader - A-Frame shader instance
  53597. * @param {object} data
  53598. */
  53599. module.exports.updateDistortionMap = function (longType, shader, data) {
  53600. var shortType = longType;
  53601. if (longType === 'ambientOcclusion') { shortType = 'ao'; }
  53602. var el = shader.el;
  53603. var material = shader.material;
  53604. var src = data[longType + 'Map'];
  53605. var info = {};
  53606. info.src = src;
  53607. // Pass through the repeat and offset to be handled by the material loader.
  53608. info.offset = data[longType + 'TextureOffset'];
  53609. info.repeat = data[longType + 'TextureRepeat'];
  53610. info.wrap = data[longType + 'TextureWrap'];
  53611. if (src) {
  53612. if (src === shader[longType + 'TextureSrc']) { return; }
  53613. // Texture added or changed.
  53614. shader[longType + 'TextureSrc'] = src;
  53615. el.sceneEl.systems.material.loadTexture(src, info, setMap);
  53616. return;
  53617. }
  53618. // Texture removed.
  53619. if (!material.map) { return; }
  53620. setMap(null);
  53621. function setMap (texture) {
  53622. material[shortType + 'Map'] = texture;
  53623. material.needsUpdate = true;
  53624. handleTextureEvents(el, texture);
  53625. }
  53626. };
  53627. /**
  53628. * Emit event on entities on texture-related events.
  53629. *
  53630. * @param {Element} el - Entity.
  53631. * @param {object} texture - three.js Texture.
  53632. */
  53633. function handleTextureEvents (el, texture) {
  53634. if (!texture) { return; }
  53635. el.emit('materialtextureloaded', {src: texture.image, texture: texture});
  53636. // Video events.
  53637. if (!texture.image || texture.image.tagName !== 'VIDEO') { return; }
  53638. texture.image.addEventListener('loadeddata', function emitVideoTextureLoadedDataAll () {
  53639. el.emit('materialvideoloadeddata', {src: texture.image, texture: texture});
  53640. });
  53641. texture.image.addEventListener('ended', function emitVideoTextureEndedAll () {
  53642. // Works for non-looping videos only.
  53643. el.emit('materialvideoended', {src: texture.image, texture: texture});
  53644. });
  53645. }
  53646. module.exports.handleTextureEvents = handleTextureEvents;
  53647. },{"../lib/three":146}],169:[function(_dereq_,module,exports){
  53648. /* global Image */
  53649. var debug = _dereq_('./debug');
  53650. var warn = debug('utils:src-loader:warn');
  53651. /**
  53652. * Validates a texture, either as a selector or as a URL.
  53653. * Detects whether `src` is pointing to an image or video and invokes the appropriate
  53654. * callback.
  53655. *
  53656. * The src will be returned on the callback
  53657. *
  53658. * @params {string} src - URL.
  53659. * @params {function} isImageCb - callback if texture is an image.
  53660. * @params {function} isVideoCb - callback if texture is a video.
  53661. */
  53662. function validateSrc (src, isImageCb, isVideoCb) {
  53663. validateImageUrl(src, function isAnImageUrl (isImage) {
  53664. if (isImage) {
  53665. isImageCb(src);
  53666. return;
  53667. }
  53668. isVideoCb(src);
  53669. });
  53670. }
  53671. /**
  53672. * Validates six images as a cubemap, either as selector or comma-separated
  53673. * URLs.
  53674. *
  53675. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  53676. must be wrapped by `url()`.
  53677. * @param {string} src - A selector or comma-separated image URLs. Image URLs
  53678. must be wrapped by `url()`.
  53679. */
  53680. function validateCubemapSrc (src, cb) {
  53681. var aCubemap;
  53682. var cubemapSrcRegex = '';
  53683. var i;
  53684. var urls;
  53685. var validatedUrls = [];
  53686. for (i = 0; i < 5; i++) {
  53687. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\),\\s*)';
  53688. }
  53689. cubemapSrcRegex += '(url\\((?:[^\\)]+)\\)\\s*)';
  53690. urls = src.match(new RegExp(cubemapSrcRegex));
  53691. // `src` is a comma-separated list of URLs.
  53692. // In this case, re-use validateSrc for each side of the cube.
  53693. function isImageCb (url) {
  53694. validatedUrls.push(url);
  53695. if (validatedUrls.length === 6) {
  53696. cb(validatedUrls);
  53697. }
  53698. }
  53699. if (urls) {
  53700. for (i = 1; i < 7; i++) {
  53701. // TODO: cubemap property type.
  53702. validateSrc(parseUrl(urls[i]), isImageCb);
  53703. }
  53704. return;
  53705. }
  53706. // `src` is a query selector to <a-cubemap> containing six $([src])s.
  53707. aCubemap = validateAndGetQuerySelector(src);
  53708. if (!aCubemap) { return; }
  53709. if (aCubemap.tagName === 'A-CUBEMAP' && aCubemap.srcs) {
  53710. return cb(aCubemap.srcs);
  53711. }
  53712. // Else if aCubeMap is not a <a-cubemap>.
  53713. warn('Selector "%s" does not point to <a-cubemap>', src);
  53714. }
  53715. /**
  53716. * Parses src from `url(src)`.
  53717. * @param {string} src - String to parse.
  53718. * @return {string} The parsed src, if parseable.
  53719. */
  53720. function parseUrl (src) {
  53721. var parsedSrc = src.match(/\url\((.+)\)/);
  53722. if (!parsedSrc) { return; }
  53723. return parsedSrc[1];
  53724. }
  53725. /**
  53726. * Validate src is a valid image url
  53727. * @param {string} src - url that will be tested
  53728. * @param {function} onResult - callback with the test result
  53729. */
  53730. function validateImageUrl (src, onResult) {
  53731. var tester = new Image();
  53732. tester.addEventListener('load', onLoad);
  53733. function onLoad () { onResult(true); }
  53734. tester.addEventListener('error', onError);
  53735. function onError () { onResult(false); }
  53736. tester.src = src;
  53737. }
  53738. /**
  53739. * Query and validate a query selector,
  53740. *
  53741. * @param {string} selector - DOM selector.
  53742. * @return {object|null|undefined} Selected DOM element if exists.
  53743. null if query yields no results.
  53744. undefined if `selector` is not a valid selector.
  53745. */
  53746. function validateAndGetQuerySelector (selector) {
  53747. try {
  53748. var el = document.querySelector(selector);
  53749. if (!el) {
  53750. warn('No element was found matching the selector: "%s"', selector);
  53751. }
  53752. return el;
  53753. } catch (e) { // Capture exception if it's not a valid selector.
  53754. warn('"%s" is not a valid selector', selector);
  53755. return undefined;
  53756. }
  53757. }
  53758. module.exports = {
  53759. parseUrl: parseUrl,
  53760. validateSrc: validateSrc,
  53761. validateCubemapSrc: validateCubemapSrc
  53762. };
  53763. },{"./debug":163}],170:[function(_dereq_,module,exports){
  53764. /* Utils for parsing style-like strings (e.g., "primitive: box; width: 5; height: 4.5"). */
  53765. var styleParser = _dereq_('style-attr');
  53766. /**
  53767. * Deserializes style-like string into an object of properties.
  53768. *
  53769. * @param {string} value - HTML attribute value.
  53770. * @returns {object} Property data.
  53771. */
  53772. module.exports.parse = function (value) {
  53773. var parsedData;
  53774. if (typeof value !== 'string') { return value; }
  53775. parsedData = styleParser.parse(value);
  53776. // The style parser returns an object { "" : "test"} when fed a string
  53777. if (parsedData['']) { return value; }
  53778. return transformKeysToCamelCase(parsedData);
  53779. };
  53780. /**
  53781. * Serialize an object of properties into a style-like string.
  53782. *
  53783. * @param {object} data - Property data.
  53784. * @returns {string}
  53785. */
  53786. module.exports.stringify = function (data) {
  53787. if (typeof data === 'string') { return data; }
  53788. return styleParser.stringify(data);
  53789. };
  53790. /**
  53791. * Converts string from hyphen to camelCase.
  53792. *
  53793. * @param {string} str - String to camelCase.
  53794. * @return {string} CamelCased string.
  53795. */
  53796. function toCamelCase (str) {
  53797. return str.replace(/-([a-z])/g, camelCase);
  53798. function camelCase (g) { return g[1].toUpperCase(); }
  53799. }
  53800. module.exports.toCamelCase = toCamelCase;
  53801. /**
  53802. * Converts object's keys from hyphens to camelCase (e.g., `max-value` to
  53803. * `maxValue`).
  53804. *
  53805. * @param {object} obj - The object to camelCase keys.
  53806. * @return {object} The object with keys camelCased.
  53807. */
  53808. function transformKeysToCamelCase (obj) {
  53809. var keys = Object.keys(obj);
  53810. var camelCaseObj = {};
  53811. keys.forEach(function (key) {
  53812. var camelCaseKey = toCamelCase(key);
  53813. camelCaseObj[camelCaseKey] = obj[key];
  53814. });
  53815. return camelCaseObj;
  53816. }
  53817. module.exports.transformKeysToCamelCase = transformKeysToCamelCase;
  53818. },{"style-attr":37}],171:[function(_dereq_,module,exports){
  53819. /**
  53820. * Return enumerated gamepads matching id prefix.
  53821. *
  53822. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  53823. */
  53824. module.exports.getGamepadsByPrefix = function (idPrefix) {
  53825. var gamepadsList = [];
  53826. var gamepad;
  53827. var gamepads = navigator.getGamepads && navigator.getGamepads();
  53828. if (!gamepads) { return gamepadsList; }
  53829. for (var i = 0; i < gamepads.length; ++i) {
  53830. gamepad = gamepads[i];
  53831. // need to check that gamepad is valid, since browsers may return array of null values
  53832. if (gamepad) {
  53833. if (!idPrefix || gamepad.id.indexOf(idPrefix) === 0) {
  53834. gamepadsList.push(gamepad);
  53835. }
  53836. }
  53837. }
  53838. return gamepadsList;
  53839. };
  53840. /**
  53841. * Enumerate controllers (as built by system tick, e.g. that have pose) and check if they match parameters.
  53842. *
  53843. * @param {object} sceneEl - the scene element.
  53844. * @param {object} idPrefix - prefix to match in gamepad id, if any.
  53845. * @param {object} queryObject - map of values to match (hand; index among controllers with idPrefix)
  53846. */
  53847. module.exports.isControllerPresent = function (sceneEl, idPrefix, queryObject) {
  53848. var isPresent = false;
  53849. var index = 0;
  53850. var gamepad;
  53851. var isPrefixMatch;
  53852. var gamepads;
  53853. var trackedControlsSystem = sceneEl && sceneEl.systems['tracked-controls'];
  53854. if (!trackedControlsSystem) { return isPresent; }
  53855. gamepads = trackedControlsSystem.controllers;
  53856. if (!gamepads || gamepads.length === 0) {
  53857. trackedControlsSystem.updateControllerList();
  53858. gamepads = trackedControlsSystem.controllers;
  53859. }
  53860. if (!gamepads) { return isPresent; }
  53861. for (var i = 0; i < gamepads.length; ++i) {
  53862. gamepad = gamepads[i];
  53863. isPrefixMatch = (!idPrefix || idPrefix === '' || gamepad.id.indexOf(idPrefix) === 0);
  53864. isPresent = isPrefixMatch;
  53865. if (isPresent && queryObject.hand) {
  53866. isPresent = gamepad.hand === queryObject.hand;
  53867. }
  53868. if (isPresent && queryObject.index) {
  53869. isPresent = index === queryObject.index; // need to use count of gamepads with idPrefix
  53870. }
  53871. if (isPresent) { break; }
  53872. if (isPrefixMatch) { index++; } // update count of gamepads with idPrefix
  53873. }
  53874. return isPresent;
  53875. };
  53876. },{}],172:[function(_dereq_,module,exports){
  53877. /**
  53878. * @author dmarcos / https://github.com/dmarcos
  53879. * @author mrdoob / http://mrdoob.com
  53880. */
  53881. THREE.VRControls = function ( object, onError ) {
  53882. var scope = this;
  53883. var vrDisplay, vrDisplays;
  53884. var standingMatrix = new THREE.Matrix4();
  53885. var frameData = null;
  53886. if ( 'VRFrameData' in window ) {
  53887. frameData = new VRFrameData();
  53888. }
  53889. function gotVRDisplays( displays ) {
  53890. vrDisplays = displays;
  53891. if ( displays.length > 0 ) {
  53892. vrDisplay = displays[ 0 ];
  53893. } else {
  53894. if ( onError ) onError( 'VR input not available.' );
  53895. }
  53896. }
  53897. if ( navigator.getVRDisplays ) {
  53898. navigator.getVRDisplays().then( gotVRDisplays ).catch ( function () {
  53899. console.warn( 'THREE.VRControls: Unable to get VR Displays' );
  53900. } );
  53901. }
  53902. // the Rift SDK returns the position in meters
  53903. // this scale factor allows the user to define how meters
  53904. // are converted to scene units.
  53905. this.scale = 1;
  53906. // If true will use "standing space" coordinate system where y=0 is the
  53907. // floor and x=0, z=0 is the center of the room.
  53908. this.standing = false;
  53909. // Distance from the users eyes to the floor in meters. Used when
  53910. // standing=true but the VRDisplay doesn't provide stageParameters.
  53911. this.userHeight = 1.6;
  53912. this.getVRDisplay = function () {
  53913. return vrDisplay;
  53914. };
  53915. this.setVRDisplay = function ( value ) {
  53916. vrDisplay = value;
  53917. };
  53918. this.getVRDisplays = function () {
  53919. console.warn( 'THREE.VRControls: getVRDisplays() is being deprecated.' );
  53920. return vrDisplays;
  53921. };
  53922. this.getStandingMatrix = function () {
  53923. return standingMatrix;
  53924. };
  53925. this.update = function () {
  53926. if ( vrDisplay ) {
  53927. var pose;
  53928. if ( vrDisplay.getFrameData ) {
  53929. vrDisplay.getFrameData( frameData );
  53930. pose = frameData.pose;
  53931. } else if ( vrDisplay.getPose ) {
  53932. pose = vrDisplay.getPose();
  53933. }
  53934. if ( pose.orientation !== null ) {
  53935. object.quaternion.fromArray( pose.orientation );
  53936. }
  53937. if ( pose.position !== null ) {
  53938. object.position.fromArray( pose.position );
  53939. } else {
  53940. object.position.set( 0, 0, 0 );
  53941. }
  53942. if ( this.standing ) {
  53943. if ( vrDisplay.stageParameters ) {
  53944. object.updateMatrix();
  53945. standingMatrix.fromArray( vrDisplay.stageParameters.sittingToStandingTransform );
  53946. object.applyMatrix( standingMatrix );
  53947. } else {
  53948. object.position.setY( object.position.y + this.userHeight );
  53949. }
  53950. }
  53951. object.position.multiplyScalar( scope.scale );
  53952. }
  53953. };
  53954. this.resetPose = function () {
  53955. if ( vrDisplay ) {
  53956. vrDisplay.resetPose();
  53957. }
  53958. };
  53959. this.resetSensor = function () {
  53960. console.warn( 'THREE.VRControls: .resetSensor() is now .resetPose().' );
  53961. this.resetPose();
  53962. };
  53963. this.zeroSensor = function () {
  53964. console.warn( 'THREE.VRControls: .zeroSensor() is now .resetPose().' );
  53965. this.resetPose();
  53966. };
  53967. this.dispose = function () {
  53968. vrDisplay = null;
  53969. };
  53970. };
  53971. },{}],173:[function(_dereq_,module,exports){
  53972. /**
  53973. * @author dmarcos / https://github.com/dmarcos
  53974. * @author mrdoob / http://mrdoob.com
  53975. *
  53976. * WebVR Spec: http://mozvr.github.io/webvr-spec/webvr.html
  53977. *
  53978. * Firefox: http://mozvr.com/downloads/
  53979. * Chromium: https://webvr.info/get-chrome
  53980. *
  53981. */
  53982. THREE.VREffect = function( renderer, onError ) {
  53983. var vrDisplay, vrDisplays;
  53984. var eyeTranslationL = new THREE.Vector3();
  53985. var eyeTranslationR = new THREE.Vector3();
  53986. var renderRectL, renderRectR;
  53987. var frameData = null;
  53988. if ( 'VRFrameData' in window ) {
  53989. frameData = new window.VRFrameData();
  53990. }
  53991. function gotVRDisplays( displays ) {
  53992. vrDisplays = displays;
  53993. if ( displays.length > 0 ) {
  53994. vrDisplay = displays[ 0 ];
  53995. } else {
  53996. if ( onError ) onError( 'HMD not available' );
  53997. }
  53998. }
  53999. if ( navigator.getVRDisplays ) {
  54000. navigator.getVRDisplays().then( gotVRDisplays ).catch( function() {
  54001. console.warn( 'THREE.VREffect: Unable to get VR Displays' );
  54002. } );
  54003. }
  54004. //
  54005. this.isPresenting = false;
  54006. var scope = this;
  54007. var rendererSize = renderer.getSize();
  54008. var rendererUpdateStyle = false;
  54009. var rendererPixelRatio = renderer.getPixelRatio();
  54010. this.getVRDisplay = function() {
  54011. return vrDisplay;
  54012. };
  54013. this.setVRDisplay = function( value ) {
  54014. vrDisplay = value;
  54015. };
  54016. this.getVRDisplays = function() {
  54017. console.warn( 'THREE.VREffect: getVRDisplays() is being deprecated.' );
  54018. return vrDisplays;
  54019. };
  54020. this.setSize = function( width, height, updateStyle ) {
  54021. rendererSize = { width: width, height: height };
  54022. rendererUpdateStyle = updateStyle;
  54023. if ( scope.isPresenting ) {
  54024. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  54025. renderer.setPixelRatio( 1 );
  54026. renderer.setSize( eyeParamsL.renderWidth * 2, eyeParamsL.renderHeight, false );
  54027. } else {
  54028. renderer.setPixelRatio( rendererPixelRatio );
  54029. renderer.setSize( width, height, updateStyle );
  54030. }
  54031. };
  54032. // VR presentation
  54033. var canvas = renderer.domElement;
  54034. var defaultLeftBounds = [ 0.0, 0.0, 0.5, 1.0 ];
  54035. var defaultRightBounds = [ 0.5, 0.0, 0.5, 1.0 ];
  54036. function onVRDisplayPresentChange() {
  54037. var wasPresenting = scope.isPresenting;
  54038. scope.isPresenting = vrDisplay !== undefined && vrDisplay.isPresenting;
  54039. if ( scope.isPresenting ) {
  54040. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  54041. var eyeWidth = eyeParamsL.renderWidth;
  54042. var eyeHeight = eyeParamsL.renderHeight;
  54043. if ( ! wasPresenting ) {
  54044. rendererPixelRatio = renderer.getPixelRatio();
  54045. rendererSize = renderer.getSize();
  54046. renderer.setPixelRatio( 1 );
  54047. renderer.setSize( eyeWidth * 2, eyeHeight, false );
  54048. }
  54049. } else if ( wasPresenting ) {
  54050. renderer.setPixelRatio( rendererPixelRatio );
  54051. renderer.setSize( rendererSize.width, rendererSize.height, rendererUpdateStyle );
  54052. }
  54053. }
  54054. window.addEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  54055. this.setFullScreen = function( boolean ) {
  54056. return new Promise( function( resolve, reject ) {
  54057. if ( vrDisplay === undefined ) {
  54058. reject( new Error( 'No VR hardware found.' ) );
  54059. return;
  54060. }
  54061. if ( scope.isPresenting === boolean ) {
  54062. resolve();
  54063. return;
  54064. }
  54065. if ( boolean ) {
  54066. resolve( vrDisplay.requestPresent( [ { source: canvas } ] ) );
  54067. } else {
  54068. resolve( vrDisplay.exitPresent() );
  54069. }
  54070. } );
  54071. };
  54072. this.requestPresent = function() {
  54073. return this.setFullScreen( true );
  54074. };
  54075. this.exitPresent = function() {
  54076. return this.setFullScreen( false );
  54077. };
  54078. this.requestAnimationFrame = function( f ) {
  54079. if ( vrDisplay !== undefined ) {
  54080. return vrDisplay.requestAnimationFrame( f );
  54081. } else {
  54082. return window.requestAnimationFrame( f );
  54083. }
  54084. };
  54085. this.cancelAnimationFrame = function( h ) {
  54086. if ( vrDisplay !== undefined ) {
  54087. vrDisplay.cancelAnimationFrame( h );
  54088. } else {
  54089. window.cancelAnimationFrame( h );
  54090. }
  54091. };
  54092. this.submitFrame = function() {
  54093. if ( vrDisplay !== undefined && scope.isPresenting ) {
  54094. vrDisplay.submitFrame();
  54095. }
  54096. };
  54097. this.autoSubmitFrame = true;
  54098. // render
  54099. var cameraL = new THREE.PerspectiveCamera();
  54100. cameraL.layers.enable( 1 );
  54101. var cameraR = new THREE.PerspectiveCamera();
  54102. cameraR.layers.enable( 2 );
  54103. this.render = function( scene, camera, renderTarget, forceClear ) {
  54104. if ( vrDisplay && scope.isPresenting ) {
  54105. var autoUpdate = scene.autoUpdate;
  54106. if ( autoUpdate ) {
  54107. scene.updateMatrixWorld();
  54108. scene.autoUpdate = false;
  54109. }
  54110. var eyeParamsL = vrDisplay.getEyeParameters( 'left' );
  54111. var eyeParamsR = vrDisplay.getEyeParameters( 'right' );
  54112. eyeTranslationL.fromArray( eyeParamsL.offset );
  54113. eyeTranslationR.fromArray( eyeParamsR.offset );
  54114. if ( Array.isArray( scene ) ) {
  54115. console.warn( 'THREE.VREffect.render() no longer supports arrays. Use object.layers instead.' );
  54116. scene = scene[ 0 ];
  54117. }
  54118. // When rendering we don't care what the recommended size is, only what the actual size
  54119. // of the backbuffer is.
  54120. var size = renderer.getSize();
  54121. var layers = vrDisplay.getLayers();
  54122. var leftBounds;
  54123. var rightBounds;
  54124. if ( layers.length ) {
  54125. var layer = layers[ 0 ];
  54126. leftBounds = layer.leftBounds !== null && layer.leftBounds.length === 4 ? layer.leftBounds : defaultLeftBounds;
  54127. rightBounds = layer.rightBounds !== null && layer.rightBounds.length === 4 ? layer.rightBounds : defaultRightBounds;
  54128. } else {
  54129. leftBounds = defaultLeftBounds;
  54130. rightBounds = defaultRightBounds;
  54131. }
  54132. renderRectL = {
  54133. x: Math.round( size.width * leftBounds[ 0 ] ),
  54134. y: Math.round( size.height * leftBounds[ 1 ] ),
  54135. width: Math.round( size.width * leftBounds[ 2 ] ),
  54136. height: Math.round( size.height * leftBounds[ 3 ] )
  54137. };
  54138. renderRectR = {
  54139. x: Math.round( size.width * rightBounds[ 0 ] ),
  54140. y: Math.round( size.height * rightBounds[ 1 ] ),
  54141. width: Math.round( size.width * rightBounds[ 2 ] ),
  54142. height: Math.round( size.height * rightBounds[ 3 ] )
  54143. };
  54144. if ( renderTarget ) {
  54145. renderer.setRenderTarget( renderTarget );
  54146. renderTarget.scissorTest = true;
  54147. } else {
  54148. renderer.setRenderTarget( null );
  54149. renderer.setScissorTest( true );
  54150. }
  54151. if ( renderer.autoClear || forceClear ) renderer.clear();
  54152. if ( camera.parent === null ) camera.updateMatrixWorld();
  54153. camera.matrixWorld.decompose( cameraL.position, cameraL.quaternion, cameraL.scale );
  54154. cameraR.position.copy(cameraL.position);
  54155. cameraR.quaternion.copy(cameraL.quaternion);
  54156. cameraR.scale.copy(cameraL.scale);
  54157. cameraL.translateOnAxis( eyeTranslationL, cameraL.scale.x );
  54158. cameraR.translateOnAxis( eyeTranslationR, cameraR.scale.x );
  54159. if ( vrDisplay.getFrameData ) {
  54160. vrDisplay.depthNear = camera.near;
  54161. vrDisplay.depthFar = camera.far;
  54162. vrDisplay.getFrameData( frameData );
  54163. cameraL.projectionMatrix.elements = frameData.leftProjectionMatrix;
  54164. cameraR.projectionMatrix.elements = frameData.rightProjectionMatrix;
  54165. } else {
  54166. cameraL.projectionMatrix = fovToProjection( eyeParamsL.fieldOfView, true, camera.near, camera.far );
  54167. cameraR.projectionMatrix = fovToProjection( eyeParamsR.fieldOfView, true, camera.near, camera.far );
  54168. }
  54169. // render left eye
  54170. if ( renderTarget ) {
  54171. renderTarget.viewport.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  54172. renderTarget.scissor.set( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  54173. } else {
  54174. renderer.setViewport( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  54175. renderer.setScissor( renderRectL.x, renderRectL.y, renderRectL.width, renderRectL.height );
  54176. }
  54177. renderer.render( scene, cameraL, renderTarget, forceClear );
  54178. // render right eye
  54179. if ( renderTarget ) {
  54180. renderTarget.viewport.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  54181. renderTarget.scissor.set( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  54182. } else {
  54183. renderer.setViewport( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  54184. renderer.setScissor( renderRectR.x, renderRectR.y, renderRectR.width, renderRectR.height );
  54185. }
  54186. renderer.render( scene, cameraR, renderTarget, forceClear );
  54187. if ( renderTarget ) {
  54188. renderTarget.viewport.set( 0, 0, size.width, size.height );
  54189. renderTarget.scissor.set( 0, 0, size.width, size.height );
  54190. renderTarget.scissorTest = false;
  54191. renderer.setRenderTarget( null );
  54192. } else {
  54193. renderer.setViewport( 0, 0, size.width, size.height );
  54194. renderer.setScissorTest( false );
  54195. }
  54196. if ( autoUpdate ) {
  54197. scene.autoUpdate = true;
  54198. }
  54199. if ( scope.autoSubmitFrame ) {
  54200. scope.submitFrame();
  54201. }
  54202. return;
  54203. }
  54204. // Regular render mode if not HMD
  54205. renderer.render( scene, camera, renderTarget, forceClear );
  54206. };
  54207. this.dispose = function() {
  54208. window.removeEventListener( 'vrdisplaypresentchange', onVRDisplayPresentChange, false );
  54209. };
  54210. //
  54211. function fovToNDCScaleOffset( fov ) {
  54212. var pxscale = 2.0 / ( fov.leftTan + fov.rightTan );
  54213. var pxoffset = ( fov.leftTan - fov.rightTan ) * pxscale * 0.5;
  54214. var pyscale = 2.0 / ( fov.upTan + fov.downTan );
  54215. var pyoffset = ( fov.upTan - fov.downTan ) * pyscale * 0.5;
  54216. return { scale: [ pxscale, pyscale ], offset: [ pxoffset, pyoffset ] };
  54217. }
  54218. function fovPortToProjection( fov, rightHanded, zNear, zFar ) {
  54219. rightHanded = rightHanded === undefined ? true : rightHanded;
  54220. zNear = zNear === undefined ? 0.01 : zNear;
  54221. zFar = zFar === undefined ? 10000.0 : zFar;
  54222. var handednessScale = rightHanded ? - 1.0 : 1.0;
  54223. // start with an identity matrix
  54224. var mobj = new THREE.Matrix4();
  54225. var m = mobj.elements;
  54226. // and with scale/offset info for normalized device coords
  54227. var scaleAndOffset = fovToNDCScaleOffset( fov );
  54228. // X result, map clip edges to [-w,+w]
  54229. m[ 0 * 4 + 0 ] = scaleAndOffset.scale[ 0 ];
  54230. m[ 0 * 4 + 1 ] = 0.0;
  54231. m[ 0 * 4 + 2 ] = scaleAndOffset.offset[ 0 ] * handednessScale;
  54232. m[ 0 * 4 + 3 ] = 0.0;
  54233. // Y result, map clip edges to [-w,+w]
  54234. // Y offset is negated because this proj matrix transforms from world coords with Y=up,
  54235. // but the NDC scaling has Y=down (thanks D3D?)
  54236. m[ 1 * 4 + 0 ] = 0.0;
  54237. m[ 1 * 4 + 1 ] = scaleAndOffset.scale[ 1 ];
  54238. m[ 1 * 4 + 2 ] = - scaleAndOffset.offset[ 1 ] * handednessScale;
  54239. m[ 1 * 4 + 3 ] = 0.0;
  54240. // Z result (up to the app)
  54241. m[ 2 * 4 + 0 ] = 0.0;
  54242. m[ 2 * 4 + 1 ] = 0.0;
  54243. m[ 2 * 4 + 2 ] = zFar / ( zNear - zFar ) * - handednessScale;
  54244. m[ 2 * 4 + 3 ] = ( zFar * zNear ) / ( zNear - zFar );
  54245. // W result (= Z in)
  54246. m[ 3 * 4 + 0 ] = 0.0;
  54247. m[ 3 * 4 + 1 ] = 0.0;
  54248. m[ 3 * 4 + 2 ] = handednessScale;
  54249. m[ 3 * 4 + 3 ] = 0.0;
  54250. mobj.transpose();
  54251. return mobj;
  54252. }
  54253. function fovToProjection( fov, rightHanded, zNear, zFar ) {
  54254. var DEG2RAD = Math.PI / 180.0;
  54255. var fovPort = {
  54256. upTan: Math.tan( fov.upDegrees * DEG2RAD ),
  54257. downTan: Math.tan( fov.downDegrees * DEG2RAD ),
  54258. leftTan: Math.tan( fov.leftDegrees * DEG2RAD ),
  54259. rightTan: Math.tan( fov.rightDegrees * DEG2RAD )
  54260. };
  54261. return fovPortToProjection( fovPort, rightHanded, zNear, zFar );
  54262. }
  54263. };
  54264. },{}],174:[function(_dereq_,module,exports){
  54265. window.glStats = function () {
  54266. var _rS = null;
  54267. var _totalDrawArraysCalls = 0,
  54268. _totalDrawElementsCalls = 0,
  54269. _totalUseProgramCalls = 0,
  54270. _totalFaces = 0,
  54271. _totalVertices = 0,
  54272. _totalPoints = 0,
  54273. _totalBindTexures = 0;
  54274. function _h ( f, c ) {
  54275. return function () {
  54276. c.apply( this, arguments );
  54277. f.apply( this, arguments );
  54278. };
  54279. }
  54280. WebGLRenderingContext.prototype.drawArrays = _h( WebGLRenderingContext.prototype.drawArrays, function () {
  54281. _totalDrawArraysCalls++;
  54282. if ( arguments[ 0 ] == this.POINTS ) _totalPoints += arguments[ 2 ];
  54283. else _totalVertices += arguments[ 2 ];
  54284. } );
  54285. WebGLRenderingContext.prototype.drawElements = _h( WebGLRenderingContext.prototype.drawElements, function () {
  54286. _totalDrawElementsCalls++;
  54287. _totalFaces += arguments[ 1 ] / 3;
  54288. _totalVertices += arguments[ 1 ];
  54289. } );
  54290. WebGLRenderingContext.prototype.useProgram = _h( WebGLRenderingContext.prototype.useProgram, function () {
  54291. _totalUseProgramCalls++;
  54292. } );
  54293. WebGLRenderingContext.prototype.bindTexture = _h( WebGLRenderingContext.prototype.bindTexture, function () {
  54294. _totalBindTexures++;
  54295. } );
  54296. var _values = {
  54297. allcalls: {
  54298. over: 3000,
  54299. caption: 'Calls (hook)'
  54300. },
  54301. drawelements: {
  54302. caption: 'drawElements (hook)'
  54303. },
  54304. drawarrays: {
  54305. caption: 'drawArrays (hook)'
  54306. }
  54307. };
  54308. var _groups = [ {
  54309. caption: 'WebGL',
  54310. values: [ 'allcalls', 'drawelements', 'drawarrays', 'useprogram', 'bindtexture', 'glfaces', 'glvertices', 'glpoints' ]
  54311. } ];
  54312. var _fractions = [ {
  54313. base: 'allcalls',
  54314. steps: [ 'drawelements', 'drawarrays' ]
  54315. } ];
  54316. function _update () {
  54317. _rS( 'allcalls' ).set( _totalDrawArraysCalls + _totalDrawElementsCalls );
  54318. _rS( 'drawElements' ).set( _totalDrawElementsCalls );
  54319. _rS( 'drawArrays' ).set( _totalDrawArraysCalls );
  54320. _rS( 'bindTexture' ).set( _totalBindTexures );
  54321. _rS( 'useProgram' ).set( _totalUseProgramCalls );
  54322. _rS( 'glfaces' ).set( _totalFaces );
  54323. _rS( 'glvertices' ).set( _totalVertices );
  54324. _rS( 'glpoints' ).set( _totalPoints );
  54325. }
  54326. function _start () {
  54327. _totalDrawArraysCalls = 0;
  54328. _totalDrawElementsCalls = 0;
  54329. _totalUseProgramCalls = 0;
  54330. _totalFaces = 0;
  54331. _totalVertices = 0;
  54332. _totalPoints = 0;
  54333. _totalBindTexures = 0;
  54334. }
  54335. function _end () {}
  54336. function _attach ( r ) {
  54337. _rS = r;
  54338. }
  54339. return {
  54340. update: _update,
  54341. start: _start,
  54342. end: _end,
  54343. attach: _attach,
  54344. values: _values,
  54345. groups: _groups,
  54346. fractions: _fractions
  54347. };
  54348. };
  54349. window.threeStats = function ( renderer ) {
  54350. var _rS = null;
  54351. var _values = {
  54352. 'renderer.info.memory.geometries': {
  54353. caption: 'Geometries'
  54354. },
  54355. 'renderer.info.memory.textures': {
  54356. caption: 'Textures'
  54357. },
  54358. 'renderer.info.programs': {
  54359. caption: 'Programs'
  54360. },
  54361. 'renderer.info.render.calls': {
  54362. caption: 'Calls'
  54363. },
  54364. 'renderer.info.render.faces': {
  54365. caption: 'Faces',
  54366. over: 1000
  54367. },
  54368. 'renderer.info.render.points': {
  54369. caption: 'Points'
  54370. },
  54371. 'renderer.info.render.vertices': {
  54372. caption: 'Vertices'
  54373. }
  54374. };
  54375. var _groups = [ {
  54376. caption: 'Three.js - Memory',
  54377. values: [ 'renderer.info.memory.geometries', 'renderer.info.programs', 'renderer.info.memory.textures' ]
  54378. }, {
  54379. caption: 'Three.js - Render',
  54380. values: [ 'renderer.info.render.calls', 'renderer.info.render.faces', 'renderer.info.render.points', 'renderer.info.render.vertices' ]
  54381. } ];
  54382. var _fractions = [];
  54383. function _update () {
  54384. _rS( 'renderer.info.memory.geometries' ).set( renderer.info.memory.geometries );
  54385. _rS( 'renderer.info.programs' ).set( renderer.info.programs.length );
  54386. _rS( 'renderer.info.memory.textures' ).set( renderer.info.memory.textures );
  54387. _rS( 'renderer.info.render.calls' ).set( renderer.info.render.calls );
  54388. _rS( 'renderer.info.render.faces' ).set( renderer.info.render.faces );
  54389. _rS( 'renderer.info.render.points' ).set( renderer.info.render.points );
  54390. _rS( 'renderer.info.render.vertices' ).set( renderer.info.render.vertices );
  54391. }
  54392. function _start () {}
  54393. function _end () {}
  54394. function _attach ( r ) {
  54395. _rS = r;
  54396. }
  54397. return {
  54398. update: _update,
  54399. start: _start,
  54400. end: _end,
  54401. attach: _attach,
  54402. values: _values,
  54403. groups: _groups,
  54404. fractions: _fractions
  54405. };
  54406. };
  54407. /*
  54408. * From https://github.com/paulirish/memory-stats.js
  54409. */
  54410. window.BrowserStats = function () {
  54411. var _rS = null;
  54412. var _usedJSHeapSize = 0,
  54413. _totalJSHeapSize = 0;
  54414. if ( window.performance && !performance.memory ) {
  54415. performance.memory = {
  54416. usedJSHeapSize: 0,
  54417. totalJSHeapSize: 0
  54418. };
  54419. }
  54420. if ( performance.memory.totalJSHeapSize === 0 ) {
  54421. console.warn( 'totalJSHeapSize === 0... performance.memory is only available in Chrome .' );
  54422. }
  54423. var _values = {
  54424. memory: {
  54425. caption: 'Used Memory',
  54426. average: true,
  54427. avgMs: 1000,
  54428. over: 22
  54429. },
  54430. total: {
  54431. caption: 'Total Memory'
  54432. }
  54433. };
  54434. var _groups = [ {
  54435. caption: 'Browser',
  54436. values: [ 'memory', 'total' ]
  54437. } ];
  54438. var _fractions = [ {
  54439. base: 'total',
  54440. steps: [ 'memory' ]
  54441. } ];
  54442. var log1024 = Math.log( 1024 );
  54443. function _size ( v ) {
  54444. var precision = 100; //Math.pow(10, 2);
  54445. var i = Math.floor( Math.log( v ) / log1024 );
  54446. return Math.round( v * precision / Math.pow( 1024, i ) ) / precision; // + ' ' + sizes[i];
  54447. }
  54448. function _update () {
  54449. _usedJSHeapSize = _size( performance.memory.usedJSHeapSize );
  54450. _totalJSHeapSize = _size( performance.memory.totalJSHeapSize );
  54451. _rS( 'memory' ).set( _usedJSHeapSize );
  54452. _rS( 'total' ).set( _totalJSHeapSize );
  54453. }
  54454. function _start () {
  54455. _usedJSHeapSize = 0;
  54456. }
  54457. function _end () {}
  54458. function _attach ( r ) {
  54459. _rS = r;
  54460. }
  54461. return {
  54462. update: _update,
  54463. start: _start,
  54464. end: _end,
  54465. attach: _attach,
  54466. values: _values,
  54467. groups: _groups,
  54468. fractions: _fractions
  54469. };
  54470. };
  54471. if (typeof module === 'object') {
  54472. module.exports = {
  54473. glStats: window.glStats,
  54474. threeStats: window.threeStats,
  54475. BrowserStats: window.BrowserStats
  54476. };
  54477. }
  54478. },{}],175:[function(_dereq_,module,exports){
  54479. // performance.now() polyfill from https://gist.github.com/paulirish/5438650
  54480. 'use strict';
  54481. ( function () {
  54482. // prepare base perf object
  54483. if ( typeof window.performance === 'undefined' ) {
  54484. window.performance = {};
  54485. }
  54486. if ( !window.performance.now ) {
  54487. var nowOffset = Date.now();
  54488. if ( performance.timing && performance.timing.navigationStart ) {
  54489. nowOffset = performance.timing.navigationStart;
  54490. }
  54491. window.performance.now = function now () {
  54492. return Date.now() - nowOffset;
  54493. };
  54494. }
  54495. if( !window.performance.mark ) {
  54496. window.performance.mark = function(){}
  54497. }
  54498. if( !window.performance.measure ) {
  54499. window.performance.measure = function(){}
  54500. }
  54501. } )();
  54502. window.rStats = function rStats ( settings ) {
  54503. function iterateKeys ( array, callback ) {
  54504. var keys = Object.keys( array );
  54505. for ( var j = 0, l = keys.length; j < l; j++ ) {
  54506. callback( keys[ j ] );
  54507. }
  54508. }
  54509. function importCSS ( url ) {
  54510. var element = document.createElement( 'link' );
  54511. element.href = url;
  54512. element.rel = 'stylesheet';
  54513. element.type = 'text/css';
  54514. document.getElementsByTagName( 'head' )[ 0 ].appendChild( element );
  54515. }
  54516. var _settings = settings || {};
  54517. var _colours = _settings.colours || [ '#850700', '#c74900', '#fcb300', '#284280', '#4c7c0c' ];
  54518. var _cssFont = 'https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,300';
  54519. var _cssRStats = ( _settings.CSSPath ? _settings.CSSPath : '' ) + 'rStats.css';
  54520. var _css = _settings.css || [ _cssFont, _cssRStats ];
  54521. _css.forEach(function (uri) {
  54522. importCSS( uri );
  54523. });
  54524. if ( !_settings.values ) _settings.values = {};
  54525. var _base, _div, _elHeight = 10, _elWidth = 200;
  54526. var _perfCounters = {};
  54527. function Graph ( _dom, _id, _defArg ) {
  54528. var _def = _defArg || {};
  54529. var _canvas = document.createElement( 'canvas' ),
  54530. _ctx = _canvas.getContext( '2d' ),
  54531. _max = 0,
  54532. _current = 0;
  54533. var c = _def.color ? _def.color : '#666666';
  54534. var _dotCanvas = document.createElement( 'canvas' ),
  54535. _dotCtx = _dotCanvas.getContext( '2d' );
  54536. _dotCanvas.width = 1;
  54537. _dotCanvas.height = 2 * _elHeight;
  54538. _dotCtx.fillStyle = '#444444';
  54539. _dotCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  54540. _dotCtx.fillStyle = c;
  54541. _dotCtx.fillRect( 0, _elHeight, 1, _elHeight );
  54542. _dotCtx.fillStyle = '#ffffff';
  54543. _dotCtx.globalAlpha = 0.5;
  54544. _dotCtx.fillRect( 0, _elHeight, 1, 1 );
  54545. _dotCtx.globalAlpha = 1;
  54546. var _alarmCanvas = document.createElement( 'canvas' ),
  54547. _alarmCtx = _alarmCanvas.getContext( '2d' );
  54548. _alarmCanvas.width = 1;
  54549. _alarmCanvas.height = 2 * _elHeight;
  54550. _alarmCtx.fillStyle = '#444444';
  54551. _alarmCtx.fillRect( 0, 0, 1, 2 * _elHeight );
  54552. _alarmCtx.fillStyle = '#b70000';
  54553. _alarmCtx.fillRect( 0, _elHeight, 1, _elHeight );
  54554. _alarmCtx.globalAlpha = 0.5;
  54555. _alarmCtx.fillStyle = '#ffffff';
  54556. _alarmCtx.fillRect( 0, _elHeight, 1, 1 );
  54557. _alarmCtx.globalAlpha = 1;
  54558. function _init () {
  54559. _canvas.width = _elWidth;
  54560. _canvas.height = _elHeight;
  54561. _canvas.style.width = _canvas.width + 'px';
  54562. _canvas.style.height = _canvas.height + 'px';
  54563. _canvas.className = 'rs-canvas';
  54564. _dom.appendChild( _canvas );
  54565. _ctx.fillStyle = '#444444';
  54566. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  54567. }
  54568. function _draw ( v, alarm ) {
  54569. _current += ( v - _current ) * 0.1;
  54570. _max *= 0.99;
  54571. if ( _current > _max ) _max = _current;
  54572. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  54573. if ( alarm ) {
  54574. _ctx.drawImage( _alarmCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  54575. } else {
  54576. _ctx.drawImage( _dotCanvas, _canvas.width - 1, _canvas.height - _current * _canvas.height / _max - _elHeight );
  54577. }
  54578. }
  54579. _init();
  54580. return {
  54581. draw: _draw
  54582. };
  54583. }
  54584. function StackGraph ( _dom, _num ) {
  54585. var _canvas = document.createElement( 'canvas' ),
  54586. _ctx = _canvas.getContext( '2d' );
  54587. function _init () {
  54588. _canvas.width = _elWidth;
  54589. _canvas.height = _elHeight * _num;
  54590. _canvas.style.width = _canvas.width + 'px';
  54591. _canvas.style.height = _canvas.height + 'px';
  54592. _canvas.className = 'rs-canvas';
  54593. _dom.appendChild( _canvas );
  54594. _ctx.fillStyle = '#444444';
  54595. _ctx.fillRect( 0, 0, _canvas.width, _canvas.height );
  54596. }
  54597. function _draw ( v ) {
  54598. _ctx.drawImage( _canvas, 1, 0, _canvas.width - 1, _canvas.height, 0, 0, _canvas.width - 1, _canvas.height );
  54599. var th = 0;
  54600. iterateKeys( v, function ( j ) {
  54601. var h = v[ j ] * _canvas.height;
  54602. _ctx.fillStyle = _colours[ j ];
  54603. _ctx.fillRect( _canvas.width - 1, th, 1, h );
  54604. th += h;
  54605. } );
  54606. }
  54607. _init();
  54608. return {
  54609. draw: _draw
  54610. };
  54611. }
  54612. function PerfCounter ( id, group ) {
  54613. var _id = id,
  54614. _time,
  54615. _value = 0,
  54616. _total = 0,
  54617. _averageValue = 0,
  54618. _accumValue = 0,
  54619. _accumStart = performance.now(),
  54620. _accumSamples = 0,
  54621. _dom = document.createElement( 'div' ),
  54622. _spanId = document.createElement( 'span' ),
  54623. _spanValue = document.createElement( 'div' ),
  54624. _spanValueText = document.createTextNode( '' ),
  54625. _def = _settings ? _settings.values[ _id.toLowerCase() ] : null,
  54626. _graph = new Graph( _dom, _id, _def ),
  54627. _started = false;
  54628. _spanId.className = 'rs-counter-id';
  54629. _spanId.textContent = ( _def && _def.caption ) ? _def.caption : _id;
  54630. _spanValue.className = 'rs-counter-value';
  54631. _spanValue.appendChild( _spanValueText );
  54632. _dom.appendChild( _spanId );
  54633. _dom.appendChild( _spanValue );
  54634. if ( group ) group.div.appendChild( _dom );
  54635. else _div.appendChild( _dom );
  54636. _time = performance.now();
  54637. function _average ( v ) {
  54638. if ( _def && _def.average ) {
  54639. _accumValue += v;
  54640. _accumSamples++;
  54641. var t = performance.now();
  54642. if ( t - _accumStart >= ( _def.avgMs || 1000 ) ) {
  54643. _averageValue = _accumValue / _accumSamples;
  54644. _accumValue = 0;
  54645. _accumStart = t;
  54646. _accumSamples = 0;
  54647. }
  54648. }
  54649. }
  54650. function _start () {
  54651. _time = performance.now();
  54652. if( _settings.userTimingAPI ) performance.mark( _id + '-start' );
  54653. _started = true;
  54654. }
  54655. function _end () {
  54656. _value = performance.now() - _time;
  54657. if( _settings.userTimingAPI ) {
  54658. performance.mark( _id + '-end' );
  54659. if( _started ) {
  54660. performance.measure( _id, _id + '-start', _id + '-end' );
  54661. }
  54662. }
  54663. _average( _value );
  54664. }
  54665. function _tick () {
  54666. _end();
  54667. _start();
  54668. }
  54669. function _draw () {
  54670. var v = ( _def && _def.average ) ? _averageValue : _value;
  54671. _spanValueText.nodeValue = Math.round( v * 100 ) / 100;
  54672. var a = ( _def && ( ( _def.below && _value < _def.below ) || ( _def.over && _value > _def.over ) ) );
  54673. _graph.draw( _value, a );
  54674. _dom.className = a ? 'rs-counter-base alarm' : 'rs-counter-base';
  54675. }
  54676. function _frame () {
  54677. var t = performance.now();
  54678. var e = t - _time;
  54679. _total++;
  54680. if ( e > 1000 ) {
  54681. if ( _def && _def.interpolate === false ) {
  54682. _value = _total;
  54683. } else {
  54684. _value = _total * 1000 / e;
  54685. }
  54686. _total = 0;
  54687. _time = t;
  54688. _average( _value );
  54689. }
  54690. }
  54691. function _set ( v ) {
  54692. _value = v;
  54693. _average( _value );
  54694. }
  54695. return {
  54696. set: _set,
  54697. start: _start,
  54698. tick: _tick,
  54699. end: _end,
  54700. frame: _frame,
  54701. value: function () {
  54702. return _value;
  54703. },
  54704. draw: _draw
  54705. };
  54706. }
  54707. function sample () {
  54708. var _value = 0;
  54709. function _set ( v ) {
  54710. _value = v;
  54711. }
  54712. return {
  54713. set: _set,
  54714. value: function () {
  54715. return _value;
  54716. }
  54717. };
  54718. }
  54719. function _perf ( idArg ) {
  54720. var id = idArg.toLowerCase();
  54721. if ( id === undefined ) id = 'default';
  54722. if ( _perfCounters[ id ] ) return _perfCounters[ id ];
  54723. var group = null;
  54724. if ( _settings && _settings.groups ) {
  54725. iterateKeys( _settings.groups, function ( j ) {
  54726. var g = _settings.groups[ parseInt( j, 10 ) ];
  54727. if ( !group && g.values.indexOf( id.toLowerCase() ) !== -1 ) {
  54728. group = g;
  54729. }
  54730. } );
  54731. }
  54732. var p = new PerfCounter( id, group );
  54733. _perfCounters[ id ] = p;
  54734. return p;
  54735. }
  54736. function _init () {
  54737. if ( _settings.plugins ) {
  54738. if ( !_settings.values ) _settings.values = {};
  54739. if ( !_settings.groups ) _settings.groups = [];
  54740. if ( !_settings.fractions ) _settings.fractions = [];
  54741. for ( var j = 0; j < _settings.plugins.length; j++ ) {
  54742. _settings.plugins[ j ].attach( _perf );
  54743. iterateKeys( _settings.plugins[ j ].values, function ( k ) {
  54744. _settings.values[ k ] = _settings.plugins[ j ].values[ k ];
  54745. } );
  54746. _settings.groups = _settings.groups.concat( _settings.plugins[ j ].groups );
  54747. _settings.fractions = _settings.fractions.concat( _settings.plugins[ j ].fractions );
  54748. }
  54749. } else {
  54750. _settings.plugins = {};
  54751. }
  54752. _base = document.createElement( 'div' );
  54753. _base.className = 'rs-base';
  54754. _div = document.createElement( 'div' );
  54755. _div.className = 'rs-container';
  54756. _div.style.height = 'auto';
  54757. _base.appendChild( _div );
  54758. document.body.appendChild( _base );
  54759. if ( !_settings ) return;
  54760. if ( _settings.groups ) {
  54761. iterateKeys( _settings.groups, function ( j ) {
  54762. var g = _settings.groups[ parseInt( j, 10 ) ];
  54763. var div = document.createElement( 'div' );
  54764. div.className = 'rs-group';
  54765. g.div = div;
  54766. var h1 = document.createElement( 'h1' );
  54767. h1.textContent = g.caption;
  54768. h1.addEventListener( 'click', function ( e ) {
  54769. this.classList.toggle( 'hidden' );
  54770. e.preventDefault();
  54771. }.bind( div ) );
  54772. _div.appendChild( h1 );
  54773. _div.appendChild( div );
  54774. } );
  54775. }
  54776. if ( _settings.fractions ) {
  54777. iterateKeys( _settings.fractions, function ( j ) {
  54778. var f = _settings.fractions[ parseInt( j, 10 ) ];
  54779. var div = document.createElement( 'div' );
  54780. div.className = 'rs-fraction';
  54781. var legend = document.createElement( 'div' );
  54782. legend.className = 'rs-legend';
  54783. var h = 0;
  54784. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  54785. var p = document.createElement( 'p' );
  54786. p.textContent = _settings.fractions[ j ].steps[ k ];
  54787. p.style.color = _colours[ h ];
  54788. legend.appendChild( p );
  54789. h++;
  54790. } );
  54791. div.appendChild( legend );
  54792. div.style.height = h * _elHeight + 'px';
  54793. f.div = div;
  54794. var graph = new StackGraph( div, h );
  54795. f.graph = graph;
  54796. _div.appendChild( div );
  54797. } );
  54798. }
  54799. }
  54800. function _update () {
  54801. iterateKeys( _settings.plugins, function ( j ) {
  54802. _settings.plugins[ j ].update();
  54803. } );
  54804. iterateKeys( _perfCounters, function ( j ) {
  54805. _perfCounters[ j ].draw();
  54806. } );
  54807. if ( _settings && _settings.fractions ) {
  54808. iterateKeys( _settings.fractions, function ( j ) {
  54809. var f = _settings.fractions[ parseInt( j, 10 ) ];
  54810. var v = [];
  54811. var base = _perfCounters[ f.base.toLowerCase() ];
  54812. if ( base ) {
  54813. base = base.value();
  54814. iterateKeys( _settings.fractions[ j ].steps, function ( k ) {
  54815. var s = _settings.fractions[ j ].steps[ parseInt( k, 10 ) ].toLowerCase();
  54816. var val = _perfCounters[ s ];
  54817. if ( val ) {
  54818. v.push( val.value() / base );
  54819. }
  54820. } );
  54821. }
  54822. f.graph.draw( v );
  54823. } );
  54824. }
  54825. /*if( _height != _div.clientHeight ) {
  54826. _height = _div.clientHeight;
  54827. _base.style.height = _height + 2 * _elHeight + 'px';
  54828. console.log( _base.clientHeight );
  54829. }*/
  54830. }
  54831. _init();
  54832. return function ( id ) {
  54833. if ( id ) return _perf( id );
  54834. return {
  54835. element: _base,
  54836. update: _update
  54837. };
  54838. };
  54839. }
  54840. if (typeof module === 'object') {
  54841. module.exports = window.rStats;
  54842. }
  54843. },{}],176:[function(_dereq_,module,exports){
  54844. /*
  54845. * Copyright 2015 Google Inc. All Rights Reserved.
  54846. * Licensed under the Apache License, Version 2.0 (the "License");
  54847. * you may not use this file except in compliance with the License.
  54848. * You may obtain a copy of the License at
  54849. *
  54850. * http://www.apache.org/licenses/LICENSE-2.0
  54851. *
  54852. * Unless required by applicable law or agreed to in writing, software
  54853. * distributed under the License is distributed on an "AS IS" BASIS,
  54854. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  54855. * See the License for the specific language governing permissions and
  54856. * limitations under the License.
  54857. */
  54858. var Util = {};
  54859. Util.base64 = function(mimeType, base64) {
  54860. return 'data:' + mimeType + ';base64,' + base64;
  54861. };
  54862. Util.isMobile = function() {
  54863. var check = false;
  54864. (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);
  54865. return check;
  54866. };
  54867. Util.isIOS = function() {
  54868. return /(iPad|iPhone|iPod)/g.test(navigator.userAgent);
  54869. };
  54870. Util.isIFrame = function() {
  54871. try {
  54872. return window.self !== window.top;
  54873. } catch (e) {
  54874. return true;
  54875. }
  54876. };
  54877. Util.appendQueryParameter = function(url, key, value) {
  54878. // Determine delimiter based on if the URL already GET parameters in it.
  54879. var delimiter = (url.indexOf('?') < 0 ? '?' : '&');
  54880. url += delimiter + key + '=' + value;
  54881. return url;
  54882. };
  54883. // From http://goo.gl/4WX3tg
  54884. Util.getQueryParameter = function(name) {
  54885. name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  54886. var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  54887. results = regex.exec(location.search);
  54888. return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  54889. };
  54890. Util.isLandscapeMode = function() {
  54891. return (window.orientation == 90 || window.orientation == -90);
  54892. };
  54893. module.exports = Util;
  54894. },{}],177:[function(_dereq_,module,exports){
  54895. /*
  54896. * Copyright 2015 Google Inc. All Rights Reserved.
  54897. * Licensed under the Apache License, Version 2.0 (the "License");
  54898. * you may not use this file except in compliance with the License.
  54899. * You may obtain a copy of the License at
  54900. *
  54901. * http://www.apache.org/licenses/LICENSE-2.0
  54902. *
  54903. * Unless required by applicable law or agreed to in writing, software
  54904. * distributed under the License is distributed on an "AS IS" BASIS,
  54905. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  54906. * See the License for the specific language governing permissions and
  54907. * limitations under the License.
  54908. */
  54909. var Util = _dereq_('./util.js');
  54910. /**
  54911. * Android and iOS compatible wakelock implementation.
  54912. *
  54913. * Refactored thanks to dkovalev@.
  54914. */
  54915. function AndroidWakeLock() {
  54916. var video = document.createElement('video');
  54917. video.addEventListener('ended', function() {
  54918. video.play();
  54919. });
  54920. this.request = function() {
  54921. if (video.paused) {
  54922. // Base64 version of videos_src/no-sleep-60s.webm.
  54923. video.src = Util.base64('video/webm', 'GkXfowEAAAAAAAAfQoaBAUL3gQFC8oEEQvOBCEKChHdlYm1Ch4ECQoWBAhhTgGcBAAAAAAAH4xFNm3RALE27i1OrhBVJqWZTrIHfTbuMU6uEFlSua1OsggEwTbuMU6uEHFO7a1OsggfG7AEAAAAAAACkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmAQAAAAAAAEUq17GDD0JATYCNTGF2ZjU2LjQwLjEwMVdBjUxhdmY1Ni40MC4xMDFzpJAGSJTMbsLpDt/ySkipgX1fRImIQO1MAAAAAAAWVK5rAQAAAAAAADuuAQAAAAAAADLXgQFzxYEBnIEAIrWcg3VuZIaFVl9WUDmDgQEj44OEO5rKAOABAAAAAAAABrCBsLqBkB9DtnUBAAAAAAAAo+eBAKOmgQAAgKJJg0IAAV4BHsAHBIODCoAACmH2MAAAZxgz4dPSTFi5JACjloED6ACmAECSnABMQAADYAAAWi0quoCjloEH0ACmAECSnABNwAADYAAAWi0quoCjloELuACmAECSnABNgAADYAAAWi0quoCjloEPoACmAECSnABNYAADYAAAWi0quoCjloETiACmAECSnABNIAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTnghdwo5aBAAAApgBAkpwATOAAA2AAAFotKrqAo5aBA+gApgBAkpwATMAAA2AAAFotKrqAo5aBB9AApgBAkpwATIAAA2AAAFotKrqAo5aBC7gApgBAkpwATEAAA2AAAFotKrqAo5aBD6AApgDAkpwAQ2AAA2AAAFotKrqAo5aBE4gApgBAkpwATCAAA2AAAFotKrqAH0O2dQEAAAAAAACU54Iu4KOWgQAAAKYAQJKcAEvAAANgAABaLSq6gKOWgQPoAKYAQJKcAEtgAANgAABaLSq6gKOWgQfQAKYAQJKcAEsAAANgAABaLSq6gKOWgQu4AKYAQJKcAEqAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEogAANgAABaLSq6gKOWgROIAKYAQJKcAEnAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCRlCjloEAAACmAECSnABJgAADYAAAWi0quoCjloED6ACmAECSnABJIAADYAAAWi0quoCjloEH0ACmAMCSnABDYAADYAAAWi0quoCjloELuACmAECSnABI4AADYAAAWi0quoCjloEPoACmAECSnABIoAADYAAAWi0quoCjloETiACmAECSnABIYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngl3Ao5aBAAAApgBAkpwASCAAA2AAAFotKrqAo5aBA+gApgBAkpwASAAAA2AAAFotKrqAo5aBB9AApgBAkpwAR8AAA2AAAFotKrqAo5aBC7gApgBAkpwAR4AAA2AAAFotKrqAo5aBD6AApgBAkpwAR2AAA2AAAFotKrqAo5aBE4gApgBAkpwARyAAA2AAAFotKrqAH0O2dQEAAAAAAACU54J1MKOWgQAAAKYAwJKcAENgAANgAABaLSq6gKOWgQPoAKYAQJKcAEbgAANgAABaLSq6gKOWgQfQAKYAQJKcAEagAANgAABaLSq6gKOWgQu4AKYAQJKcAEaAAANgAABaLSq6gKOWgQ+gAKYAQJKcAEZAAANgAABaLSq6gKOWgROIAKYAQJKcAEYAAANgAABaLSq6gB9DtnUBAAAAAAAAlOeCjKCjloEAAACmAECSnABF4AADYAAAWi0quoCjloED6ACmAECSnABFwAADYAAAWi0quoCjloEH0ACmAECSnABFoAADYAAAWi0quoCjloELuACmAECSnABFgAADYAAAWi0quoCjloEPoACmAMCSnABDYAADYAAAWi0quoCjloETiACmAECSnABFYAADYAAAWi0quoAfQ7Z1AQAAAAAAAJTngqQQo5aBAAAApgBAkpwARUAAA2AAAFotKrqAo5aBA+gApgBAkpwARSAAA2AAAFotKrqAo5aBB9AApgBAkpwARQAAA2AAAFotKrqAo5aBC7gApgBAkpwARQAAA2AAAFotKrqAo5aBD6AApgBAkpwAROAAA2AAAFotKrqAo5aBE4gApgBAkpwARMAAA2AAAFotKrqAH0O2dQEAAAAAAACU54K7gKOWgQAAAKYAQJKcAESgAANgAABaLSq6gKOWgQPoAKYAQJKcAESAAANgAABaLSq6gKOWgQfQAKYAwJKcAENgAANgAABaLSq6gKOWgQu4AKYAQJKcAERgAANgAABaLSq6gKOWgQ+gAKYAQJKcAERAAANgAABaLSq6gKOWgROIAKYAQJKcAEQgAANgAABaLSq6gB9DtnUBAAAAAAAAlOeC0vCjloEAAACmAECSnABEIAADYAAAWi0quoCjloED6ACmAECSnABEAAADYAAAWi0quoCjloEH0ACmAECSnABD4AADYAAAWi0quoCjloELuACmAECSnABDwAADYAAAWi0quoCjloEPoACmAECSnABDoAADYAAAWi0quoCjloETiACmAECSnABDgAADYAAAWi0quoAcU7trAQAAAAAAABG7j7OBALeK94EB8YIBd/CBAw==');
  54924. video.play();
  54925. }
  54926. };
  54927. this.release = function() {
  54928. video.pause();
  54929. video.src = '';
  54930. };
  54931. }
  54932. function iOSWakeLock() {
  54933. var timer = null;
  54934. this.request = function() {
  54935. if (!timer) {
  54936. timer = setInterval(function() {
  54937. window.location = window.location;
  54938. setTimeout(window.stop, 0);
  54939. }, 30000);
  54940. }
  54941. }
  54942. this.release = function() {
  54943. if (timer) {
  54944. clearInterval(timer);
  54945. timer = null;
  54946. }
  54947. }
  54948. }
  54949. function getWakeLock() {
  54950. var userAgent = navigator.userAgent || navigator.vendor || window.opera;
  54951. if (userAgent.match(/iPhone/i) || userAgent.match(/iPod/i)) {
  54952. return iOSWakeLock;
  54953. } else {
  54954. return AndroidWakeLock;
  54955. }
  54956. }
  54957. module.exports = getWakeLock();
  54958. },{"./util.js":176}]},{},[144])(144)
  54959. });
  54960. //# sourceMappingURL=aframe-master.js.map